source: src/Actions/PotentialAction/FitPotentialAction.cpp@ c73e35

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 Candidate_v1.7.0 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 c73e35 was 26b4d62, checked in by Frederik Heber <heber@…>, 11 years ago

All Actions now give correct failure status via STATUS() macro.

  • Property mode set to 100644
File size: 14.5 KB
RevLine 
[48d20d]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
[5aaa43]5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
[48d20d]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
[f5724f]49#include "Actions/PotentialAction/FitPotentialAction.hpp"
[48d20d]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"
[baccf6]62#include "Potentials/CompoundPotential.hpp"
[49dcf7]63#include "Potentials/Exceptions.hpp"
[baccf6]64#include "Potentials/PotentialDeserializer.hpp"
[48d20d]65#include "Potentials/PotentialFactory.hpp"
[baccf6]66#include "Potentials/PotentialRegistry.hpp"
67#include "Potentials/PotentialSerializer.hpp"
[48d20d]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)
[3536a5f]104 if (!(*iter).hasTimesAtomicNumber(
105 static_cast<size_t>(countiter->first),
106 static_cast<size_t>(countiter->second))
107 )
[48d20d]108 break;
109 if( countiter == counts_per_charge.end())
110 return *iter;
111 }
112 return HomologyGraph();
113}
114
[b5b01e]115ActionState::ptr PotentialFitPotentialAction::performCall() {
[48d20d]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
[baccf6]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()) {
[49dcf7]128 try {
129 PotentialDeserializer deserialize(returnstream);
130 deserialize();
131 } catch (SerializablePotentialMissingValueException &e) {
132 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
[26b4d62]133 STATUS("Missing value when parsing information for potential "+*key+".");
[49dcf7]134 else
[26b4d62]135 STATUS("Missing value parsing information for potential with unknown key.");
[49dcf7]136 return Action::failure;
137 } catch (SerializablePotentialIllegalKeyException &e) {
138 if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e))
[26b4d62]139 STATUS("Illegal key parsing information for potential "+*key+".");
[49dcf7]140 else
[26b4d62]141 STATUS("Illegal key parsing information for potential with unknown key.");
[49dcf7]142 return Action::failure;
143 }
[baccf6]144 } else {
[26b4d62]145 STATUS("Failed to parse from "+params.potential_file.get().string()+".");
[baccf6]146 return Action::failure;
147 }
148 returnstream.close();
149
150 LOG(0, "STATUS: I'm training now a set of potentials parsed from "
151 << params.potential_file.get().string() << " on a fragment "
[d449a9]152 << fragmentnumbers << " on data from World's homologies.");
[baccf6]153
154 } else {
155 if (params.charges.get().empty()) {
[26b4d62]156 STATUS("Neither charges nor potential file given!");
[baccf6]157 return Action::failure;
158 } else {
159 // charges specify the potential type
160 SerializablePotential::ParticleTypes_t chargenumbers;
161 {
162 const std::vector<const element *> &charges = params.charges.get();
163 std::transform(charges.begin(), charges.end(), std::back_inserter(chargenumbers),
164 boost::bind(&element::getAtomicNumber, _1));
165 }
166
167 LOG(0, "STATUS: I'm training now a " << params.potentialtype.get()
[d449a9]168 << " potential on charges " << chargenumbers << " on data from World's homologies.");
[baccf6]169
170 // register desired potential and an additional constant one
[c34711]171 {
172 EmpiricalPotential *potential =
173 PotentialFactory::getInstance().createInstance(
174 params.potentialtype.get(),
175 chargenumbers);
176 // check whether such a potential already exists
177 const std::string potential_name = potential->getName();
178 if (PotentialRegistry::getInstance().isPresentByName(potential_name)) {
179 delete potential;
180 potential = PotentialRegistry::getInstance().getByName(potential_name);
181 } else
182 PotentialRegistry::getInstance().registerInstance(potential);
183 }
184 {
185 EmpiricalPotential *constant =
186 PotentialFactory::getInstance().createInstance(
187 std::string("constant"),
188 SerializablePotential::ParticleTypes_t());
189 // check whether such a potential already exists
190 const std::string constant_name = constant->getName();
191 if (PotentialRegistry::getInstance().isPresentByName(constant_name)) {
192 delete constant;
193 constant = PotentialRegistry::getInstance().getByName(constant_name);
194 } else
195 PotentialRegistry::getInstance().registerInstance(constant);
196 }
[baccf6]197 }
198 }
199
[48d20d]200 // parse homologies into container
[d449a9]201 HomologyContainer &homologies = World::getInstance().getHomologies();
[48d20d]202
203 // first we try to look into the HomologyContainer
204 LOG(1, "INFO: Listing all present homologies ...");
205 for (HomologyContainer::container_t::const_iterator iter =
206 homologies.begin(); iter != homologies.end(); ++iter) {
[bf1d1b]207 LOG(1, "INFO: graph " << iter->first
208 << " has Fragment " << iter->second.fragment
209 << ", associated energy " << iter->second.energy
210 << ", and sampled grid integral " << iter->second.charge_distribution.integral()
211 << ".");
[48d20d]212 }
213
[baccf6]214 // then we ought to pick the right HomologyGraph ...
215 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
216 if (graph != HomologyGraph()) {
217 LOG(1, "First representative graph containing fragment "
218 << fragmentnumbers << " is " << graph << ".");
219 } else {
[26b4d62]220 STATUS("Specific fragment "+toString(fragmentnumbers)+" not found in homologies!");
[baccf6]221 return Action::failure;
222 }
223
224 // fit potential
225 FunctionModel *model = new CompoundPotential(graph);
226 ASSERT( model != NULL,
[f5724f]227 "PotentialFitPotentialAction::performCall() - model is NULL.");
[48d20d]228
229 /******************** TRAINING ********************/
230 // fit potential
231 FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
232 {
[baccf6]233 // Afterwards we go through all of this type and gather the distance and the energy value
[af2c7ec]234 TrainingData data(model->getSpecificFilter());
[baccf6]235 data(homologies.getHomologousGraphs(graph));
[48d20d]236
[baccf6]237 // print distances and energies if desired for debugging
238 if (!data.getTrainingInputs().empty()) {
239 // print which distance is which
240 size_t counter=1;
241 if (DoLog(3)) {
242 const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
243 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
244 iter != inputs.end(); ++iter) {
245 const argument_t &arg = *iter;
246 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
247 << arg.indices.first << "c" << arg.types.first << ","
248 << arg.indices.second << "c" << arg.types.second << ").");
[48d20d]249 }
250 }
251
[baccf6]252 // print table
[a504946]253 if (params.training_file.get().string().empty()) {
254 LOG(3, "DEBUG: I gathered the following training data:\n" <<
255 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
256 } else {
257 std::ofstream trainingstream(params.training_file.get().string().c_str());
258 if (trainingstream.good()) {
259 LOG(3, "DEBUG: Writing training data to file " <<
260 params.training_file.get().string() << ".");
261 trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable());
262 }
263 trainingstream.close();
264 }
[baccf6]265 }
266
267 // now perform the function approximation by optimizing the model function
268 FunctionApproximation approximator(data, *model);
269 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
[4792ab]270 double l2error = std::numeric_limits<double>::max();
[baccf6]271 // seed with current time
272 srand((unsigned)time(0));
[4792ab]273 unsigned int runs=0;
274 // threshold overrules max_runs
275 const double threshold = params.threshold.get();
276 const unsigned int max_runs = (threshold >= 1.) ?
277 (params.best_of_howmany.isSet() ? params.best_of_howmany.get() : 1) : 0;
278 LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << ".");
279 do {
[baccf6]280 // generate new random initial parameter values
281 model->setParametersToRandomInitialValues(data);
282 LOG(1, "INFO: Initial parameters of run " << runs << " are "
283 << model->getParameters() << ".");
284 approximator(FunctionApproximation::ParameterDerivative);
285 LOG(1, "INFO: Final parameters of run " << runs << " are "
286 << model->getParameters() << ".");
287 const double new_l2error = data.getL2Error(*model);
288 if (new_l2error < l2error) {
289 // store currently best parameters
290 l2error = new_l2error;
291 bestparams = model->getParameters();
292 LOG(1, "STATUS: New fit from run " << runs
293 << " has better error of " << l2error << ".");
[48d20d]294 }
[4792ab]295 } while (( ++runs < max_runs) || (l2error > threshold));
[baccf6]296 // reset parameters from best fit
297 model->setParameters(bestparams);
298 LOG(1, "INFO: Best parameters with L2 error of "
299 << l2error << " are " << model->getParameters() << ".");
300 } else {
[26b4d62]301 STATUS("No required parameter derivatives for a box constraint minimization known.");
[baccf6]302 return Action::failure;
303 }
304
305 // create a map of each fragment with error.
306 typedef std::multimap< double, size_t > WorseFragmentMap_t;
307 WorseFragmentMap_t WorseFragmentMap;
308 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
309 // fragments make it into the container in reversed order, hence count from top down
310 size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
311 for (HomologyContainer::const_iterator iter = fragmentrange.first;
312 iter != fragmentrange.second;
313 ++iter) {
[bf1d1b]314 const Fragment& fragment = iter->second.fragment;
315 const double &energy = iter->second.energy;
[48d20d]316
[baccf6]317 // create arguments from the fragment
[f0025d]318 FunctionModel::extractor_t extractor = model->getSpecificExtractor();
[baccf6]319 FunctionModel::arguments_t args = extractor(fragment, 1);
320
321 // calculate value from potential
322 const double fitvalue = (*model)(args)[0];
323
324 // insert difference into map
325 const double error = fabs(energy - fitvalue);
326 WorseFragmentMap.insert( std::make_pair( error, index-- ) );
327
328 {
329 // give only the distances in the debugging text
330 std::stringstream streamargs;
331 BOOST_FOREACH (argument_t arg, args) {
332 streamargs << " " << arg.distance*AtomicLengthToAngstroem;
333 }
334 LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
335 << "| = " << error << " for args " << streamargs.str() << ".");
[48d20d]336 }
337 }
[baccf6]338 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
339
340 // print fitted potentials
341 std::stringstream potentials;
342 PotentialSerializer serialize(potentials);
343 serialize();
344 LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str());
[62164d]345 std::ofstream returnstream(params.potential_file.get().string().c_str());
346 if (returnstream.good()) {
347 returnstream << potentials.str();
348 }
[48d20d]349 }
350 delete model;
351
352 return Action::success;
353}
354
[b5b01e]355ActionState::ptr PotentialFitPotentialAction::performUndo(ActionState::ptr _state) {
[48d20d]356 return Action::success;
357}
358
[b5b01e]359ActionState::ptr PotentialFitPotentialAction::performRedo(ActionState::ptr _state){
[48d20d]360 return Action::success;
361}
362
[f5724f]363bool PotentialFitPotentialAction::canUndo() {
[48d20d]364 return false;
365}
366
[f5724f]367bool PotentialFitPotentialAction::shouldUndo() {
[48d20d]368 return false;
369}
370/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.