source: src/Potentials/CompoundPotential.cpp@ 51e0e3

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 51e0e3 was 0f5d38, checked in by Frederik Heber <heber@…>, 11 years ago

Added getSpecificFilter() and getSpecificArgumentCount() to FunctionModel.

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