source: src/Potentials/CompoundPotential.cpp@ f0025d

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing 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_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since f0025d was f0025d, checked in by Frederik Heber <heber@…>, 11 years ago

Renamed getFragmentSpecificExtractor() -> getSpecificExtractor().

  • Property mode set to 100644
File size: 17.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/PotentialRegistry.hpp"
56
57
58CompoundPotential::CompoundPotential(const HomologyGraph &graph)
59{
60 LOG(1, "INFO: Creating CompoundPotential for graph " << graph << ".");
61 // look though graph and place all matching FunctionModel's in
62 // PotentialRegistry in models
63 PotentialRegistry::const_iterator potentialiter =
64 PotentialRegistry::getInstance().getBeginIter();
65 while (potentialiter != PotentialRegistry::getInstance().getEndIter()) {
66 // get model and types
67 EmpiricalPotential * const potential = potentialiter->second;
68 const SerializablePotential::ParticleTypes_t &types =
69 potential->getParticleTypes();
70
71 // create charges
72 Fragment::charges_t charges;
73 charges.resize(types.size());
74 std::transform(types.begin(), types.end(),
75 charges.begin(), boost::lambda::_1);
76 // convert into count map
77 Extractors::elementcounts_t counts_per_charge =
78 Extractors::_detail::getElementCounts(charges);
79// ASSERT( !counts_per_charge.empty(),
80// "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
81 LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
82
83 // check whether graph contains suitable types
84 Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
85 for (; countiter != counts_per_charge.end(); ++countiter)
86 if (!graph.hasGreaterEqualTimesAtomicNumber(
87 static_cast<size_t>(countiter->first),
88 static_cast<size_t>(countiter->second))
89 )
90 break;
91 // if we have a match for every count, store model
92 if( countiter == counts_per_charge.end()) {
93 LOG(1, "INFO: Potential " << potentialiter->first << " matches with fragment.");
94 models.push_back(static_cast<FunctionModel*>(potential));
95 particletypes_per_model.push_back(types);
96 }
97 ++potentialiter;
98 }
99
100 // check that models and particletypes_per_model match
101 ASSERT( models.size() == particletypes_per_model.size(),
102 "CompoundPotential::CompoundPotential() - particletypes not stored for all models?");
103}
104
105CompoundPotential::~CompoundPotential()
106{
107 // clear all models and internally stored particletypes
108 models.clear();
109 particletypes_per_model.clear();
110}
111
112void CompoundPotential::setParameters(const parameters_t &_params)
113{
114 size_t dim = _params.size();
115 parameters_t::const_iterator iter = _params.begin();
116 BOOST_FOREACH( FunctionModel* model, models) {
117 const size_t model_dim = model->getParameterDimension();
118 if (dim > 0) {
119 parameters_t subparams;
120 if (dim < model_dim) {
121 std::copy(iter, iter+dim, std::back_inserter(subparams));
122 iter += dim;
123 dim = 0;
124 } else {
125 std::copy(iter, iter+model_dim, std::back_inserter(subparams));
126 iter += model_dim;
127 dim -= model_dim;
128 }
129 model->setParameters(subparams);
130 }
131 }
132
133#ifndef NDEBUG
134 parameters_t check_params(getParameters());
135 check_params.resize(_params.size()); // truncate to same size
136 ASSERT( check_params == _params,
137 "CompoundPotential::setParameters() - failed, mismatch in to be set "
138 +toString(_params)+" and set "+toString(check_params)+" params.");
139#endif
140}
141
142CompoundPotential::parameters_t CompoundPotential::getParameters() const
143{
144 const size_t dimension = getParameterDimension();
145 CompoundPotential::parameters_t parameters(dimension);
146 CompoundPotential::parameters_t::iterator iter = parameters.begin();
147 BOOST_FOREACH( const FunctionModel* model, models) {
148 const CompoundPotential::parameters_t &params = model->getParameters();
149 ASSERT( iter != parameters.end(),
150 "CompoundPotential::getParameters() - iter already at end.");
151 iter = std::copy(params.begin(), params.end(), iter);
152 }
153 ASSERT( iter == parameters.end(),
154 "CompoundPotential::getParameters() - iter not at end.");
155 return parameters;
156}
157
158void CompoundPotential::setParametersToRandomInitialValues(const TrainingData &data)
159{
160 std::for_each(models.begin(), models.end(),
161 boost::bind(&FunctionModel::setParametersToRandomInitialValues, _1, boost::cref(data))
162 );
163}
164
165size_t CompoundPotential::getParameterDimension() const
166{
167 std::vector<size_t> dimensions(models.size(), 0);
168 std::transform(models.begin(), models.end(), dimensions.begin(),
169 boost::bind(&FunctionModel::getParameterDimension, _1));
170 return std::accumulate(dimensions.begin(), dimensions.end(), 0, std::plus<size_t>());
171}
172
173void CompoundPotential::setTriplefunction(triplefunction_t &_triplefunction)
174{
175 std::for_each(models.begin(), models.end(),
176 boost::bind(&FunctionModel::setTriplefunction, _1, boost::ref(_triplefunction))
177 );
178}
179
180bool CompoundPotential::areValidArguments(
181 const SerializablePotential::ParticleTypes_t &_types,
182 const arguments_t &args) const
183{
184 // /this function does much the same as Extractors::reorderArgumentsByParticleTypes()
185 typedef std::list< argument_t > ListArguments_t;
186 ListArguments_t availableList(args.begin(), args.end());
187
188 /// basically, we have two choose any two pairs out of types but only those
189 /// where the first is less than the letter. Hence, we start the second
190 /// iterator at the current position of the first one and skip the equal case.
191 for (SerializablePotential::ParticleTypes_t::const_iterator firstiter = _types.begin();
192 firstiter != _types.end();
193 ++firstiter) {
194 for (SerializablePotential::ParticleTypes_t::const_iterator seconditer = firstiter;
195 seconditer != _types.end();
196 ++seconditer) {
197 if (seconditer == firstiter)
198 continue;
199
200 // search the right one in _args (we might allow switching places of
201 // firstiter and seconditer, as distance is symmetric).
202 // we remove the matching argument to make sure we don't pick it twice
203 ListArguments_t::iterator iter = availableList.begin();
204 for (;iter != availableList.end(); ++iter) {
205 LOG(3, "DEBUG: Current args is " << *iter << ".");
206 if ((iter->types.first == *firstiter)
207 && (iter->types.second == *seconditer)) {
208 availableList.erase(iter);
209 break;
210 }
211 else if ((iter->types.first == *seconditer)
212 && (iter->types.second == *firstiter)) {
213 availableList.erase(iter);
214 break;
215 }
216 }
217 if ( iter == availableList.end())
218 return false;
219 }
220 }
221
222 return true;
223}
224
225CompoundPotential::arguments_by_model_t CompoundPotential::splitUpArgumentsByModels(
226 const arguments_t &arguments) const
227{
228 arguments_by_model_t partial_args;
229 arguments_t::const_iterator argiter = arguments.begin();
230 particletypes_per_model_t::const_iterator typesiter = particletypes_per_model.begin();
231 models_t::const_iterator modeliter = models.begin();
232
233 // add constant model (which is always first model) with empty args if present
234 if (typesiter->empty()) {
235 partial_args.push_back(
236 std::pair<FunctionModel *, arguments_t>(*modeliter, arguments_t())
237 );
238 ++modeliter;
239 ++typesiter;
240 }
241 // then check other models
242 while (argiter != arguments.end()) {
243 if (typesiter+1 != particletypes_per_model.end()) {
244 // check whether next argument bunch is for same model or different one
245 // we extract both partial_arguments, if the latter fits, we take the latter.
246 const SerializablePotential::ParticleTypes_t &types = *typesiter;
247 const SerializablePotential::ParticleTypes_t &nexttypes = *(typesiter+1);
248
249 // we always expect N(N-1)/2 distances for N particle types
250 arguments_t::const_iterator enditer = argiter+(types.size()*(types.size()-1)/2);
251 arguments_t::const_iterator nextenditer = argiter+(nexttypes.size()*(nexttypes.size()-1)/2);
252 arguments_t args(argiter, enditer);
253 arguments_t nextargs(argiter, nextenditer);
254 if (types.size() < nexttypes.size()) {
255 if (areValidArguments(nexttypes, nextargs)) {
256 // latter matches, increment
257 ++typesiter;
258 partial_args.push_back(
259 std::make_pair(*(++modeliter), arguments_t(argiter, nextenditer))
260 );
261 argiter = nextenditer;
262 } else if (areValidArguments(types, args)) {
263 // only former matches, don't increment
264 partial_args.push_back(
265 std::make_pair(*modeliter, arguments_t(argiter, enditer))
266 );
267 argiter = enditer;
268 } else
269 ASSERT(0,
270 "CompoundPotential::splitUpArgumentsByModels() - neither type matches its argument bunch.");
271 } else {
272 if (areValidArguments(types, args)) {
273 // only former matches, don't increment
274 partial_args.push_back(
275 std::make_pair(*modeliter, arguments_t(argiter, enditer))
276 );
277 argiter = enditer;
278 } else if (areValidArguments(nexttypes, nextargs)) {
279 // latter matches, increment
280 ++typesiter;
281 partial_args.push_back(
282 std::make_pair(*(++modeliter), arguments_t(argiter, nextenditer))
283 );
284 argiter = nextenditer;
285 }
286 }
287 } else {
288 const SerializablePotential::ParticleTypes_t &types = *typesiter;
289 // we always expect N(N-1)/2 distances for N particle types
290 arguments_t::const_iterator enditer = argiter+(types.size()*(types.size()-1)/2);
291 partial_args.push_back(
292 std::make_pair(*modeliter, arguments_t(argiter, enditer))
293 );
294 argiter = enditer;
295 }
296 }
297
298 return partial_args;
299}
300
301CompoundPotential::results_t CompoundPotential::operator()(const arguments_t &arguments) const
302{
303 /// first, we have to split up the given arguments
304 arguments_by_model_t partial_args =
305 splitUpArgumentsByModels(arguments);
306 // print split up argument list for debugging
307 if (DoLog(4)) {
308 LOG(4, "Arguments by model are: ");
309 for(arguments_by_model_t::const_iterator iter = partial_args.begin();
310 iter != partial_args.end(); ++iter) {
311 LOG(4, "\tModel with " << iter->first->getParameterDimension()
312 << " parameters " << iter->first->getParameters()
313 << " and arguments: " << iter->second);
314 }
315 }
316
317 /// then, with each bunch of arguments, we call the specific model
318 results_t results(1,0.);
319 std::vector<results_t> partial_results;
320 for(arguments_by_model_t::const_iterator iter = partial_args.begin();
321 iter != partial_args.end(); ++iter) {
322 partial_results.push_back(
323 (*iter->first)(iter->second)
324 );
325 }
326 // print partial results for debugging
327 if (DoLog(4)) {
328 std::stringstream output;
329 output << "Partial results are: ";
330 std::for_each(partial_results.begin(), partial_results.end(),
331 output << (boost::lambda::_1)[0] << "\t");
332 LOG(4, output.str());
333 }
334
335 /// Finally, sum up all results and return
336 std::for_each(partial_results.begin(), partial_results.end(),
337 results[0] += (boost::lambda::_1)[0]);
338 return results;
339}
340
341CompoundPotential::results_t CompoundPotential::parameter_derivative(const arguments_t &arguments, const size_t index) const
342{
343 // first, we have to split up the given arguments
344 arguments_by_model_t partial_args =
345 splitUpArgumentsByModels(arguments);
346 // then, with each bunch of arguments, we call the specific model
347 // get parameter dimensions per model
348 std::vector<size_t> dimensions(models.size(), 0);
349 std::transform(models.begin(), models.end(), dimensions.begin(),
350 boost::bind(&FunctionModel::getParameterDimension, _1));
351
352 // convert to index end+1 per model
353 std::partial_sum(dimensions.begin(), dimensions.end(), dimensions.begin());
354
355 // look for first value greater than index
356 std::vector<size_t>::const_iterator iter =
357 std::upper_bound(dimensions.begin(), dimensions.end(), index);
358
359 // step forward to same model
360 models_t::const_iterator modeliter = models.begin();
361 std::advance(modeliter,
362 std::distance(const_cast<const std::vector<size_t> &>(dimensions).begin(), iter) );
363
364 CompoundPotential::results_t returnresults;
365 for(arguments_by_model_t::const_iterator argiter = partial_args.begin();
366 argiter != partial_args.end(); ++argiter) {
367 const FunctionModel *model = argiter->first;
368
369 // for every matching model evaluate
370 if (model == *modeliter) {
371 // evaluate with correct relative index and return
372 const size_t indexbase = (iter == dimensions.begin()) ? 0 : *(iter-1);
373 CompoundPotential::results_t results =
374 model->parameter_derivative(argiter->second, index-indexbase);
375
376 // either set results or add
377 if (returnresults.empty())
378 returnresults = results;
379 else
380 std::transform(
381 results.begin(), results.end(),
382 returnresults.begin(),
383 returnresults.begin(),
384 std::plus<FunctionModel::result_t>());
385 }
386 }
387
388 return returnresults;
389}
390
391bool CompoundPotential::isBoxConstraint() const
392{
393 std::vector<bool> constraints(models.size(), 0);
394 std::transform(models.begin(), models.end(), constraints.begin(),
395 boost::bind(&FunctionModel::getParameterDimension, _1));
396 return std::accumulate(constraints.begin(), constraints.end(), true,
397 std::logical_and<bool>());
398}
399
400CompoundPotential::parameters_t CompoundPotential::getLowerBoxConstraints() const
401{
402 const size_t dimension = getParameterDimension();
403 CompoundPotential::parameters_t constraints(dimension);
404 CompoundPotential::parameters_t::iterator iter = constraints.begin();
405 BOOST_FOREACH( FunctionModel* model, models) {
406 const CompoundPotential::parameters_t params = model->getLowerBoxConstraints();
407 ASSERT( iter != constraints.end(),
408 "CompoundPotential::getLowerBoxConstraints() - iter already at end.");
409 iter = std::copy(params.begin(), params.end(), iter);
410 }
411 ASSERT( iter == constraints.end(),
412 "CompoundPotential::getLowerBoxConstraints() - iter not at end.");
413 return constraints;
414}
415
416CompoundPotential::parameters_t CompoundPotential::getUpperBoxConstraints() const
417{
418 const size_t dimension = getParameterDimension();
419 CompoundPotential::parameters_t constraints(dimension);
420 CompoundPotential::parameters_t::iterator iter = constraints.begin();
421 BOOST_FOREACH( FunctionModel* model, models) {
422 const CompoundPotential::parameters_t params = model->getUpperBoxConstraints();
423 ASSERT( iter != constraints.end(),
424 "CompoundPotential::getUpperBoxConstraints() - iter already at end.");
425 iter = std::copy(params.begin(), params.end(), iter);
426 }
427 ASSERT( iter == constraints.end(),
428 "CompoundPotential::getUpperBoxConstraints() - iter not at end.");
429 return constraints;
430}
431
432FunctionModel::extractor_t CompoundPotential::getSpecificExtractor() const
433{
434 // create initial returnfunction
435 particletypes_per_model_t::const_iterator typesiter = particletypes_per_model.begin();
436 Fragment::charges_t charges;
437 {
438 charges.resize((*typesiter).size());
439 std::transform((*typesiter).begin(), (*typesiter).end(),
440 charges.begin(), boost::lambda::_1);
441 }
442 FunctionModel::extractor_t returnfunction =
443 boost::bind(&Extractors::gatherAllDistancesFromFragment,
444 boost::bind(&Fragment::getPositions, _1),
445 boost::bind(&Fragment::getCharges, _1),
446 charges, // no crefs here as are temporaries!
447 _2);
448
449 // every following fragments combines its arguments with the initial function
450 for (; typesiter != particletypes_per_model.end(); ++typesiter) {
451 Fragment::charges_t charges;
452 {
453 charges.resize((*typesiter).size());
454 std::transform((*typesiter).begin(), (*typesiter).end(),
455 charges.begin(), boost::lambda::_1);
456 }
457
458 returnfunction =
459 boost::bind(&Extractors::concatenateArguments,
460 boost::bind(returnfunction, _1, _2),
461 boost::bind(&Extractors::gatherAllDistancesFromFragment,
462 boost::bind(&Fragment::getPositions, _1),
463 boost::bind(&Fragment::getCharges, _1),
464 charges, // no crefs here as are temporaries!
465 _2)
466 );
467 }
468 return returnfunction;
469}
Note: See TracBrowser for help on using the repository browser.