source: src/Potentials/Specifics/SaturationPotential.cpp@ 64bdfd

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 64bdfd was 035c0d, checked in by Frederik Heber <heber@…>, 12 years ago

Removed typedef charges_t from FunctionModel, using SerializationPotential's instead.

  • 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) 2012 University of Bonn. All rights reserved.
5 * Please see the COPYING file or "Copyright notice" in builder.cpp for details.
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 * SaturationPotential.cpp
26 *
27 * Created on: Oct 11, 2012
28 * Author: heber
29 */
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 "SaturationPotential.hpp"
40
41#include <boost/assign.hpp>
42#include <boost/assign/list_of.hpp> // for 'map_list_of()'
43#include <boost/lambda/lambda.hpp>
44#include <iostream>
45#include <string>
46
47#include "CodePatterns/Assert.hpp"
48#include "CodePatterns/Log.hpp"
49
50#include "FunctionApproximation/Extractors.hpp"
51#include "FunctionApproximation/TrainingData.hpp"
52#include "Potentials/helpers.hpp"
53#include "Potentials/ParticleTypeCheckers.hpp"
54
55class Fragment;
56
57using namespace boost::assign;
58
59// static definitions
60const SaturationPotential::ParameterNames_t
61SaturationPotential::ParameterNames =
62 boost::assign::list_of<std::string>
63 ("all_energy_offset")
64 ("")
65 ("")
66 ("")
67 ("")
68 ("")
69 ;
70const std::string SaturationPotential::potential_token("saturation");
71
72SaturationPotential::SaturationPotential(
73 const ParticleTypes_t &_ParticleTypes) :
74 SerializablePotential(_ParticleTypes),
75 morse(_ParticleTypes),
76 angle(symmetrizeTypes(_ParticleTypes)),
77 energy_offset(0.)
78{
79 // have some decent defaults for parameter_derivative checking
80 // Morse and Angle have their own defaults, offset is set
81 ASSERT( _ParticleTypes.size() == (size_t)2,
82 "SaturationPotential::SaturationPotential() - exactly two types must be given.");
83 ASSERT( _ParticleTypes[1] == 1,
84 "SaturationPotential::SaturationPotential() - second type must be hydrogen.");
85}
86
87SaturationPotential::SaturationPotential(
88 const ParticleTypes_t &_ParticleTypes,
89 const double _all_energy_offset,
90 const double _morse_spring_constant,
91 const double _morse_equilibrium_distance,
92 const double _morse_dissociation_energy,
93 const double _angle_spring_constant,
94 const double _angle_equilibrium_distance) :
95 SerializablePotential(_ParticleTypes),
96 morse(_ParticleTypes),
97 angle(symmetrizeTypes(_ParticleTypes)),
98 energy_offset(_all_energy_offset)
99{
100 ASSERT( _ParticleTypes.size() == (size_t)2,
101 "SaturationPotential::SaturationPotential() - exactly two types must be given.");
102 ASSERT( _ParticleTypes[1] == 1,
103 "SaturationPotential::SaturationPotential() - second type must be hydrogen.");
104 parameters_t morse_params(morse.getParameterDimension());
105 morse_params[PairPotential_Morse::spring_constant] = _morse_spring_constant;
106 morse_params[PairPotential_Morse::equilibrium_distance] = _morse_equilibrium_distance;
107 morse_params[PairPotential_Morse::dissociation_energy] = _morse_dissociation_energy;
108 morse_params[PairPotential_Morse::energy_offset] = 0.;
109 morse.setParameters(morse_params);
110 parameters_t angle_params(angle.getParameterDimension());
111 angle_params[PairPotential_Angle::spring_constant] = _angle_spring_constant;
112 angle_params[PairPotential_Angle::equilibrium_distance] = _angle_equilibrium_distance;
113 angle_params[PairPotential_Angle::energy_offset] = 0.;
114 angle.setParameters(angle_params);
115}
116
117void SaturationPotential::setParameters(const parameters_t &_params)
118{
119 const size_t paramsDim = _params.size();
120 ASSERT( paramsDim <= getParameterDimension(),
121 "SaturationPotential::setParameters() - we need not more than "
122 +toString(getParameterDimension())+" parameters.");
123// LOG(1, "INFO: Setting new SaturationPotential params: " << _params);
124
125
126 // offsets
127 if (paramsDim > all_energy_offset)
128 energy_offset = _params[all_energy_offset];
129
130 // Morse
131 {
132 parameters_t morse_params(morse.getParameters());
133 if (paramsDim > morse_spring_constant)
134 morse_params[PairPotential_Morse::spring_constant] = _params[morse_spring_constant];
135 if (paramsDim > morse_equilibrium_distance)
136 morse_params[PairPotential_Morse::equilibrium_distance] = _params[morse_equilibrium_distance];
137 if (paramsDim > morse_dissociation_energy)
138 morse_params[PairPotential_Morse::dissociation_energy] = _params[morse_dissociation_energy];
139 morse_params[PairPotential_Morse::energy_offset] = 0.;
140 morse.setParameters(morse_params);
141 }
142
143 // Angle
144 {
145 parameters_t angle_params(angle.getParameters());
146 if (paramsDim > angle_spring_constant)
147 angle_params[PairPotential_Angle::spring_constant] = _params[angle_spring_constant];
148 if (paramsDim > angle_equilibrium_distance)
149 angle_params[PairPotential_Angle::equilibrium_distance] = _params[angle_equilibrium_distance];
150 angle_params[PairPotential_Angle::energy_offset] = 0.;
151 angle.setParameters(angle_params);
152 }
153#ifndef NDEBUG
154 parameters_t check_params(getParameters());
155 check_params.resize(paramsDim); // truncate to same size
156 ASSERT( check_params == _params,
157 "SaturationPotential::setParameters() - failed, mismatch in to be set "
158 +toString(_params)+" and set "+toString(check_params)+" params.");
159#endif
160}
161
162SaturationPotential::parameters_t SaturationPotential::getParameters() const
163{
164 parameters_t params(getParameterDimension());
165 const parameters_t morse_params = morse.getParameters();
166 const parameters_t angle_params = angle.getParameters();
167
168 params[all_energy_offset] = energy_offset;
169
170 params[morse_spring_constant] = morse_params[PairPotential_Morse::spring_constant];
171 params[morse_equilibrium_distance] = morse_params[PairPotential_Morse::equilibrium_distance];
172 params[morse_dissociation_energy] = morse_params[PairPotential_Morse::dissociation_energy];
173
174 params[angle_spring_constant] = angle_params[PairPotential_Angle::spring_constant];
175 params[angle_equilibrium_distance] = angle_params[PairPotential_Angle::equilibrium_distance];
176 return params;
177}
178
179void SaturationPotential::stream_to(std::ostream &ost) const
180{
181 morse.stream_to(ost);
182 ost << std::endl;
183 angle.stream_to(ost);
184}
185
186void SaturationPotential::stream_from(std::istream &ist)
187{
188 morse.stream_from(ist);
189 ist >> ws;
190 angle.stream_from(ist);
191}
192
193std::vector<FunctionModel::arguments_t>
194triplefunction(
195 const argument_t &argument,
196 const FunctionModel::arguments_t& args)
197{
198 const size_t firstindex = argument.indices.first;
199 const size_t secondindex = argument.indices.second;
200// LOG(2, "DEBUG: first index is " << firstindex << ", second index is " << secondindex << ".");
201
202 // place all arguments that share either index into a lookup map
203 typedef std::map< size_t, FunctionModel::arguments_t::const_iterator > IndexLookup_t;
204 IndexLookup_t LookuptoFirst;
205 IndexLookup_t LookuptoSecond;
206 for (FunctionModel::arguments_t::const_iterator iter = args.begin();
207 iter != args.end();
208 ++iter) {
209 if (((*iter).indices.first == argument.indices.first)
210 && ((*iter).indices.second == argument.indices.second))
211 continue;
212 if (firstindex == (*iter).indices.first) {
213 LookuptoFirst.insert( std::make_pair( (*iter).indices.second, iter) );
214 }
215 else if (firstindex == (*iter).indices.second) {
216 LookuptoFirst.insert( std::make_pair( (*iter).indices.first, iter) );
217 }
218 if (secondindex == (*iter).indices.first) {
219 LookuptoSecond.insert( std::make_pair( (*iter).indices.second, iter) );
220 }
221 else if (secondindex == (*iter).indices.second) {
222 LookuptoSecond.insert( std::make_pair((*iter).indices.first, iter) );
223 }
224 }
225// {
226// std::stringstream lookupstream;
227// for (IndexLookup_t::const_iterator iter = LookuptoFirst.begin();
228// iter != LookuptoFirst.end();
229// ++iter) {
230// lookupstream << "(" << iter->first << "," << *(iter->second) << ") ";
231// }
232// LOG(2, "DEBUG: LookupToFirst is " << lookupstream.str() << ".");
233// }
234// {
235// std::stringstream lookupstream;
236// for (IndexLookup_t::const_iterator iter = LookuptoSecond.begin();
237// iter != LookuptoSecond.end();
238// ++iter) {
239// lookupstream << "(" << iter->first << "," << *(iter->second) << ") ";
240// }
241// LOG(2, "DEBUG: LookuptoSecond is " << lookupstream.str() << ".");
242// }
243
244 // now go through the first lookup as the second argument and pick the
245 // corresponding third argument by the matching index
246 std::vector<FunctionModel::arguments_t> results;
247 for (IndexLookup_t::const_iterator iter = LookuptoFirst.begin();
248 iter != LookuptoFirst.end();
249 ++iter) {
250 IndexLookup_t::const_iterator otheriter = LookuptoSecond.find(iter->first);
251 ASSERT( otheriter != LookuptoSecond.end(),
252 "triplefunction() - cannot find index "+toString(iter->first)
253 +" in LookupToSecond");
254 FunctionModel::arguments_t result(1, argument);
255 result.reserve(3);
256 result.push_back(*(iter->second));
257 result.push_back(*(otheriter->second));
258 results.push_back(result);
259 }
260
261 return results;
262}
263
264SaturationPotential::results_t
265SaturationPotential::operator()(
266 const arguments_t &arguments
267 ) const
268{
269 double result = 0.;
270 const ParticleTypes_t &morse_types = morse.getParticleTypes();
271 for(arguments_t::const_iterator argiter = arguments.begin();
272 argiter != arguments.end();
273 ++argiter) {
274 const argument_t &r_ij = *argiter;
275 if (((r_ij.types.first == morse_types[0]) && (r_ij.types.second == morse_types[1]))
276 || ((r_ij.types.first == morse_types[1]) && (r_ij.types.second == morse_types[0]))) {
277 arguments_t args(1, r_ij);
278
279 // Morse contribution
280 const double tmp = morse(args)[0];
281// LOG(3, "DEBUG: Morse yields " << tmp << " for << " << r_ij << ".");
282 result += tmp;
283 if (result != result)
284 ELOG(1, "result is NAN.");
285
286 // Angle contribution
287 {
288 typedef std::vector<FunctionModel::arguments_t> tripleargs_t;
289 tripleargs_t tripleargs =
290 triplefunction(r_ij, arguments);
291 for (tripleargs_t::const_iterator iter = tripleargs.begin();
292 iter != tripleargs.end();
293 ++iter) {
294 FunctionModel::arguments_t tempargs =
295 Extractors::reorderArgumentsByParticleTypes(*iter, angle.getParticleTypes());
296 // We get both angles, e.g. 0-4-1 and 1-4-0, hence multiply with 0.5
297 const double tmp = .5*angle(tempargs)[0]; // as we have all distances we get both jk and kj
298// LOG(3, "DEBUG: angle yields " << tmp << " for << " << tempargs << ".");
299 result += tmp;
300 if (result != result)
301 ELOG(1, "result is NAN.");
302 }
303 }
304 }
305 }
306 return std::vector<result_t>(1, energy_offset + result);
307}
308
309SaturationPotential::derivative_components_t
310SaturationPotential::derivative(
311 const arguments_t &arguments
312 ) const
313{
314 ASSERT( 0,
315 "SaturationPotential::operator() - not implemented.");
316 derivative_components_t result;
317 return result;
318}
319
320SaturationPotential::results_t
321SaturationPotential::parameter_derivative(
322 const arguments_t &arguments,
323 const size_t index
324 ) const
325{
326 double result = 0.;
327 if (index == all_energy_offset) {
328 result = 1.;
329 } else {
330 const ParticleTypes_t &morse_types = morse.getParticleTypes();
331 for(arguments_t::const_iterator argiter = arguments.begin();
332 argiter != arguments.end();
333 ++argiter) {
334 const argument_t &r_ij = *argiter;
335 if (((r_ij.types.first == morse_types[0]) && (r_ij.types.second == morse_types[1]))
336 || ((r_ij.types.first == morse_types[1]) && (r_ij.types.second == morse_types[0]))) {
337 arguments_t args(1, r_ij);
338
339 switch (index) {
340 case morse_spring_constant:
341 result += morse.parameter_derivative(args, PairPotential_Morse::spring_constant)[0];
342 break;
343 case morse_equilibrium_distance:
344 result += morse.parameter_derivative(args, PairPotential_Morse::equilibrium_distance)[0];
345 break;
346 case morse_dissociation_energy:
347 result += morse.parameter_derivative(args, PairPotential_Morse::dissociation_energy)[0];
348 break;
349 case angle_spring_constant:
350 case angle_equilibrium_distance:
351 {
352 typedef std::vector<FunctionModel::arguments_t> tripleargs_t;
353 tripleargs_t tripleargs =
354 triplefunction(r_ij, arguments);
355 for (tripleargs_t::const_iterator iter = tripleargs.begin();
356 iter != tripleargs.end();
357 ++iter) {
358 FunctionModel::arguments_t tempargs =
359 Extractors::reorderArgumentsByParticleTypes(*iter, angle.getParticleTypes());
360 // We get both angles, e.g. 0-4-1 and 1-4-0, hence multiply with 0.5
361 if (index == angle_spring_constant)
362 result += .5*angle.parameter_derivative(tempargs, PairPotential_Angle::spring_constant)[0];
363 else if (index == angle_equilibrium_distance)
364 result += .5*angle.parameter_derivative(tempargs, PairPotential_Angle::equilibrium_distance)[0];
365// LOG(2, "DEBUG: angle yields " << tmp << " for << " << arguments << ".");
366// result += tmp;
367 if (result != result)
368 ELOG(1, "result is NAN.");
369 }
370 }
371 break;
372 default:
373 ASSERT( 0, "SaturationPotential::parameter_derivative() - impossible to get here.");
374 break;
375 }
376 }
377 }
378 }
379 return SaturationPotential::results_t(1, result);
380}
381
382const SaturationPotential::ParticleTypes_t
383SaturationPotential::symmetrizeTypes(const ParticleTypes_t &_ParticleTypes)
384{
385 ASSERT( _ParticleTypes.size() == (size_t)2,
386 "SaturationPotential::symmetrizeTypes() - require initial _ParticleTypes with two elements.");
387// // insert before couple
388// ParticleTypes_t types(1, _ParticleTypes[1]);
389// types.insert(types.end(), _ParticleTypes.begin(), _ParticleTypes.end());
390 // insert after the couple
391 ParticleTypes_t types(_ParticleTypes);
392 types.push_back( _ParticleTypes.back() );
393 ASSERT( types.size() == (size_t)3,
394 "SaturationPotential::symmetrizeTypes() - failed to generate three types for angle.");
395 return types;
396}
397
398FunctionModel::extractor_t
399SaturationPotential::getFragmentSpecificExtractor() const
400{
401 Fragment::charges_t charges;
402 charges.resize(getParticleTypes().size());
403 std::transform(getParticleTypes().begin(), getParticleTypes().end(),
404 charges.begin(), boost::lambda::_1);
405 FunctionModel::extractor_t returnfunction;
406 if (charges[0] == charges[1]) {
407 // In case both types are equal there is only a single pair of possible
408 // type combinations.
409 returnfunction =
410 boost::bind(&Extractors::gatherAllDistancesFromFragment,
411 boost::bind(&Fragment::getPositions, _1),
412 boost::bind(&Fragment::getCharges, _1),
413 charges, // is only temporarily created, hence copy
414 _2);
415 } else {
416 // we have to chain here a rather complex "tree" of functions
417 // as we only have a couple of ParticleTypes but need to get
418 // all possible three pairs of the set of the two types.
419 // Finally, we also need to arrange them in correct order
420 // (for PairPotentiale_Angle).
421 //charges_t firstpair(2, boost::cref(charges[0]));
422 // only that saturation potential never has its middle element twice!
423 // hence, we skip the firstpair but keep the code for later generalization
424 Fragment::charges_t secondpair(2, boost::cref(charges[1]));
425 const Fragment::charges_t &thirdpair = charges;
426 returnfunction =
427// boost::bind(&Extractors::reorderArgumentsByParticleTypes,
428 boost::bind(&Extractors::combineArguments,
429// boost::bind(&Extractors::combineArguments,
430// boost::bind(&Extractors::gatherAllDistancesFromFragment,
431// boost::bind(&Fragment::getPositions, _1),
432// boost::bind(&Fragment::getCharges, _1),
433// firstpair, // no crefs here as are temporaries!
434// _2),
435 boost::bind(&Extractors::gatherAllDistancesFromFragment,
436 boost::bind(&Fragment::getPositions, _1),
437 boost::bind(&Fragment::getCharges, _1),
438 secondpair, // no crefs here as are temporaries!
439 _2),
440// ),
441 boost::bind(&Extractors::gatherAllDistancesFromFragment,
442 boost::bind(&Fragment::getPositions, _1),
443 boost::bind(&Fragment::getCharges, _1),
444 boost::cref(thirdpair), // only the last one is no temporary
445 _2)
446 );
447// boost::cref(angle.getParticleTypes())
448// );
449}
450 return returnfunction;
451}
452
453void
454SaturationPotential::setParametersToRandomInitialValues(
455 const TrainingData &data)
456{
457 energy_offset = data.getTrainingOutputAverage()[0];
458 morse.setParametersToRandomInitialValues(data);
459 angle.setParametersToRandomInitialValues(data);
460}
Note: See TracBrowser for help on using the repository browser.