source: src/Potentials/CompoundPotential.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 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 c5e75f3, checked in by Frederik Heber <heber@…>, 8 years ago

ParticleType_t is now an unsigned int.

  • this allows direct use of atomicNumber_t and also signed integers dont' make much sense for a particle type, i.e. an id.
  • Property mode set to 100644
File size: 18.3 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * CompoundPotential.cpp
26 *
27 * Created on: May 8, 2013
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "Potentials/CompoundPotential.hpp"
39
40#include <algorithm>
41#include <boost/bind.hpp>
42#include <boost/foreach.hpp>
43#include <boost/lambda/lambda.hpp>
44#include <iterator>
45#include <numeric>
46
47#include "CodePatterns/Assert.hpp"
48#include "CodePatterns/Log.hpp"
49
50#include "Element/element.hpp"
51#include "Fragmentation/Homology/HomologyGraph.hpp"
52#include "Fragmentation/Summation/SetValues/Fragment.hpp"
53#include "FunctionApproximation/Extractors.hpp"
54#include "Potentials/EmpiricalPotential.hpp"
55#include "Potentials/helpers.hpp"
56#include "Potentials/PotentialRegistry.hpp"
57
58
59CompoundPotential::CompoundPotential(const HomologyGraph &graph)
60{
61 LOG(1, "INFO: Creating CompoundPotential for graph " << graph << ".");
62 // look though graph and place all matching FunctionModel's in
63 // PotentialRegistry in models
64 PotentialRegistry::const_iterator potentialiter =
65 PotentialRegistry::getInstance().getBeginIter();
66 while (potentialiter != PotentialRegistry::getInstance().getEndIter()) {
67 // get model and types
68 EmpiricalPotential * const potential = potentialiter->second;
69 const SerializablePotential::ParticleTypes_t &types =
70 potential->getParticleTypes();
71
72 // convert into count map
73 Extractors::elementcounts_t counts_per_element =
74 Extractors::_detail::getElementCounts(types);
75// ASSERT( !counts_per_element.empty(),
76// "getFirstGraphwithSpecifiedElements() - element counts are empty?");
77 LOG(2, "DEBUG: counts_per_element is " << counts_per_element << ".");
78
79 // check whether graph contains suitable types
80 Extractors::elementcounts_t::const_iterator countiter = counts_per_element.begin();
81 for (; countiter != counts_per_element.end(); ++countiter)
82 if (!graph.hasGreaterEqualTimesAtomicNumber(
83 static_cast<size_t>(countiter->first),
84 static_cast<size_t>(countiter->second))
85 )
86 break;
87 // if we have a match for every count, store model
88 if( countiter == counts_per_element.end()) {
89 LOG(1, "INFO: Potential " << potentialiter->first << " matches with fragment.");
90 models.push_back(static_cast<FunctionModel*>(potential));
91 particletypes_per_model.push_back(types);
92 }
93 ++potentialiter;
94 }
95
96 // check that models and particletypes_per_model match
97 ASSERT( models.size() == particletypes_per_model.size(),
98 "CompoundPotential::CompoundPotential() - particletypes not stored for all models?");
99}
100
101CompoundPotential::~CompoundPotential()
102{
103 // clear all models and internally stored particletypes
104 models.clear();
105 particletypes_per_model.clear();
106}
107
108void CompoundPotential::setParameters(const parameters_t &_params)
109{
110 size_t dim = _params.size();
111 parameters_t::const_iterator iter = _params.begin();
112 BOOST_FOREACH( FunctionModel* model, models) {
113 const size_t model_dim = model->getParameterDimension();
114 if (dim > 0) {
115 parameters_t subparams;
116 if (dim < model_dim) {
117 std::copy(iter, iter+dim, std::back_inserter(subparams));
118 iter += dim;
119 dim = 0;
120 } else {
121 std::copy(iter, iter+model_dim, std::back_inserter(subparams));
122 iter += model_dim;
123 dim -= model_dim;
124 }
125 model->setParameters(subparams);
126 }
127 }
128
129#ifndef NDEBUG
130 parameters_t check_params(getParameters());
131 check_params.resize(_params.size()); // truncate to same size
132 ASSERT( check_params == _params,
133 "CompoundPotential::setParameters() - failed, mismatch in to be set "
134 +toString(_params)+" and set "+toString(check_params)+" params.");
135#endif
136}
137
138CompoundPotential::parameters_t CompoundPotential::getParameters() const
139{
140 const size_t dimension = getParameterDimension();
141 CompoundPotential::parameters_t parameters(dimension);
142 CompoundPotential::parameters_t::iterator iter = parameters.begin();
143 BOOST_FOREACH( const FunctionModel* model, models) {
144 const CompoundPotential::parameters_t &params = model->getParameters();
145 ASSERT( iter != parameters.end(),
146 "CompoundPotential::getParameters() - iter already at end.");
147 iter = std::copy(params.begin(), params.end(), iter);
148 }
149 ASSERT( iter == parameters.end(),
150 "CompoundPotential::getParameters() - iter not at end.");
151 return parameters;
152}
153
154void CompoundPotential::setParametersToRandomInitialValues(const TrainingData &data)
155{
156 std::for_each(models.begin(), models.end(),
157 boost::bind(&FunctionModel::setParametersToRandomInitialValues, _1, boost::cref(data))
158 );
159}
160
161size_t CompoundPotential::getParameterDimension() const
162{
163 std::vector<size_t> dimensions(models.size(), 0);
164 std::transform(models.begin(), models.end(), dimensions.begin(),
165 boost::bind(&FunctionModel::getParameterDimension, _1));
166 return std::accumulate(dimensions.begin(), dimensions.end(), 0, std::plus<size_t>());
167}
168
169void CompoundPotential::setTriplefunction(triplefunction_t &_triplefunction)
170{
171 std::for_each(models.begin(), models.end(),
172 boost::bind(&FunctionModel::setTriplefunction, _1, boost::ref(_triplefunction))
173 );
174}
175
176bool CompoundPotential::areValidArguments(
177 const SerializablePotential::ParticleTypes_t &_types,
178 const arguments_t &args) const
179{
180 // /this function does much the same as Extractors::reorderArgumentsByParticleTypes()
181 typedef std::list< argument_t > ListArguments_t;
182 ListArguments_t availableList(args.begin(), args.end());
183
184 /// basically, we have two choose any two pairs out of types but only those
185 /// where the first is less than the letter. Hence, we start the second
186 /// iterator at the current position of the first one and skip the equal case.
187 for (SerializablePotential::ParticleTypes_t::const_iterator firstiter = _types.begin();
188 firstiter != _types.end();
189 ++firstiter) {
190 for (SerializablePotential::ParticleTypes_t::const_iterator seconditer = firstiter;
191 seconditer != _types.end();
192 ++seconditer) {
193 if (seconditer == firstiter)
194 continue;
195
196 // search the right one in _args (we might allow switching places of
197 // firstiter and seconditer, as distance is symmetric).
198 // we remove the matching argument to make sure we don't pick it twice
199 ListArguments_t::iterator iter = availableList.begin();
200 for (;iter != availableList.end(); ++iter) {
201 LOG(3, "DEBUG: Current args is " << *iter << ".");
202 if ((iter->types.first == *firstiter)
203 && (iter->types.second == *seconditer)) {
204 availableList.erase(iter);
205 break;
206 }
207 else if ((iter->types.first == *seconditer)
208 && (iter->types.second == *firstiter)) {
209 availableList.erase(iter);
210 break;
211 }
212 }
213 if ( iter == availableList.end())
214 return false;
215 }
216 }
217
218 return true;
219}
220
221CompoundPotential::arguments_by_model_t CompoundPotential::splitUpArgumentsByModelsFilter(
222 const arguments_t &arguments) const
223{
224 arguments_by_model_t partial_args;
225 // go through each model and have it filter out its arguments, this already
226 // returns a list of tuples associated with the specific model
227 for(models_t::const_iterator modeliter = models.begin();
228 modeliter != models.end(); ++modeliter) {
229 FunctionModel::filter_t filterfunction = (*modeliter)->getSpecificFilter();
230 list_of_arguments_t tempargs = filterfunction(arguments);
231 // then split up all the bunches, too.
232 for (list_of_arguments_t::const_iterator argiter = tempargs.begin();
233 argiter != tempargs.end(); ++argiter) {
234 const arguments_t &args = *argiter;
235 partial_args.push_back(
236 std::make_pair(
237 *modeliter,
238 args
239 )
240 );
241 }
242 }
243
244 return partial_args;
245}
246
247CompoundPotential::arguments_by_model_t CompoundPotential::splitUpArgumentsByModels(
248 const list_of_arguments_t &listarguments) const
249{
250 arguments_by_model_t partial_args;
251 particletypes_per_model_t::const_iterator typesiter = particletypes_per_model.begin();
252 models_t::const_iterator modeliter = models.begin();
253
254 /// add constant model (which is always first model) with empty args if present
255 if (typesiter->empty()) {
256 partial_args.push_back(
257 std::pair<FunctionModel *, arguments_t>(*modeliter, arguments_t())
258 );
259 ++modeliter;
260 ++typesiter;
261 }
262
263 // then check other models
264 /// we only have to check whether the current model still matches or whether
265 /// have to use the next model.
266 for (list_of_arguments_t::const_iterator argiter = listarguments.begin();
267 argiter != listarguments.end(); ++argiter) {
268 const arguments_t &arguments = *argiter;
269 if (typesiter+1 != particletypes_per_model.end()) {
270 // check whether next argument bunch is for same model or different one
271 // we extract both partial_arguments, if the latter fits, we take the latter.
272 const SerializablePotential::ParticleTypes_t &types = *typesiter;
273 const SerializablePotential::ParticleTypes_t &nexttypes = *(typesiter+1);
274
275 // we always expect N(N-1)/2 distances for N particle types
276 // check first from sizes alone
277 const size_t tuplesize = types.size()*(types.size()-1)/2;
278 const size_t nexttuplesize = nexttypes.size()*(nexttypes.size()-1)/2;
279 if ((tuplesize != nexttuplesize)) {
280 if ((arguments.size() == tuplesize) && areValidArguments(types, arguments)) {
281 // only former still matches, don't increment
282 partial_args.push_back(
283 std::make_pair(*modeliter, arguments)
284 );
285 } else if ((arguments.size() == nexttuplesize) && areValidArguments(nexttypes, arguments)) {
286 // latter matches, increment
287 ++typesiter;
288 partial_args.push_back(
289 std::make_pair(*(++modeliter), arguments)
290 );
291 } else {
292 ASSERT(0,
293 "CompoundPotential::splitUpArgumentsByModels() - neither this model nor next model match (size) with current tuple.");
294 }
295 } else { // same size, now we have to check the types individually
296 size_t encodeValidity = 0;
297 encodeValidity += 1*areValidArguments(types, arguments);
298 encodeValidity += 2*areValidArguments(nexttypes, arguments);
299
300 switch (encodeValidity) {
301 case 1:
302 // only former still matches, don't increment
303 partial_args.push_back(
304 std::make_pair(*modeliter, arguments)
305 );
306 break;
307 case 2:
308 ++typesiter;
309 partial_args.push_back(
310 std::make_pair(*(++modeliter), arguments)
311 );
312 break;
313 case 0:
314 case 3:
315 default:
316 ASSERT(0,
317 "CompoundPotential::splitUpArgumentsByModels() - neither this model nor next model match (type) with current tuple.");
318 break;
319 }
320 }
321 } else {
322 const SerializablePotential::ParticleTypes_t &types = *typesiter;
323 if (areValidArguments(types, arguments)) {
324 // only former matches, don't increment
325 partial_args.push_back(
326 std::make_pair(*modeliter, arguments)
327 );
328 } else {
329 ASSERT(0,
330 "CompoundPotential::splitUpArgumentsByModels() - last model does not match with current tuple.");
331 }
332 }
333 }
334
335 return partial_args;
336}
337
338CompoundPotential::results_t CompoundPotential::operator()(
339 const list_of_arguments_t &listarguments) const
340{
341 /// first, we have to split up the given arguments
342 arguments_by_model_t partial_args =
343 splitUpArgumentsByModels(listarguments);
344 // print split up argument list for debugging
345 if (DoLog(4)) {
346 LOG(4, "Arguments by model are: ");
347 for(arguments_by_model_t::const_iterator iter = partial_args.begin();
348 iter != partial_args.end(); ++iter) {
349 LOG(4, "\tModel with " << iter->first->getParameterDimension()
350 << " parameters " << iter->first->getParameters()
351 << " and arguments: " << iter->second);
352 }
353 }
354
355 /// then, with each bunch of arguments, we call the specific model
356 results_t results(1,0.);
357 std::vector<results_t> partial_results;
358 for(arguments_by_model_t::const_iterator iter = partial_args.begin();
359 iter != partial_args.end(); ++iter) {
360 partial_results.push_back(
361 (*iter->first)(
362 FunctionModel::list_of_arguments_t(1, iter->second))
363 );
364 }
365 // print partial results for debugging
366 if (DoLog(4)) {
367 std::stringstream output;
368 output << "Partial results are: ";
369 std::for_each(partial_results.begin(), partial_results.end(),
370 output << (boost::lambda::_1)[0] << "\t");
371 LOG(4, output.str());
372 }
373
374 /// Finally, sum up all results and return
375 std::for_each(partial_results.begin(), partial_results.end(),
376 results[0] += (boost::lambda::_1)[0]);
377 return results;
378}
379
380CompoundPotential::results_t CompoundPotential::parameter_derivative(
381 const list_of_arguments_t &listarguments,
382 const size_t index) const
383{
384 // first, we have to split up the given arguments
385 arguments_by_model_t partial_args =
386 splitUpArgumentsByModels(listarguments);
387 // then, with each bunch of arguments, we call the specific model
388 // get parameter dimensions per model
389 std::vector<size_t> dimensions(models.size(), 0);
390 std::transform(models.begin(), models.end(), dimensions.begin(),
391 boost::bind(&FunctionModel::getParameterDimension, _1));
392
393 // convert to index end+1 per model
394 std::partial_sum(dimensions.begin(), dimensions.end(), dimensions.begin());
395
396 // look for first value greater than index
397 std::vector<size_t>::const_iterator iter =
398 std::upper_bound(dimensions.begin(), dimensions.end(), index);
399
400 // step forward to same model
401 models_t::const_iterator modeliter = models.begin();
402 std::advance(modeliter,
403 std::distance(const_cast<const std::vector<size_t> &>(dimensions).begin(), iter) );
404
405 CompoundPotential::results_t returnresults;
406 for(arguments_by_model_t::const_iterator argiter = partial_args.begin();
407 argiter != partial_args.end(); ++argiter) {
408 const FunctionModel *model = argiter->first;
409
410 // for every matching model evaluate
411 if (model == *modeliter) {
412 // evaluate with correct relative index and return
413 const size_t indexbase = (iter == dimensions.begin()) ? 0 : *(iter-1);
414 CompoundPotential::results_t results =
415 model->parameter_derivative(
416 FunctionModel::list_of_arguments_t(1, argiter->second), index-indexbase);
417
418 // either set results or add
419 if (returnresults.empty())
420 returnresults = results;
421 else
422 std::transform(
423 results.begin(), results.end(),
424 returnresults.begin(),
425 returnresults.begin(),
426 std::plus<FunctionModel::result_t>());
427 }
428 }
429
430 return returnresults;
431}
432
433bool CompoundPotential::isBoxConstraint() const
434{
435 std::vector<bool> constraints(models.size(), 0);
436 std::transform(models.begin(), models.end(), constraints.begin(),
437 boost::bind(&FunctionModel::getParameterDimension, _1));
438 return std::accumulate(constraints.begin(), constraints.end(), true,
439 std::logical_and<bool>());
440}
441
442CompoundPotential::parameters_t CompoundPotential::getLowerBoxConstraints() const
443{
444 const size_t dimension = getParameterDimension();
445 CompoundPotential::parameters_t constraints(dimension);
446 CompoundPotential::parameters_t::iterator iter = constraints.begin();
447 BOOST_FOREACH( FunctionModel* model, models) {
448 const CompoundPotential::parameters_t params = model->getLowerBoxConstraints();
449 ASSERT( iter != constraints.end(),
450 "CompoundPotential::getLowerBoxConstraints() - iter already at end.");
451 iter = std::copy(params.begin(), params.end(), iter);
452 }
453 ASSERT( iter == constraints.end(),
454 "CompoundPotential::getLowerBoxConstraints() - iter not at end.");
455 return constraints;
456}
457
458CompoundPotential::parameters_t CompoundPotential::getUpperBoxConstraints() const
459{
460 const size_t dimension = getParameterDimension();
461 CompoundPotential::parameters_t constraints(dimension);
462 CompoundPotential::parameters_t::iterator iter = constraints.begin();
463 BOOST_FOREACH( FunctionModel* model, models) {
464 const CompoundPotential::parameters_t params = model->getUpperBoxConstraints();
465 ASSERT( iter != constraints.end(),
466 "CompoundPotential::getUpperBoxConstraints() - iter already at end.");
467 iter = std::copy(params.begin(), params.end(), iter);
468 }
469 ASSERT( iter == constraints.end(),
470 "CompoundPotential::getUpperBoxConstraints() - iter not at end.");
471 return constraints;
472}
473
474FunctionModel::filter_t CompoundPotential::getSpecificFilter() const
475{
476 // we must concatenate all filtered arguments here
477 // create initial returnfunction
478 FunctionModel::filter_t returnfunction =
479 boost::bind(&Helpers::returnEmptyListArguments);
480
481 // every following fragments combines its arguments with the initial function
482 for (models_t::const_iterator modeliter = models.begin();
483 modeliter != models.end(); ++modeliter) {
484 returnfunction =
485 boost::bind(&Extractors::concatenateListOfArguments,
486 boost::bind(returnfunction, _1),
487 boost::bind((*modeliter)->getSpecificFilter(), _1)
488 );
489 }
490 return returnfunction;
491}
492
493size_t CompoundPotential::getSpecificArgumentCount() const
494{
495 std::vector<size_t> argument_counts(models.size(), 0);
496 std::transform(models.begin(), models.end(), argument_counts.begin(),
497 boost::bind(&FunctionModel::getSpecificArgumentCount, _1));
498 return std::accumulate(argument_counts.begin(), argument_counts.end(), 0,
499 std::plus<size_t>());
500}
501
Note: See TracBrowser for help on using the repository browser.