source: src/FunctionApproximation/Extractors.cpp@ e47ac7

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 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 e47ac7 was e47ac7, checked in by Frederik Heber <heber@…>, 9 years ago

REFACTOR: Removed many unused functions from Extractor namespace.

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