source: src/Actions/PotentialAction/FitPotentialAction.cpp@ 93909a

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 93909a was f5724f, checked in by Frederik Heber <heber@…>, 12 years ago

Moved all FragmentationActions related to potentials into own menu and folder.

  • changed class names Fragmentation... -> Potential...
  • changed tokens in GlobalListOfActions.
  • added menu entry "potential" and CommandLineParser program_options variable.
  • moved regression tests into own folder as well and renamed folder in files.
  • Property mode set to 100644
File size: 13.9 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
115Action::state_ptr PotentialFitPotentialAction::performCall() {
116 // fragment specifies the homology fragment to use
117 SerializablePotential::ParticleTypes_t fragmentnumbers;
118 {
119 const std::vector<const element *> &fragment = params.fragment.get();
120 std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
121 boost::bind(&element::getAtomicNumber, _1));
122 }
123
124 // either charges and a potential is specified or a file
125 if (boost::filesystem::exists(params.potential_file.get())) {
126 std::ifstream returnstream(params.potential_file.get().string().c_str());
127 if (returnstream.good()) {
128 try {
129 PotentialDeserializer deserialize(returnstream);
130 deserialize();
131 } catch (SerializablePotentialMissingValueException &e) {
132 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
133 ELOG(1, "Missing value when parsing information for potential "
134 << *key << ".");
135 else
136 ELOG(1, "Missing value parsing information for potential with unknown key.");
137 return Action::failure;
138 } catch (SerializablePotentialIllegalKeyException &e) {
139 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
140 ELOG(1, "Illegal key parsing information for potential "
141 << *key << ".");
142 else
143 ELOG(1, "Illegal key parsing information for potential with unknown key.");
144 return Action::failure;
145 }
146 } else {
147 ELOG(0, "Failed to parse from " << params.potential_file.get().string() << ".");
148 return Action::failure;
149 }
150 returnstream.close();
151
152 LOG(0, "STATUS: I'm training now a set of potentials parsed from "
153 << params.potential_file.get().string() << " on a fragment "
154 << fragmentnumbers << " on data from World's homologies.");
155
156 } else {
157 if (params.charges.get().empty()) {
158 ELOG(1, "Neither charges nor potential file given!");
159 return Action::failure;
160 } else {
161 // charges specify the potential type
162 SerializablePotential::ParticleTypes_t chargenumbers;
163 {
164 const std::vector<const element *> &charges = params.charges.get();
165 std::transform(charges.begin(), charges.end(), std::back_inserter(chargenumbers),
166 boost::bind(&element::getAtomicNumber, _1));
167 }
168
169 LOG(0, "STATUS: I'm training now a " << params.potentialtype.get()
170 << " potential on charges " << chargenumbers << " on data from World's homologies.");
171
172 // register desired potential and an additional constant one
173 EmpiricalPotential *potential =
174 PotentialFactory::getInstance().createInstance(
175 params.potentialtype.get(),
176 chargenumbers);
177 PotentialRegistry::getInstance().registerInstance(potential);
178 EmpiricalPotential *constant =
179 PotentialFactory::getInstance().createInstance(
180 std::string("constant"),
181 SerializablePotential::ParticleTypes_t());
182 PotentialRegistry::getInstance().registerInstance(constant);
183 }
184 }
185
186 // parse homologies into container
187 HomologyContainer &homologies = World::getInstance().getHomologies();
188
189 // first we try to look into the HomologyContainer
190 LOG(1, "INFO: Listing all present homologies ...");
191 for (HomologyContainer::container_t::const_iterator iter =
192 homologies.begin(); iter != homologies.end(); ++iter) {
193 LOG(1, "INFO: graph " << iter->first
194 << " has Fragment " << iter->second.fragment
195 << ", associated energy " << iter->second.energy
196 << ", and sampled grid integral " << iter->second.charge_distribution.integral()
197 << ".");
198 }
199
200 // then we ought to pick the right HomologyGraph ...
201 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
202 if (graph != HomologyGraph()) {
203 LOG(1, "First representative graph containing fragment "
204 << fragmentnumbers << " is " << graph << ".");
205 } else {
206 ELOG(1, "Specific fragment " << fragmentnumbers << " not found in homologies!");
207 return Action::failure;
208 }
209
210 // fit potential
211 FunctionModel *model = new CompoundPotential(graph);
212 ASSERT( model != NULL,
213 "PotentialFitPotentialAction::performCall() - model is NULL.");
214
215 /******************** TRAINING ********************/
216 // fit potential
217 FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
218 {
219 // Afterwards we go through all of this type and gather the distance and the energy value
220 TrainingData data(model->getSpecificFilter());
221 data(homologies.getHomologousGraphs(graph));
222
223 // print distances and energies if desired for debugging
224 if (!data.getTrainingInputs().empty()) {
225 // print which distance is which
226 size_t counter=1;
227 if (DoLog(3)) {
228 const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
229 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
230 iter != inputs.end(); ++iter) {
231 const argument_t &arg = *iter;
232 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
233 << arg.indices.first << "c" << arg.types.first << ","
234 << arg.indices.second << "c" << arg.types.second << ").");
235 }
236 }
237
238 // print table
239 if (params.training_file.get().string().empty()) {
240 LOG(3, "DEBUG: I gathered the following training data:\n" <<
241 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
242 } else {
243 std::ofstream trainingstream(params.training_file.get().string().c_str());
244 if (trainingstream.good()) {
245 LOG(3, "DEBUG: Writing training data to file " <<
246 params.training_file.get().string() << ".");
247 trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable());
248 }
249 trainingstream.close();
250 }
251 }
252
253 // now perform the function approximation by optimizing the model function
254 FunctionApproximation approximator(data, *model);
255 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
256 double l2error = std::numeric_limits<double>::max();
257 // seed with current time
258 srand((unsigned)time(0));
259 unsigned int runs=0;
260 // threshold overrules max_runs
261 const double threshold = params.threshold.get();
262 const unsigned int max_runs = (threshold >= 1.) ?
263 (params.best_of_howmany.isSet() ? params.best_of_howmany.get() : 1) : 0;
264 LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << ".");
265 do {
266 // generate new random initial parameter values
267 model->setParametersToRandomInitialValues(data);
268 LOG(1, "INFO: Initial parameters of run " << runs << " are "
269 << model->getParameters() << ".");
270 approximator(FunctionApproximation::ParameterDerivative);
271 LOG(1, "INFO: Final parameters of run " << runs << " are "
272 << model->getParameters() << ".");
273 const double new_l2error = data.getL2Error(*model);
274 if (new_l2error < l2error) {
275 // store currently best parameters
276 l2error = new_l2error;
277 bestparams = model->getParameters();
278 LOG(1, "STATUS: New fit from run " << runs
279 << " has better error of " << l2error << ".");
280 }
281 } while (( ++runs < max_runs) || (l2error > threshold));
282 // reset parameters from best fit
283 model->setParameters(bestparams);
284 LOG(1, "INFO: Best parameters with L2 error of "
285 << l2error << " are " << model->getParameters() << ".");
286 } else {
287 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
288 return Action::failure;
289 }
290
291 // create a map of each fragment with error.
292 typedef std::multimap< double, size_t > WorseFragmentMap_t;
293 WorseFragmentMap_t WorseFragmentMap;
294 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
295 // fragments make it into the container in reversed order, hence count from top down
296 size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
297 for (HomologyContainer::const_iterator iter = fragmentrange.first;
298 iter != fragmentrange.second;
299 ++iter) {
300 const Fragment& fragment = iter->second.fragment;
301 const double &energy = iter->second.energy;
302
303 // create arguments from the fragment
304 FunctionModel::extractor_t extractor = model->getSpecificExtractor();
305 FunctionModel::arguments_t args = extractor(fragment, 1);
306
307 // calculate value from potential
308 const double fitvalue = (*model)(args)[0];
309
310 // insert difference into map
311 const double error = fabs(energy - fitvalue);
312 WorseFragmentMap.insert( std::make_pair( error, index-- ) );
313
314 {
315 // give only the distances in the debugging text
316 std::stringstream streamargs;
317 BOOST_FOREACH (argument_t arg, args) {
318 streamargs << " " << arg.distance*AtomicLengthToAngstroem;
319 }
320 LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
321 << "| = " << error << " for args " << streamargs.str() << ".");
322 }
323 }
324 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
325
326 // print fitted potentials
327 std::stringstream potentials;
328 PotentialSerializer serialize(potentials);
329 serialize();
330 LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str());
331 std::ofstream returnstream(params.potential_file.get().string().c_str());
332 if (returnstream.good()) {
333 returnstream << potentials.str();
334 }
335 }
336 delete model;
337
338 return Action::success;
339}
340
341Action::state_ptr PotentialFitPotentialAction::performUndo(Action::state_ptr _state) {
342 return Action::success;
343}
344
345Action::state_ptr PotentialFitPotentialAction::performRedo(Action::state_ptr _state){
346 return Action::success;
347}
348
349bool PotentialFitPotentialAction::canUndo() {
350 return false;
351}
352
353bool PotentialFitPotentialAction::shouldUndo() {
354 return false;
355}
356/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.