source: src/FunctionApproximation/Extractors.cpp@ 67044a

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 67044a was 67044a, checked in by Frederik Heber <heber@…>, 9 years ago

Extractors require additional binding model which EmpiricalPotentials supply in getSpecificFilter().

  • Property mode set to 100644
File size: 16.3 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
56#include "Fragmentation/Homology/HomologyGraph.hpp"
57
58using namespace boost::assign;
59
60FunctionModel::arguments_t
61Extractors::gatherAllSymmetricDistanceArguments(
62 const Fragment::positions_t& positions,
63 const Fragment::atomicnumbers_t& atomicnumbers,
64 const size_t globalid)
65{
66 FunctionModel::arguments_t result;
67
68 // go through current configuration and gather all other distances
69 Fragment::positions_t::const_iterator firstpositer = positions.begin();
70 for (;firstpositer != positions.end(); ++firstpositer) {
71 Fragment::positions_t::const_iterator secondpositer = firstpositer;
72 for (; secondpositer != positions.end(); ++secondpositer) {
73 if (firstpositer == secondpositer)
74 continue;
75 argument_t arg;
76 const Vector firsttemp((*firstpositer)[0],(*firstpositer)[1],(*firstpositer)[2]);
77 const Vector secondtemp((*secondpositer)[0],(*secondpositer)[1],(*secondpositer)[2]);
78 arg.distance = firsttemp.distance(secondtemp);
79 arg.types = std::make_pair(
80 (int)atomicnumbers[ std::distance(positions.begin(), firstpositer) ],
81 (int)atomicnumbers[ std::distance(positions.begin(), secondpositer) ]
82 );
83 arg.indices = std::make_pair(
84 std::distance(
85 positions.begin(), firstpositer),
86 std::distance(
87 positions.begin(), secondpositer)
88 );
89 arg.globalid = globalid;
90 LOG(3, "DEBUG: Created argument " << arg << ".");
91 result.push_back(arg);
92 }
93 }
94
95 return result;
96}
97
98Extractors::elementcounts_t
99Extractors::_detail::getElementCounts(
100 const Fragment::atomicnumbers_t elements
101 )
102{
103 elementcounts_t elementcounts;
104 for (Fragment::atomicnumbers_t::const_iterator elementiter = elements.begin();
105 elementiter != elements.end(); ++elementiter) {
106 // insert new element
107 std::pair< elementcounts_t::iterator, bool> inserter =
108 elementcounts.insert( std::make_pair( *elementiter, 1) );
109 // if already present, just increase its count
110 if (!inserter.second)
111 ++(inserter.first->second);
112 }
113 return elementcounts;
114}
115
116struct ParticleTypesComparator {
117 bool operator()(const argument_t::types_t &a, const argument_t::types_t &b)
118 {
119 if (a.first < a.second) {
120 if (b.first < b.second) {
121 if (a.first < b.first)
122 return true;
123 else if (a.first > b.first)
124 return false;
125 else
126 return (a.second < b.second);
127 } else {
128 if (a.first < b.second)
129 return true;
130 else if (a.first > b.second)
131 return false;
132 else
133 return (a.second < b.first);
134 }
135 } else {
136 if (b.first < b.second) {
137 if (a.second < b.first)
138 return true;
139 else if (a.second > b.first)
140 return false;
141 else
142 return (a.first < b.second);
143 } else {
144 if (a.second < b.second)
145 return true;
146 else if (a.second > b.second)
147 return false;
148 else
149 return (a.first < b.first);
150 }
151 }
152 }
153};
154
155std::ostream& operator<<(std::ostream &out, const argument_t::types_t &a)
156{
157 out << "[" << a.first << "," << a.second << "]";
158 return out;
159}
160
161FunctionModel::list_of_arguments_t Extractors::reorderArgumentsByParticleTypes(
162 const FunctionModel::list_of_arguments_t &listargs,
163 const ParticleTypes_t &_types,
164 const HomologyGraph &_bindingmodel
165 )
166{
167 FunctionModel::list_of_arguments_t returnargs;
168 for (FunctionModel::list_of_arguments_t::const_iterator iter = listargs.begin();
169 iter != listargs.end(); ++iter) {
170 const FunctionModel::arguments_t &args = *iter;
171 /// We place all arguments into multimap according to particle type pair.
172 // here, we need a special comparator such that types in key pair are always
173 // properly ordered.
174 typedef std::multimap<
175 argument_t::types_t,
176 argument_t,
177 ParticleTypesComparator> TypePair_Argument_Map_t;
178 TypePair_Argument_Map_t argument_map;
179 for(FunctionModel::arguments_t::const_iterator iter = args.begin();
180 iter != args.end(); ++iter) {
181 argument_map.insert( std::make_pair(iter->types, *iter) );
182 }
183 LOG(4, "DEBUG: particle_type map is " << argument_map << ".");
184
185 /// Then, we create the desired unique keys
186 typedef std::vector<argument_t::types_t> UniqueTypes_t;
187 UniqueTypes_t UniqueTypes;
188 for (ParticleTypes_t::const_iterator firstiter = _types.begin();
189 firstiter != _types.end();
190 ++firstiter) {
191 for (ParticleTypes_t::const_iterator seconditer = firstiter;
192 seconditer != _types.end();
193 ++seconditer) {
194 if (seconditer == firstiter)
195 continue;
196 UniqueTypes.push_back( std::make_pair(*firstiter, *seconditer) );
197 }
198 }
199 LOG(4, "DEBUG: Created unique types as keys " << UniqueTypes << ".");
200
201 /// Finally, we use the unique key list to pick corresponding arguments from the map
202 FunctionModel::arguments_t sortedargs;
203 sortedargs.reserve(args.size());
204 while (!argument_map.empty()) {
205 // note that particle_types_t may be flipped, i.e. 1,8 is equal to 8,1, but we
206 // must maintain the correct order in indices in accordance with the order
207 // in _types, i.e. 1,8,1 must match with e.g. ids 1,0,2 where 1 has type 1,
208 // 0 has type 8, and 2 has type 2.
209 // In other words: We do not want to flip/modify arguments such that they match
210 // with the specific type pair we seek but then this comes at the price that we
211 // have flip indices when the types in a pair are flipped.
212
213 typedef std::vector<size_t> indices_t;
214 //!> here, we gather the indices as we discover them
215 indices_t indices;
216 indices.resize(_types.size(), (size_t)-1);
217
218 // these are two iterators that create index pairs in the same way as we have
219 // created type pairs. If a -1 is still present in indices, then the index is
220 // still arbitrary but is then set by the next found index
221 indices_t::iterator firstindex = indices.begin();
222 indices_t::iterator secondindex = firstindex+1;
223
224 //!> here, we gather the current bunch of arguments as we find them
225 FunctionModel::arguments_t argumentbunch;
226 argumentbunch.reserve(UniqueTypes.size());
227
228 for (UniqueTypes_t::const_iterator typeiter = UniqueTypes.begin();
229 typeiter != UniqueTypes.end(); ++typeiter) {
230 // have all arguments to same type pair as list within the found range
231 std::pair<
232 TypePair_Argument_Map_t::iterator,
233 TypePair_Argument_Map_t::iterator> range_t =
234 argument_map.equal_range(*typeiter);
235 LOG(4, "DEBUG: Set of arguments to current key [" << typeiter->first << ","
236 << typeiter->second << "] is " << std::list<argument_t>(
237 MapValueIterator<TypePair_Argument_Map_t::iterator>(range_t.first),
238 MapValueIterator<TypePair_Argument_Map_t::iterator>(range_t.second)
239 ) << ".");
240 // the first key is always easy and is pivot which the rest has to be associated to
241 if (typeiter == UniqueTypes.begin()) {
242 const argument_t & arg = range_t.first->second;
243 if ((typeiter->first == arg.types.first) && (typeiter->second == arg.types.second)) {
244 // store in correct order
245 *firstindex = arg.indices.first;
246 *secondindex = arg.indices.second;
247 } else {
248 // store in flipped order
249 *firstindex = arg.indices.second;
250 *secondindex = arg.indices.first;
251 }
252 argumentbunch.push_back(arg);
253 argument_map.erase(range_t.first);
254 LOG(4, "DEBUG: Gathered first argument " << arg << ".");
255 } else {
256 // go through the range and pick the first argument matching the index constraints
257 for (TypePair_Argument_Map_t::iterator argiter = range_t.first;
258 argiter != range_t.second; ++argiter) {
259 // seconditer may be -1 still
260 const argument_t &arg = argiter->second;
261 if (arg.indices.first == *firstindex) {
262 if ((arg.indices.second == *secondindex) || (*secondindex == (size_t)-1)) {
263 if (*secondindex == (size_t)-1)
264 *secondindex = arg.indices.second;
265 argumentbunch.push_back(arg);
266 argument_map.erase(argiter);
267 LOG(4, "DEBUG: Gathered another argument " << arg << ".");
268 break;
269 }
270 } else if ((arg.indices.first == *secondindex) || (*secondindex == (size_t)-1)) {
271 if (arg.indices.second == *firstindex) {
272 if (*secondindex == (size_t)-1)
273 *secondindex = arg.indices.first;
274 argumentbunch.push_back(arg);
275 argument_map.erase(argiter);
276 LOG(4, "DEBUG: Gathered another (flipped) argument " << arg << ".");
277 break;
278 }
279 }
280 }
281 }
282 // move along in indices and check bounds
283 ++secondindex;
284 if (secondindex == indices.end()) {
285 ++firstindex;
286 if (firstindex != indices.end()-1)
287 secondindex = firstindex+1;
288 }
289 }
290 ASSERT( (firstindex == indices.end()-1) && (secondindex == indices.end()),
291 "Extractors::reorderArgumentsByParticleTypes() - we have not gathered enough arguments.");
292 ASSERT( argumentbunch.size() == UniqueTypes.size(),
293 "Extractors::reorderArgumentsByParticleTypes() - we have not gathered enough arguments.");
294 // place bunch of arguments in return args
295 LOG(3, "DEBUG: Given types " << _types << " and found indices " << indices << ".");
296 LOG(3, "DEBUG: Final bunch of arguments is " << argumentbunch << ".");
297 sortedargs.insert(sortedargs.end(), argumentbunch.begin(), argumentbunch.end());
298 }
299 returnargs.push_back(sortedargs);
300 }
301
302 return returnargs;
303}
304
305FunctionModel::list_of_arguments_t Extractors::filterArgumentsByParticleTypes(
306 const FunctionModel::arguments_t &args,
307 const ParticleTypes_t &_types,
308 const HomologyGraph &_bindingmodel
309 )
310{
311 typedef std::list< argument_t > ListArguments_t;
312 ListArguments_t availableList(args.begin(), args.end());
313 LOG(2, "DEBUG: Initial list of args is " << args << ".");
314
315
316 // TODO: fill a lookup map such that we don't have O(M^3) scaling, if M is number
317 // of types (and we always must have M(M-1)/2 args) but O(M^2 log(M)). However, as
318 // M is very small (<=3), this is not necessary fruitful now.
319// typedef ParticleTypes_t firsttype;
320// typedef ParticleTypes_t secondtype;
321// typedef std::map< firsttype, std::map< secondtype, boost::ref(args) > > ArgsLookup_t;
322// ArgsLookup_t ArgsLookup;
323
324 // basically, we have two choose any two pairs out of types but only those
325 // where the first is less than the latter. Hence, we start the second
326 // iterator at the current position of the first one and skip the equal case.
327 FunctionModel::arguments_t allargs;
328 allargs.reserve(args.size());
329 for (ParticleTypes_t::const_iterator firstiter = _types.begin();
330 firstiter != _types.end();
331 ++firstiter) {
332 for (ParticleTypes_t::const_iterator seconditer = firstiter;
333 seconditer != _types.end();
334 ++seconditer) {
335 if (seconditer == firstiter)
336 continue;
337 LOG(3, "DEBUG: Looking for (" << *firstiter << "," << *seconditer << ") in all args.");
338
339 // search the right one in _args (we might allow switching places of
340 // firstiter and seconditer, as distance is symmetric).
341 ListArguments_t::iterator iter = availableList.begin();
342 while (iter != availableList.end()) {
343 LOG(4, "DEBUG: Current args is " << *iter << ".");
344 if ((iter->types.first == *firstiter)
345 && (iter->types.second == *seconditer)) {
346 allargs.push_back( *iter );
347 iter = availableList.erase(iter);
348 LOG(4, "DEBUG: Accepted argument.");
349 } else if ((iter->types.first == *seconditer)
350 && (iter->types.second == *firstiter)) {
351 allargs.push_back( *iter );
352 iter = availableList.erase(iter);
353 LOG(4, "DEBUG: Accepted (flipped) argument.");
354 } else {
355 ++iter;
356 LOG(4, "DEBUG: Rejected argument.");
357 }
358 }
359 }
360 }
361 LOG(2, "DEBUG: Final list of args is " << allargs << ".");
362
363 // first, we bring together tuples of distances that belong together
364 FunctionModel::list_of_arguments_t singlelist_allargs;
365 singlelist_allargs.push_back(allargs);
366 FunctionModel::list_of_arguments_t sortedargs =
367 reorderArgumentsByParticleTypes(singlelist_allargs, _types, _bindingmodel);
368 ASSERT( sortedargs.size() == (size_t)1,
369 "Extractors::filterArgumentsByParticleTypes() - reordering did not generate a single list.");
370 // then we split up the tuples of arguments and place each into single list
371 FunctionModel::list_of_arguments_t returnargs;
372 FunctionModel::arguments_t::const_iterator argiter = sortedargs.begin()->begin();
373 const size_t num_types = _types.size();
374 const size_t args_per_tuple = num_types * (num_types-1) / 2;
375 while (argiter != sortedargs.begin()->end()) {
376 FunctionModel::arguments_t currenttuple(args_per_tuple);
377 const FunctionModel::arguments_t::const_iterator startiter = argiter;
378 std::advance(argiter, args_per_tuple);
379#ifndef NDEBUG
380 FunctionModel::arguments_t::const_iterator endoutiter =
381#endif
382 std::copy(startiter, argiter, currenttuple.begin());
383 ASSERT( endoutiter == currenttuple.end(),
384 "Extractors::filterArgumentsByParticleTypes() - currenttuple not initialized to right size.");
385 returnargs.push_back(currenttuple);
386 }
387
388 LOG(2, "DEBUG: We have generated " << returnargs.size() << " tuples of distances.");
389
390 return returnargs;
391}
392
393
394FunctionModel::arguments_t Extractors::combineArguments(
395 const FunctionModel::arguments_t &firstargs,
396 const FunctionModel::arguments_t &secondargs)
397{
398 FunctionModel::arguments_t args = concatenateArguments(firstargs, secondargs);
399 std::sort(args.begin(), args.end(),
400 boost::bind(&argument_t::operator<, _1, _2));
401 FunctionModel::arguments_t::iterator iter =
402 std::unique(args.begin(), args.end(),
403 boost::bind(&argument_t::operator==, _1, _2));
404 args.erase(iter, args.end());
405 return args;
406}
407
408FunctionModel::arguments_t Extractors::concatenateArguments(
409 const FunctionModel::arguments_t &firstargs,
410 const FunctionModel::arguments_t &secondargs)
411{
412 FunctionModel::arguments_t args(firstargs);
413 args.insert(args.end(), secondargs.begin(), secondargs.end());
414 return args;
415}
416
417FunctionModel::list_of_arguments_t Extractors::concatenateListOfArguments(
418 const FunctionModel::list_of_arguments_t &firstlistargs,
419 const FunctionModel::list_of_arguments_t &secondlistargs)
420{
421 FunctionModel::list_of_arguments_t listargs(firstlistargs);
422 listargs.insert(listargs.end(), secondlistargs.begin(), secondlistargs.end());
423 return listargs;
424}
Note: See TracBrowser for help on using the repository browser.