source: src/Potentials/CompoundPotential.cpp@ 9b0dcd

Candidate_v1.7.0 stable
Last change on this file since 9b0dcd was c98620, checked in by Frederik Heber <frederik.heber@…>, 4 years ago

FIX: StreamFactory did not set BindingModel.

  • we streamed into a default potential instance but this does not set the BindingModel. Now, we use the particle types from that deseralized instance and instantiate a new potential that then also generates the BindingModel.
  • added output operator to BindingModel.
  • TEST: This fixes the fit-compound-potential regression test case.
  • Property mode set to 100644
File size: 18.7 KB
RevLine 
[154e88]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
[acc9b1]5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
[154e88]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
[9eb71b3]36//#include "CodePatterns/MemDebug.hpp"
[154e88]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"
[0f5d38]55#include "Potentials/helpers.hpp"
[154e88]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
[c98620]64 for(PotentialRegistry::const_iterator potentialiter = PotentialRegistry::getInstance().getBeginIter();
65 potentialiter != PotentialRegistry::getInstance().getEndIter(); ++potentialiter) {
[154e88]66 // get model and types
67 EmpiricalPotential * const potential = potentialiter->second;
68 const SerializablePotential::ParticleTypes_t &types =
69 potential->getParticleTypes();
70
71 // convert into count map
[c5e75f3]72 Extractors::elementcounts_t counts_per_element =
73 Extractors::_detail::getElementCounts(types);
74 LOG(2, "DEBUG: counts_per_element is " << counts_per_element << ".");
[154e88]75
76 // check whether graph contains suitable types
[c98620]77 bool status = true;
78 for (Extractors::elementcounts_t::const_iterator countiter = counts_per_element.begin();
79 (countiter != counts_per_element.end()) && (status); ++countiter)
80 status = status & (graph.hasGreaterEqualTimesAtomicNumber(
[154e88]81 static_cast<size_t>(countiter->first),
82 static_cast<size_t>(countiter->second))
[c98620]83 );
84 // check whether graph contains all necessary edges
85 status &= graph.contains(potential->getBindingModel().getGraph());
86
87 // if we have a matched all nodes and edges, store model
88 if( status) {
89 LOG(1, "INFO: Potential " << potential->getName() << " matches with fragment.");
[154e88]90 models.push_back(static_cast<FunctionModel*>(potential));
91 particletypes_per_model.push_back(types);
92 }
93 }
94
95 // check that models and particletypes_per_model match
96 ASSERT( models.size() == particletypes_per_model.size(),
97 "CompoundPotential::CompoundPotential() - particletypes not stored for all models?");
98}
99
100CompoundPotential::~CompoundPotential()
101{
102 // clear all models and internally stored particletypes
103 models.clear();
104 particletypes_per_model.clear();
105}
106
107void CompoundPotential::setParameters(const parameters_t &_params)
108{
109 size_t dim = _params.size();
110 parameters_t::const_iterator iter = _params.begin();
111 BOOST_FOREACH( FunctionModel* model, models) {
[7c1091]112 const size_t model_dim = model->getParameterDimension();
[154e88]113 if (dim > 0) {
114 parameters_t subparams;
115 if (dim < model_dim) {
116 std::copy(iter, iter+dim, std::back_inserter(subparams));
[7e5b94]117 iter += dim;
[154e88]118 dim = 0;
119 } else {
120 std::copy(iter, iter+model_dim, std::back_inserter(subparams));
[7e5b94]121 iter += model_dim;
[154e88]122 dim -= model_dim;
123 }
124 model->setParameters(subparams);
125 }
126 }
[7c1091]127
128#ifndef NDEBUG
129 parameters_t check_params(getParameters());
130 check_params.resize(_params.size()); // truncate to same size
131 ASSERT( check_params == _params,
132 "CompoundPotential::setParameters() - failed, mismatch in to be set "
133 +toString(_params)+" and set "+toString(check_params)+" params.");
134#endif
[154e88]135}
136
137CompoundPotential::parameters_t CompoundPotential::getParameters() const
138{
139 const size_t dimension = getParameterDimension();
140 CompoundPotential::parameters_t parameters(dimension);
141 CompoundPotential::parameters_t::iterator iter = parameters.begin();
142 BOOST_FOREACH( const FunctionModel* model, models) {
143 const CompoundPotential::parameters_t &params = model->getParameters();
144 ASSERT( iter != parameters.end(),
145 "CompoundPotential::getParameters() - iter already at end.");
[7c1091]146 iter = std::copy(params.begin(), params.end(), iter);
[154e88]147 }
[7c1091]148 ASSERT( iter == parameters.end(),
149 "CompoundPotential::getParameters() - iter not at end.");
[154e88]150 return parameters;
151}
152
153void CompoundPotential::setParametersToRandomInitialValues(const TrainingData &data)
154{
155 std::for_each(models.begin(), models.end(),
156 boost::bind(&FunctionModel::setParametersToRandomInitialValues, _1, boost::cref(data))
157 );
158}
159
160size_t CompoundPotential::getParameterDimension() const
161{
162 std::vector<size_t> dimensions(models.size(), 0);
163 std::transform(models.begin(), models.end(), dimensions.begin(),
164 boost::bind(&FunctionModel::getParameterDimension, _1));
165 return std::accumulate(dimensions.begin(), dimensions.end(), 0, std::plus<size_t>());
166}
167
168void CompoundPotential::setTriplefunction(triplefunction_t &_triplefunction)
169{
170 std::for_each(models.begin(), models.end(),
171 boost::bind(&FunctionModel::setTriplefunction, _1, boost::ref(_triplefunction))
172 );
173}
174
[7c1091]175bool CompoundPotential::areValidArguments(
176 const SerializablePotential::ParticleTypes_t &_types,
177 const arguments_t &args) const
178{
179 // /this function does much the same as Extractors::reorderArgumentsByParticleTypes()
180 typedef std::list< argument_t > ListArguments_t;
181 ListArguments_t availableList(args.begin(), args.end());
182
183 /// basically, we have two choose any two pairs out of types but only those
184 /// where the first is less than the letter. Hence, we start the second
185 /// iterator at the current position of the first one and skip the equal case.
186 for (SerializablePotential::ParticleTypes_t::const_iterator firstiter = _types.begin();
187 firstiter != _types.end();
188 ++firstiter) {
189 for (SerializablePotential::ParticleTypes_t::const_iterator seconditer = firstiter;
190 seconditer != _types.end();
191 ++seconditer) {
192 if (seconditer == firstiter)
193 continue;
194
195 // search the right one in _args (we might allow switching places of
196 // firstiter and seconditer, as distance is symmetric).
197 // we remove the matching argument to make sure we don't pick it twice
198 ListArguments_t::iterator iter = availableList.begin();
199 for (;iter != availableList.end(); ++iter) {
200 LOG(3, "DEBUG: Current args is " << *iter << ".");
201 if ((iter->types.first == *firstiter)
202 && (iter->types.second == *seconditer)) {
203 availableList.erase(iter);
204 break;
205 }
206 else if ((iter->types.first == *seconditer)
207 && (iter->types.second == *firstiter)) {
208 availableList.erase(iter);
209 break;
210 }
211 }
212 if ( iter == availableList.end())
213 return false;
214 }
215 }
216
217 return true;
218}
219
[a633f6]220CompoundPotential::arguments_by_model_t CompoundPotential::splitUpArgumentsByModelsFilter(
[e60558]221 const HomologyGraph &graph,
[a633f6]222 const arguments_t &arguments) const
223{
224 arguments_by_model_t partial_args;
[e1fe7e]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
[a633f6]227 for(models_t::const_iterator modeliter = models.begin();
228 modeliter != models.end(); ++modeliter) {
229 FunctionModel::filter_t filterfunction = (*modeliter)->getSpecificFilter();
[e60558]230 list_of_arguments_t tempargs = filterfunction(graph, arguments);
[a633f6]231 // then split up all the bunches, too.
[e1fe7e]232 for (list_of_arguments_t::const_iterator argiter = tempargs.begin();
233 argiter != tempargs.end(); ++argiter) {
234 const arguments_t &args = *argiter;
[a633f6]235 partial_args.push_back(
236 std::make_pair(
237 *modeliter,
[e1fe7e]238 args
[a633f6]239 )
240 );
241 }
242 }
243
244 return partial_args;
245}
246
[7c1091]247CompoundPotential::arguments_by_model_t CompoundPotential::splitUpArgumentsByModels(
[e1fe7e]248 const list_of_arguments_t &listarguments) const
[7e5b94]249{
[7c1091]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
[e1fe7e]254 /// add constant model (which is always first model) with empty args if present
[7c1091]255 if (typesiter->empty()) {
256 partial_args.push_back(
257 std::pair<FunctionModel *, arguments_t>(*modeliter, arguments_t())
258 );
259 ++modeliter;
260 ++typesiter;
261 }
[e1fe7e]262
[7c1091]263 // then check other models
[e1fe7e]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;
[7c1091]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
[e1fe7e]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
[7c1091]282 partial_args.push_back(
[e1fe7e]283 std::make_pair(*modeliter, arguments)
[7c1091]284 );
[e1fe7e]285 } else if ((arguments.size() == nexttuplesize) && areValidArguments(nexttypes, arguments)) {
[7c1091]286 // latter matches, increment
287 ++typesiter;
288 partial_args.push_back(
[e1fe7e]289 std::make_pair(*(++modeliter), arguments)
[7c1091]290 );
[e1fe7e]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;
[7c1091]319 }
320 }
321 } else {
322 const SerializablePotential::ParticleTypes_t &types = *typesiter;
[e1fe7e]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 }
[7c1091]332 }
[7e5b94]333 }
[7c1091]334
[7e5b94]335 return partial_args;
336}
337
[e1fe7e]338CompoundPotential::results_t CompoundPotential::operator()(
339 const list_of_arguments_t &listarguments) const
[154e88]340{
[7c1091]341 /// first, we have to split up the given arguments
342 arguments_by_model_t partial_args =
[e1fe7e]343 splitUpArgumentsByModels(listarguments);
[7c1091]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
[154e88]356 results_t results(1,0.);
[7c1091]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(
[e1fe7e]361 (*iter->first)(
362 FunctionModel::list_of_arguments_t(1, iter->second))
[7c1091]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
[154e88]375 std::for_each(partial_results.begin(), partial_results.end(),
376 results[0] += (boost::lambda::_1)[0]);
377 return results;
378}
379
[e1fe7e]380CompoundPotential::results_t CompoundPotential::parameter_derivative(
381 const list_of_arguments_t &listarguments,
382 const size_t index) const
[154e88]383{
[7e5b94]384 // first, we have to split up the given arguments
[7c1091]385 arguments_by_model_t partial_args =
[e1fe7e]386 splitUpArgumentsByModels(listarguments);
[7e5b94]387 // then, with each bunch of arguments, we call the specific model
[154e88]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
[7c1091]396 // look for first value greater than index
[154e88]397 std::vector<size_t>::const_iterator iter =
[7c1091]398 std::upper_bound(dimensions.begin(), dimensions.end(), index);
[154e88]399
400 // step forward to same model
[7e5b94]401 models_t::const_iterator modeliter = models.begin();
[154e88]402 std::advance(modeliter,
403 std::distance(const_cast<const std::vector<size_t> &>(dimensions).begin(), iter) );
404
[7c1091]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 =
[e1fe7e]415 model->parameter_derivative(
416 FunctionModel::list_of_arguments_t(1, argiter->second), index-indexbase);
[7c1091]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 }
[698185]429 ASSERT(!returnresults.empty(),
430 "CompoundPotential::parameter_derivative() - could not determine derivative for index "
[c98620]431 +toString(index)+". This typically indicates that a parameter derivative of "
432 +"a model is evaluated which has no arguments in the partial argument list.");
[7c1091]433 return returnresults;
[154e88]434}
435
436bool CompoundPotential::isBoxConstraint() const
437{
438 std::vector<bool> constraints(models.size(), 0);
439 std::transform(models.begin(), models.end(), constraints.begin(),
[698185]440 boost::bind(&FunctionModel::isBoxConstraint, _1));
[154e88]441 return std::accumulate(constraints.begin(), constraints.end(), true,
442 std::logical_and<bool>());
443}
444
445CompoundPotential::parameters_t CompoundPotential::getLowerBoxConstraints() const
446{
447 const size_t dimension = getParameterDimension();
448 CompoundPotential::parameters_t constraints(dimension);
449 CompoundPotential::parameters_t::iterator iter = constraints.begin();
450 BOOST_FOREACH( FunctionModel* model, models) {
451 const CompoundPotential::parameters_t params = model->getLowerBoxConstraints();
452 ASSERT( iter != constraints.end(),
[7c1091]453 "CompoundPotential::getLowerBoxConstraints() - iter already at end.");
454 iter = std::copy(params.begin(), params.end(), iter);
[154e88]455 }
[7c1091]456 ASSERT( iter == constraints.end(),
457 "CompoundPotential::getLowerBoxConstraints() - iter not at end.");
[154e88]458 return constraints;
459}
460
461CompoundPotential::parameters_t CompoundPotential::getUpperBoxConstraints() const
462{
463 const size_t dimension = getParameterDimension();
464 CompoundPotential::parameters_t constraints(dimension);
465 CompoundPotential::parameters_t::iterator iter = constraints.begin();
466 BOOST_FOREACH( FunctionModel* model, models) {
467 const CompoundPotential::parameters_t params = model->getUpperBoxConstraints();
468 ASSERT( iter != constraints.end(),
[7c1091]469 "CompoundPotential::getUpperBoxConstraints() - iter already at end.");
470 iter = std::copy(params.begin(), params.end(), iter);
[154e88]471 }
[7c1091]472 ASSERT( iter == constraints.end(),
473 "CompoundPotential::getUpperBoxConstraints() - iter not at end.");
[154e88]474 return constraints;
475}
476
[0f5d38]477FunctionModel::filter_t CompoundPotential::getSpecificFilter() const
478{
479 // we must concatenate all filtered arguments here
480 // create initial returnfunction
481 FunctionModel::filter_t returnfunction =
[e1fe7e]482 boost::bind(&Helpers::returnEmptyListArguments);
[0f5d38]483
484 // every following fragments combines its arguments with the initial function
485 for (models_t::const_iterator modeliter = models.begin();
486 modeliter != models.end(); ++modeliter) {
487 returnfunction =
[e1fe7e]488 boost::bind(&Extractors::concatenateListOfArguments,
[e60558]489 boost::bind(returnfunction, _1, _2),
490 boost::bind((*modeliter)->getSpecificFilter(), _1, _2)
[0f5d38]491 );
492 }
493 return returnfunction;
494}
495
496size_t CompoundPotential::getSpecificArgumentCount() const
497{
498 std::vector<size_t> argument_counts(models.size(), 0);
499 std::transform(models.begin(), models.end(), argument_counts.begin(),
500 boost::bind(&FunctionModel::getSpecificArgumentCount, _1));
501 return std::accumulate(argument_counts.begin(), argument_counts.end(), 0,
502 std::plus<size_t>());
503}
504
Note: See TracBrowser for help on using the repository browser.