source: src/FunctionApproximation/Extractors.cpp@ 6cfb22a

Fix_FitPotential_needs_atomicnumbers
Last change on this file since 6cfb22a was fc08c7, checked in by Frederik Heber <heber@…>, 9 years ago

ATTEMPT: Tried to add all subgraph in graph finding to Extractors::reorderArg..().

  • Property mode set to 100644
File size: 18.9 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 * Please see the COPYING file or "Copyright notice" in builder.cpp for details.
7 *
8 *
9 * This file is part of MoleCuilder.
10 *
11 * MoleCuilder is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * MoleCuilder is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
23 */
24
25/*
26 * Extractors.cpp
27 *
28 * Created on: 15.10.2012
29 * Author: heber
30 */
31
32// include config.h
33#ifdef HAVE_CONFIG_H
34#include <config.h>
35#endif
36
37#include "CodePatterns/MemDebug.hpp"
38
39#include <sstream>
40#include <utility>
41#include <vector>
42#include <boost/assign.hpp>
43#include <boost/bind.hpp>
44#include <boost/foreach.hpp>
45
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/IteratorAdaptors.hpp"
48#include "CodePatterns/Log.hpp"
49#include "CodePatterns/toString.hpp"
50
51#include "LinearAlgebra/Vector.hpp"
52
53#include "FunctionApproximation/Extractors.hpp"
54#include "FunctionApproximation/FunctionArgument.hpp"
55
56using namespace boost::assign;
57
58FunctionModel::arguments_t
59Extractors::gatherAllSymmetricDistanceArguments(
60 const Fragment::positions_t& positions,
61 const Fragment::atomicnumbers_t& atomicnumbers,
62 const size_t globalid)
63{
64 FunctionModel::arguments_t result;
65
66 // go through current configuration and gather all other distances
67 Fragment::positions_t::const_iterator firstpositer = positions.begin();
68 for (;firstpositer != positions.end(); ++firstpositer) {
69 Fragment::positions_t::const_iterator secondpositer = firstpositer;
70 for (; secondpositer != positions.end(); ++secondpositer) {
71 if (firstpositer == secondpositer)
72 continue;
73 argument_t arg;
74 const Vector firsttemp((*firstpositer)[0],(*firstpositer)[1],(*firstpositer)[2]);
75 const Vector secondtemp((*secondpositer)[0],(*secondpositer)[1],(*secondpositer)[2]);
76 arg.distance = firsttemp.distance(secondtemp);
77 arg.types = std::make_pair(
78 (int)atomicnumbers[ std::distance(positions.begin(), firstpositer) ],
79 (int)atomicnumbers[ std::distance(positions.begin(), secondpositer) ]
80 );
81 arg.indices = std::make_pair(
82 std::distance(
83 positions.begin(), firstpositer),
84 std::distance(
85 positions.begin(), secondpositer)
86 );
87 arg.globalid = globalid;
88 LOG(3, "DEBUG: Created argument " << arg << ".");
89 result.push_back(arg);
90 }
91 }
92
93 return result;
94}
95
96Extractors::elementcounts_t
97Extractors::_detail::getElementCounts(
98 const Fragment::atomicnumbers_t elements
99 )
100{
101 elementcounts_t elementcounts;
102 for (Fragment::atomicnumbers_t::const_iterator elementiter = elements.begin();
103 elementiter != elements.end(); ++elementiter) {
104 // insert new element
105 std::pair< elementcounts_t::iterator, bool> inserter =
106 elementcounts.insert( std::make_pair( *elementiter, 1) );
107 // if already present, just increase its count
108 if (!inserter.second)
109 ++(inserter.first->second);
110 }
111 return elementcounts;
112}
113
114struct ParticleTypesComparator {
115 bool operator()(const argument_t::types_t &a, const argument_t::types_t &b)
116 {
117 if (a.first < a.second) {
118 if (b.first < b.second) {
119 if (a.first < b.first)
120 return true;
121 else if (a.first > b.first)
122 return false;
123 else
124 return (a.second < b.second);
125 } else {
126 if (a.first < b.second)
127 return true;
128 else if (a.first > b.second)
129 return false;
130 else
131 return (a.second < b.first);
132 }
133 } else {
134 if (b.first < b.second) {
135 if (a.second < b.first)
136 return true;
137 else if (a.second > b.first)
138 return false;
139 else
140 return (a.first < b.second);
141 } else {
142 if (a.second < b.second)
143 return true;
144 else if (a.second > b.second)
145 return false;
146 else
147 return (a.first < b.first);
148 }
149 }
150 }
151};
152
153std::ostream& operator<<(std::ostream &out, const argument_t::types_t &a)
154{
155 out << "[" << a.first << "," << a.second << "]";
156 return out;
157}
158
159static std::vector<PotentialGraph>
160findSubgraphsInPotentialGraph(const PotentialGraph &_graph, const PotentialGraph &_subgraph)
161{
162 std::vector<PotentialGraph> list_of_subgraphs;
163
164 return list_of_subgraphs;
165}
166
167
168FunctionModel::list_of_arguments_t Extractors::reorderArgumentsByParticleTypes(
169 const FunctionModel::list_of_arguments_t &listargs,
170 const ParticleTypes_t &_types,
171 const PotentialGraph &_subgraph
172 )
173{
174 FunctionModel::list_of_arguments_t returnargs;
175 for (FunctionModel::list_of_arguments_t::const_iterator iter = listargs.begin();
176 iter != listargs.end(); ++iter) {
177 const FunctionModel::arguments_t &args = *iter;
178 /// We place all arguments into multimap according to particle type pair.
179 // here, we need a special comparator such that types in key pair are always
180 // properly ordered.
181 typedef std::multimap<
182 argument_t::types_t,
183 argument_t,
184 ParticleTypesComparator> TypePair_Argument_Map_t;
185 TypePair_Argument_Map_t argument_map;
186 for(FunctionModel::arguments_t::const_iterator iter = args.begin();
187 iter != args.end(); ++iter) {
188 argument_map.insert( std::make_pair(iter->types, *iter) );
189 }
190 LOG(4, "DEBUG: particle_type map is " << argument_map << ".");
191
192 /// Then, we create the desired unique keys
193 typedef std::vector<argument_t::types_t> UniqueTypes_t;
194 UniqueTypes_t UniqueTypes;
195 for (ParticleTypes_t::const_iterator firstiter = _types.begin();
196 firstiter != _types.end();
197 ++firstiter) {
198 for (ParticleTypes_t::const_iterator seconditer = firstiter;
199 seconditer != _types.end();
200 ++seconditer) {
201 if (seconditer == firstiter)
202 continue;
203 UniqueTypes.push_back( std::make_pair(*firstiter, *seconditer) );
204 }
205 }
206 LOG(4, "DEBUG: Created unique types as keys " << UniqueTypes << ".");
207
208 /// take the (filtered) list of args and convert into graph
209 PotentialGraph fragmentgraph;
210 for(FunctionModel::arguments_t::const_iterator iter = args.begin();
211 iter != args.end(); ++iter)
212 fragmentgraph.add_edge( static_cast<const SubgraphEdge&>(*iter));
213
214 /// find all subgraphs to the given potential subgraph
215 std::vector<PotentialGraph > list_of_subgraphs =
216 findSubgraphsInPotentialGraph(fragmentgraph, _subgraph);
217
218 /// convert into tuples with each subgraph sorted by _types
219
220// /// turn fragment into graph from the known edges
221// boost::adjacency_list<> fragmentgraph(_types.size());
222// boost::property_map < boost::adjacency_list <>, ParticleType_t > types_map;
223// typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;
224// typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;
225// for(FunctionModel::arguments_t::const_iterator iter = args.begin();
226// iter != args.end(); ++iter) {
227// std::pair<Edge, bool> inserter =
228// boost::add_edge(iter->indices.first, iter->indices.second, fragmentgraph);
229// ASSERT( inserter.second,
230// "Extractors::reorderArgumentsByParticleTypes() - cannot insert edge between "
231// +toString(iter->indices.first)+" and "+toString(iter->indices.second));
232// // add type to property map
233// Vertex u = boost::source(inserter.first,fragmentgraph);
234// boost::put(types_map, u, iter->types.first);
235// Vertex v = boost::source(inserter.first,fragmentgraph);
236// boost::put(types_map, v, iter->types.second);
237// }
238// // create property map with index
239// boost::property_map < boost::adjacency_list <>, boost::vertex_index_t >::type
240// index_map = boost::get(boost::vertex_index, fragmentgraph);
241//
242// // use list of types to obtain all possible candidate graphs
243//
244// // compare candidate graph with potential's subgraph
245//
246// // ensure uniqueness of candidate graphs
247//
248// // step through every vertex
249// boost::graph_traits < boost::adjacency_list <> >::vertex_iterator i, end;
250// for (boost::tie(i, end) = boost::vertices(fragmentgraph); i != end; ++i) {
251// // step through every adjacent vertex
252// boost::graph_traits < boost::adjacency_list <> >::adjacency_iterator ai, a_end;
253// boost::tie(ai, a_end) = boost::adjacent_vertices(*i, fragmentgraph);
254// for (; ai != a_end; ++ai) {
255// // look ahead at next vertex
256// if (boost::next(ai) != a_end) {}
257// }
258// }
259
260 /// Finally, we use the unique key list to pick corresponding arguments from the map
261 FunctionModel::arguments_t sortedargs;
262 sortedargs.reserve(args.size());
263 while (!argument_map.empty()) {
264 // note that particle_types_t may be flipped, i.e. 1,8 is equal to 8,1, but we
265 // must maintain the correct order in indices in accordance with the order
266 // in _types, i.e. 1,8,1 must match with e.g. ids 1,0,2 where 1 has type 1,
267 // 0 has type 8, and 2 has type 2.
268 // In other words: We do not want to flip/modify arguments such that they match
269 // with the specific type pair we seek but then this comes at the price that we
270 // have flip indices when the types in a pair are flipped.
271
272 typedef std::vector<size_t> indices_t;
273 //!> here, we gather the indices as we discover them
274 indices_t indices;
275 indices.resize(_types.size(), (size_t)-1);
276
277 // these are two iterators that create index pairs in the same way as we have
278 // created type pairs. If a -1 is still present in indices, then the index is
279 // still arbitrary but is then set by the next found index
280 indices_t::iterator firstindex = indices.begin();
281 indices_t::iterator secondindex = firstindex+1;
282
283 //!> here, we gather the current bunch of arguments as we find them
284 FunctionModel::arguments_t argumentbunch;
285 argumentbunch.reserve(UniqueTypes.size());
286
287 for (UniqueTypes_t::const_iterator typeiter = UniqueTypes.begin();
288 typeiter != UniqueTypes.end(); ++typeiter) {
289 // have all arguments to same type pair as list within the found range
290 std::pair<
291 TypePair_Argument_Map_t::iterator,
292 TypePair_Argument_Map_t::iterator> range_t =
293 argument_map.equal_range(*typeiter);
294 LOG(4, "DEBUG: Set of arguments to current key [" << typeiter->first << ","
295 << typeiter->second << "] is " << std::list<argument_t>(
296 MapValueIterator<TypePair_Argument_Map_t::iterator>(range_t.first),
297 MapValueIterator<TypePair_Argument_Map_t::iterator>(range_t.second)
298 ) << ".");
299 // the first key is always easy and is pivot which the rest has to be associated to
300 if (typeiter == UniqueTypes.begin()) {
301 const argument_t & arg = range_t.first->second;
302 if ((typeiter->first == arg.types.first) && (typeiter->second == arg.types.second)) {
303 // store in correct order
304 *firstindex = arg.indices.first;
305 *secondindex = arg.indices.second;
306 } else {
307 // store in flipped order
308 *firstindex = arg.indices.second;
309 *secondindex = arg.indices.first;
310 }
311 argumentbunch.push_back(arg);
312 argument_map.erase(range_t.first);
313 LOG(4, "DEBUG: Gathered first argument " << arg << ".");
314 } else {
315 // go through the range and pick the first argument matching the index constraints
316 for (TypePair_Argument_Map_t::iterator argiter = range_t.first;
317 argiter != range_t.second; ++argiter) {
318 // seconditer may be -1 still
319 const argument_t &arg = argiter->second;
320 if (arg.indices.first == *firstindex) {
321 if ((arg.indices.second == *secondindex) || (*secondindex == (size_t)-1)) {
322 if (*secondindex == (size_t)-1)
323 *secondindex = arg.indices.second;
324 argumentbunch.push_back(arg);
325 argument_map.erase(argiter);
326 LOG(4, "DEBUG: Gathered another argument " << arg << ".");
327 break;
328 }
329 } else if ((arg.indices.first == *secondindex) || (*secondindex == (size_t)-1)) {
330 if (arg.indices.second == *firstindex) {
331 if (*secondindex == (size_t)-1)
332 *secondindex = arg.indices.first;
333 argumentbunch.push_back(arg);
334 argument_map.erase(argiter);
335 LOG(4, "DEBUG: Gathered another (flipped) argument " << arg << ".");
336 break;
337 }
338 }
339 }
340 }
341 // move along in indices and check bounds
342 ++secondindex;
343 if (secondindex == indices.end()) {
344 ++firstindex;
345 if (firstindex != indices.end()-1)
346 secondindex = firstindex+1;
347 }
348 }
349 ASSERT( (firstindex == indices.end()-1) && (secondindex == indices.end()),
350 "Extractors::reorderArgumentsByParticleTypes() - we have not gathered enough arguments.");
351 ASSERT( argumentbunch.size() == UniqueTypes.size(),
352 "Extractors::reorderArgumentsByParticleTypes() - we have not gathered enough arguments.");
353 // place bunch of arguments in return args
354 LOG(3, "DEBUG: Given types " << _types << " and found indices " << indices << ".");
355 LOG(3, "DEBUG: Final bunch of arguments is " << argumentbunch << ".");
356 sortedargs.insert(sortedargs.end(), argumentbunch.begin(), argumentbunch.end());
357 }
358 returnargs.push_back(sortedargs);
359 }
360
361 return returnargs;
362}
363
364FunctionModel::list_of_arguments_t Extractors::filterArgumentsByParticleTypes(
365 const FunctionModel::arguments_t &args,
366 const ParticleTypes_t &_types,
367 const PotentialGraph &_subgraph
368 )
369{
370 typedef std::list< argument_t > ListArguments_t;
371 ListArguments_t availableList(args.begin(), args.end());
372 LOG(2, "DEBUG: Initial list of args is " << args << ".");
373
374
375 // TODO: fill a lookup map such that we don't have O(M^3) scaling, if M is number
376 // of types (and we always must have M(M-1)/2 args) but O(M^2 log(M)). However, as
377 // M is very small (<=3), this is not necessary fruitful now.
378// typedef ParticleTypes_t firsttype;
379// typedef ParticleTypes_t secondtype;
380// typedef std::map< firsttype, std::map< secondtype, boost::ref(args) > > ArgsLookup_t;
381// ArgsLookup_t ArgsLookup;
382
383 // basically, we have two choose any two pairs out of types but only those
384 // where the first is less than the latter. Hence, we start the second
385 // iterator at the current position of the first one and skip the equal case.
386 FunctionModel::arguments_t allargs;
387 allargs.reserve(args.size());
388 for (ParticleTypes_t::const_iterator firstiter = _types.begin();
389 firstiter != _types.end();
390 ++firstiter) {
391 for (ParticleTypes_t::const_iterator seconditer = firstiter;
392 seconditer != _types.end();
393 ++seconditer) {
394 if (seconditer == firstiter)
395 continue;
396 LOG(3, "DEBUG: Looking for (" << *firstiter << "," << *seconditer << ") in all args.");
397
398 // search the right one in _args (we might allow switching places of
399 // firstiter and seconditer, as distance is symmetric).
400 ListArguments_t::iterator iter = availableList.begin();
401 while (iter != availableList.end()) {
402 LOG(4, "DEBUG: Current args is " << *iter << ".");
403 if ((iter->types.first == *firstiter)
404 && (iter->types.second == *seconditer)) {
405 allargs.push_back( *iter );
406 iter = availableList.erase(iter);
407 LOG(4, "DEBUG: Accepted argument.");
408 } else if ((iter->types.first == *seconditer)
409 && (iter->types.second == *firstiter)) {
410 allargs.push_back( *iter );
411 iter = availableList.erase(iter);
412 LOG(4, "DEBUG: Accepted (flipped) argument.");
413 } else {
414 ++iter;
415 LOG(4, "DEBUG: Rejected argument.");
416 }
417 }
418 }
419 }
420 LOG(2, "DEBUG: Final list of args is " << allargs << ".");
421
422 // first, we bring together tuples of distances that belong together
423 FunctionModel::list_of_arguments_t singlelist_allargs;
424 singlelist_allargs.push_back(allargs);
425 FunctionModel::list_of_arguments_t sortedargs =
426 reorderArgumentsByParticleTypes(singlelist_allargs, _types, _subgraph);
427 ASSERT( sortedargs.size() == (size_t)1,
428 "Extractors::filterArgumentsByParticleTypes() - reordering did not generate a single list.");
429 // then we split up the tuples of arguments and place each into single list
430 FunctionModel::list_of_arguments_t returnargs;
431 FunctionModel::arguments_t::const_iterator argiter = sortedargs.begin()->begin();
432 const size_t num_types = _types.size();
433 const size_t args_per_tuple = num_types * (num_types-1) / 2;
434 while (argiter != sortedargs.begin()->end()) {
435 FunctionModel::arguments_t currenttuple(args_per_tuple);
436 const FunctionModel::arguments_t::const_iterator startiter = argiter;
437 std::advance(argiter, args_per_tuple);
438#ifndef NDEBUG
439 FunctionModel::arguments_t::const_iterator endoutiter =
440#endif
441 std::copy(startiter, argiter, currenttuple.begin());
442 ASSERT( endoutiter == currenttuple.end(),
443 "Extractors::filterArgumentsByParticleTypes() - currenttuple not initialized to right size.");
444 returnargs.push_back(currenttuple);
445 }
446
447 LOG(2, "DEBUG: We have generated " << returnargs.size() << " tuples of distances.");
448
449 return returnargs;
450}
451
452
453FunctionModel::arguments_t Extractors::combineArguments(
454 const FunctionModel::arguments_t &firstargs,
455 const FunctionModel::arguments_t &secondargs)
456{
457 FunctionModel::arguments_t args = concatenateArguments(firstargs, secondargs);
458 std::sort(args.begin(), args.end(),
459 boost::bind(&argument_t::operator<, _1, _2));
460 FunctionModel::arguments_t::iterator iter =
461 std::unique(args.begin(), args.end(),
462 boost::bind(&argument_t::operator==, _1, _2));
463 args.erase(iter, args.end());
464 return args;
465}
466
467FunctionModel::arguments_t Extractors::concatenateArguments(
468 const FunctionModel::arguments_t &firstargs,
469 const FunctionModel::arguments_t &secondargs)
470{
471 FunctionModel::arguments_t args(firstargs);
472 args.insert(args.end(), secondargs.begin(), secondargs.end());
473 return args;
474}
475
476FunctionModel::list_of_arguments_t Extractors::concatenateListOfArguments(
477 const FunctionModel::list_of_arguments_t &firstlistargs,
478 const FunctionModel::list_of_arguments_t &secondlistargs)
479{
480 FunctionModel::list_of_arguments_t listargs(firstlistargs);
481 listargs.insert(listargs.end(), secondlistargs.begin(), secondlistargs.end());
482 return listargs;
483}
Note: See TracBrowser for help on using the repository browser.