source: src/Actions/PotentialAction/FitPotentialAction.cpp@ 550f2a

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 550f2a was e1fe7e, checked in by Frederik Heber <heber@…>, 11 years ago

FunctionModel now uses list_of_arguments to split sequence of subsets of distances.

  • this fixes ambiguities with the set of distances: Imagine the distances within a water molecule as OH (A) and HH (B). We then may have a sequence of argument_t as AABAAB. And with the current implementation of CompoundPotential::splitUpArgumentsByModels() we would always choose the latter (and more complex) model. Hence, we make two calls to TriplePotential_Angle, instead of calls twice to PairPotential_Harmonic for A, one to PairPotential_Harmonic for B, and once to TriplePotential_Angle for AAB.
  • now, we new list looks like A,A,B,AAB where each tuple of distances can be uniquely associated with a specific potential.
  • changed signatures of EmpiricalPotential::operator(), ::derivative(), ::parameter_derivative(). This involved changing all of the current specific potentials and CompoundPotential.
  • TrainingData must discern between the InputVector_t (just all distances) and the FilteredInputVector_t (tuples of subsets of distances).
  • FunctionApproximation now has list_of_arguments_t as parameter to evaluate() and evaluate_derivative().
  • DOCU: docu change in TrainingData.
  • Property mode set to 100644
File size: 13.5 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 * FitPotentialAction.cpp
26 *
27 * Created on: Apr 09, 2013
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36// needs to come before MemDebug due to placement new
37#include <boost/archive/text_iarchive.hpp>
38
39#include "CodePatterns/MemDebug.hpp"
40
41#include <algorithm>
42#include <boost/bind.hpp>
43#include <boost/filesystem.hpp>
44#include <boost/foreach.hpp>
45#include <map>
46#include <string>
47#include <sstream>
48
49#include "Actions/PotentialAction/FitPotentialAction.hpp"
50
51#include "CodePatterns/Log.hpp"
52
53#include "Element/element.hpp"
54#include "Fragmentation/Homology/HomologyContainer.hpp"
55#include "Fragmentation/Homology/HomologyGraph.hpp"
56#include "Fragmentation/Summation/SetValues/Fragment.hpp"
57#include "FunctionApproximation/Extractors.hpp"
58#include "FunctionApproximation/FunctionApproximation.hpp"
59#include "FunctionApproximation/FunctionModel.hpp"
60#include "FunctionApproximation/TrainingData.hpp"
61#include "FunctionApproximation/writeDistanceEnergyTable.hpp"
62#include "Potentials/CompoundPotential.hpp"
63#include "Potentials/Exceptions.hpp"
64#include "Potentials/PotentialDeserializer.hpp"
65#include "Potentials/PotentialFactory.hpp"
66#include "Potentials/PotentialRegistry.hpp"
67#include "Potentials/PotentialSerializer.hpp"
68#include "Potentials/SerializablePotential.hpp"
69
70using namespace MoleCuilder;
71
72// and construct the stuff
73#include "FitPotentialAction.def"
74#include "Action_impl_pre.hpp"
75/** =========== define the function ====================== */
76
77HomologyGraph getFirstGraphwithSpecifiedElements(
78 const HomologyContainer &homologies,
79 const SerializablePotential::ParticleTypes_t &types)
80{
81 ASSERT( !types.empty(),
82 "getFirstGraphwithSpecifiedElements() - charges is empty?");
83 // create charges
84 Fragment::charges_t charges;
85 charges.resize(types.size());
86 std::transform(types.begin(), types.end(),
87 charges.begin(), boost::lambda::_1);
88 // convert into count map
89 Extractors::elementcounts_t counts_per_charge =
90 Extractors::_detail::getElementCounts(charges);
91 ASSERT( !counts_per_charge.empty(),
92 "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
93 LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
94 // we want to check each (unique) key only once
95 HomologyContainer::const_key_iterator olditer = homologies.key_end();
96 for (HomologyContainer::const_key_iterator iter =
97 homologies.key_begin(); iter != homologies.key_end(); olditer = iter++) {
98 // if it's the same as the old one, skip it
99 if (*olditer == *iter)
100 continue;
101 // if it's a new key, check if every element has the right number of counts
102 Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
103 for (; countiter != counts_per_charge.end(); ++countiter)
104 if (!(*iter).hasTimesAtomicNumber(
105 static_cast<size_t>(countiter->first),
106 static_cast<size_t>(countiter->second))
107 )
108 break;
109 if( countiter == counts_per_charge.end())
110 return *iter;
111 }
112 return HomologyGraph();
113}
114
115SerializablePotential::ParticleTypes_t getNumbersFromElements(
116 const std::vector<const element *> &fragment)
117{
118 SerializablePotential::ParticleTypes_t fragmentnumbers;
119 std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
120 boost::bind(&element::getAtomicNumber, _1));
121 return fragmentnumbers;
122}
123
124
125ActionState::ptr PotentialFitPotentialAction::performCall() {
126 // fragment specifies the homology fragment to use
127 SerializablePotential::ParticleTypes_t fragmentnumbers =
128 getNumbersFromElements(params.fragment.get());
129
130 // either charges and a potential is specified or a file
131 if (boost::filesystem::exists(params.potential_file.get())) {
132 std::ifstream returnstream(params.potential_file.get().string().c_str());
133 if (returnstream.good()) {
134 try {
135 PotentialDeserializer deserialize(returnstream);
136 deserialize();
137 } catch (SerializablePotentialMissingValueException &e) {
138 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
139 ELOG(1, "Missing value when parsing information for potential "
140 << *key << ".");
141 else
142 ELOG(1, "Missing value parsing information for potential with unknown key.");
143 return Action::failure;
144 } catch (SerializablePotentialIllegalKeyException &e) {
145 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
146 ELOG(1, "Illegal key parsing information for potential "
147 << *key << ".");
148 else
149 ELOG(1, "Illegal key parsing information for potential with unknown key.");
150 return Action::failure;
151 }
152 } else {
153 ELOG(0, "Failed to parse from " << params.potential_file.get().string() << ".");
154 return Action::failure;
155 }
156 returnstream.close();
157
158 LOG(0, "STATUS: I'm training now a set of potentials parsed from "
159 << params.potential_file.get().string() << " on a fragment "
160 << fragmentnumbers << " on data from World's homologies.");
161
162 } else {
163 if (params.charges.get().empty()) {
164 ELOG(1, "Neither charges nor potential file given!");
165 return Action::failure;
166 } else {
167 // charges specify the potential type
168 SerializablePotential::ParticleTypes_t chargenumbers =
169 getNumbersFromElements(params.charges.get());
170
171 LOG(0, "STATUS: I'm training now a " << params.potentialtype.get()
172 << " potential on charges " << chargenumbers << " on data from World's homologies.");
173
174 // register desired potential and an additional constant one
175 {
176 EmpiricalPotential *potential =
177 PotentialFactory::getInstance().createInstance(
178 params.potentialtype.get(),
179 chargenumbers);
180 // check whether such a potential already exists
181 const std::string potential_name = potential->getName();
182 if (PotentialRegistry::getInstance().isPresentByName(potential_name)) {
183 delete potential;
184 potential = PotentialRegistry::getInstance().getByName(potential_name);
185 } else
186 PotentialRegistry::getInstance().registerInstance(potential);
187 }
188 {
189 EmpiricalPotential *constant =
190 PotentialFactory::getInstance().createInstance(
191 std::string("constant"),
192 SerializablePotential::ParticleTypes_t());
193 // check whether such a potential already exists
194 const std::string constant_name = constant->getName();
195 if (PotentialRegistry::getInstance().isPresentByName(constant_name)) {
196 delete constant;
197 constant = PotentialRegistry::getInstance().getByName(constant_name);
198 } else
199 PotentialRegistry::getInstance().registerInstance(constant);
200 }
201 }
202 }
203
204 // parse homologies into container
205 HomologyContainer &homologies = World::getInstance().getHomologies();
206
207 // first we try to look into the HomologyContainer
208 LOG(1, "INFO: Listing all present homologies ...");
209 for (HomologyContainer::container_t::const_iterator iter =
210 homologies.begin(); iter != homologies.end(); ++iter) {
211 LOG(1, "INFO: graph " << iter->first
212 << " has Fragment " << iter->second.fragment
213 << ", associated energy " << iter->second.energy
214 << ", and sampled grid integral " << iter->second.charge_distribution.integral()
215 << ".");
216 }
217
218 // then we ought to pick the right HomologyGraph ...
219 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
220 if (graph != HomologyGraph()) {
221 LOG(1, "First representative graph containing fragment "
222 << fragmentnumbers << " is " << graph << ".");
223 } else {
224 ELOG(1, "Specific fragment " << fragmentnumbers << " not found in homologies!");
225 return Action::failure;
226 }
227
228 // fit potential
229 FunctionModel *model = new CompoundPotential(graph);
230 ASSERT( model != NULL,
231 "PotentialFitPotentialAction::performCall() - model is NULL.");
232
233 /******************** TRAINING ********************/
234 // fit potential
235 FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
236 {
237 // Afterwards we go through all of this type and gather the distance and the energy value
238 TrainingData data(model->getSpecificFilter());
239 data(homologies.getHomologousGraphs(graph));
240
241 // print distances and energies if desired for debugging
242 if (!data.getTrainingInputs().empty()) {
243 // print which distance is which
244 size_t counter=1;
245 if (DoLog(3)) {
246 const FunctionModel::arguments_t &inputs = data.getAllArguments()[0];
247 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
248 iter != inputs.end(); ++iter) {
249 const argument_t &arg = *iter;
250 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
251 << arg.indices.first << "c" << arg.types.first << ","
252 << arg.indices.second << "c" << arg.types.second << ").");
253 }
254 }
255
256 // print table
257 if (params.training_file.get().string().empty()) {
258 LOG(3, "DEBUG: I gathered the following training data:\n" <<
259 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
260 } else {
261 std::ofstream trainingstream(params.training_file.get().string().c_str());
262 if (trainingstream.good()) {
263 LOG(3, "DEBUG: Writing training data to file " <<
264 params.training_file.get().string() << ".");
265 trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable());
266 }
267 trainingstream.close();
268 }
269 }
270
271 if ((params.threshold.get() < 1) && (params.best_of_howmany.isSet()))
272 ELOG(2, "threshold parameter always overrules max_runs, both are specified.");
273 // now perform the function approximation by optimizing the model function
274 FunctionApproximation approximator(data, *model);
275 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
276 double l2error = std::numeric_limits<double>::max();
277 // seed with current time
278 srand((unsigned)time(0));
279 unsigned int runs=0;
280 // threshold overrules max_runs
281 const double threshold = params.threshold.get();
282 const unsigned int max_runs = (threshold >= 1.) ?
283 (params.best_of_howmany.isSet() ? params.best_of_howmany.get() : 1) : 0;
284 LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << ".");
285 do {
286 // generate new random initial parameter values
287 model->setParametersToRandomInitialValues(data);
288 LOG(1, "INFO: Initial parameters of run " << runs << " are "
289 << model->getParameters() << ".");
290 approximator(FunctionApproximation::ParameterDerivative);
291 LOG(1, "INFO: Final parameters of run " << runs << " are "
292 << model->getParameters() << ".");
293 const double new_l2error = data.getL2Error(*model);
294 if (new_l2error < l2error) {
295 // store currently best parameters
296 l2error = new_l2error;
297 bestparams = model->getParameters();
298 LOG(1, "STATUS: New fit from run " << runs
299 << " has better error of " << l2error << ".");
300 }
301 } while (( ++runs < max_runs) || (l2error > threshold));
302 // reset parameters from best fit
303 model->setParameters(bestparams);
304 LOG(1, "INFO: Best parameters with L2 error of "
305 << l2error << " are " << model->getParameters() << ".");
306 } else {
307 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
308 return Action::failure;
309 }
310
311 // create a map of each fragment with error.
312 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
313 TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap =
314 data.getWorstFragmentMap(*model, fragmentrange);
315 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
316
317 // print fitted potentials
318 std::stringstream potentials;
319 PotentialSerializer serialize(potentials);
320 serialize();
321 LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str());
322 std::ofstream returnstream(params.potential_file.get().string().c_str());
323 if (returnstream.good()) {
324 returnstream << potentials.str();
325 }
326 }
327 delete model;
328
329 return Action::success;
330}
331
332ActionState::ptr PotentialFitPotentialAction::performUndo(ActionState::ptr _state) {
333 return Action::success;
334}
335
336ActionState::ptr PotentialFitPotentialAction::performRedo(ActionState::ptr _state){
337 return Action::success;
338}
339
340bool PotentialFitPotentialAction::canUndo() {
341 return false;
342}
343
344bool PotentialFitPotentialAction::shouldUndo() {
345 return false;
346}
347/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.