source: src/Actions/FragmentationAction/FitPotentialAction.cpp@ 62164d

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

Writing final parameters to potential-file.

  • Property mode set to 100644
File size: 14.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 * 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/FragmentationAction/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 FragmentationFitPotentialAction::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 " << params.homology_file.get() << ".");
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 "
171 << params.homology_file.get() << ".");
172
173 // register desired potential and an additional constant one
174 EmpiricalPotential *potential =
175 PotentialFactory::getInstance().createInstance(
176 params.potentialtype.get(),
177 chargenumbers);
178 PotentialRegistry::getInstance().registerInstance(potential);
179 EmpiricalPotential *constant =
180 PotentialFactory::getInstance().createInstance(
181 std::string("constant"),
182 SerializablePotential::ParticleTypes_t());
183 PotentialRegistry::getInstance().registerInstance(constant);
184 }
185 }
186
187 // parse homologies into container
188 HomologyContainer homologies;
189 if (boost::filesystem::exists(params.homology_file.get())) {
190 std::ifstream returnstream(params.homology_file.get().string().c_str());
191 if (returnstream.good()) {
192 boost::archive::text_iarchive ia(returnstream);
193 ia >> homologies;
194 } else {
195 ELOG(0, "Failed to parse from " << params.homology_file.get().string() << ".");
196 return Action::failure;
197 }
198 returnstream.close();
199 } else {
200 ELOG(0, params.homology_file.get() << " does not exist.");
201 return Action::failure;
202 }
203
204 // first we try to look into the HomologyContainer
205 LOG(1, "INFO: Listing all present homologies ...");
206 for (HomologyContainer::container_t::const_iterator iter =
207 homologies.begin(); iter != homologies.end(); ++iter) {
208 LOG(1, "INFO: graph " << iter->first << " has Fragment " << iter->second.first
209 << " and associated energy " << iter->second.second << ".");
210 }
211
212 // then we ought to pick the right HomologyGraph ...
213 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
214 if (graph != HomologyGraph()) {
215 LOG(1, "First representative graph containing fragment "
216 << fragmentnumbers << " is " << graph << ".");
217 } else {
218 ELOG(1, "Specific fragment " << fragmentnumbers << " not found in homologies!");
219 return Action::failure;
220 }
221
222 // fit potential
223 FunctionModel *model = new CompoundPotential(graph);
224 ASSERT( model != NULL,
225 "FragmentationFitPotentialAction::performCall() - model is NULL.");
226
227 /******************** TRAINING ********************/
228 // fit potential
229 FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
230 {
231 // Afterwards we go through all of this type and gather the distance and the energy value
232 TrainingData data(model->getFragmentSpecificExtractor());
233 data(homologies.getHomologousGraphs(graph));
234
235 // print distances and energies if desired for debugging
236 if (!data.getTrainingInputs().empty()) {
237 // print which distance is which
238 size_t counter=1;
239 if (DoLog(3)) {
240 const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
241 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
242 iter != inputs.end(); ++iter) {
243 const argument_t &arg = *iter;
244 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
245 << arg.indices.first << "c" << arg.types.first << ","
246 << arg.indices.second << "c" << arg.types.second << ").");
247 }
248 }
249
250 // print table
251 if (params.training_file.get().string().empty()) {
252 LOG(3, "DEBUG: I gathered the following training data:\n" <<
253 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
254 } else {
255 std::ofstream trainingstream(params.training_file.get().string().c_str());
256 if (trainingstream.good()) {
257 LOG(3, "DEBUG: Writing training data to file " <<
258 params.training_file.get().string() << ".");
259 trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable());
260 }
261 trainingstream.close();
262 }
263 }
264
265 // now perform the function approximation by optimizing the model function
266 FunctionApproximation approximator(data, *model);
267 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
268 double l2error = std::numeric_limits<double>::infinity();
269 // seed with current time
270 srand((unsigned)time(0));
271 for (unsigned int runs=0; runs < params.best_of_howmany.get(); ++runs) {
272 // generate new random initial parameter values
273 model->setParametersToRandomInitialValues(data);
274 LOG(1, "INFO: Initial parameters of run " << runs << " are "
275 << model->getParameters() << ".");
276 approximator(FunctionApproximation::ParameterDerivative);
277 LOG(1, "INFO: Final parameters of run " << runs << " are "
278 << model->getParameters() << ".");
279 const double new_l2error = data.getL2Error(*model);
280 if (new_l2error < l2error) {
281 // store currently best parameters
282 l2error = new_l2error;
283 bestparams = model->getParameters();
284 LOG(1, "STATUS: New fit from run " << runs
285 << " has better error of " << l2error << ".");
286 }
287 }
288 // reset parameters from best fit
289 model->setParameters(bestparams);
290 LOG(1, "INFO: Best parameters with L2 error of "
291 << l2error << " are " << model->getParameters() << ".");
292 } else {
293 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
294 return Action::failure;
295 }
296
297 // create a map of each fragment with error.
298 typedef std::multimap< double, size_t > WorseFragmentMap_t;
299 WorseFragmentMap_t WorseFragmentMap;
300 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
301 // fragments make it into the container in reversed order, hence count from top down
302 size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
303 for (HomologyContainer::const_iterator iter = fragmentrange.first;
304 iter != fragmentrange.second;
305 ++iter) {
306 const Fragment& fragment = iter->second.first;
307 const double &energy = iter->second.second;
308
309 // create arguments from the fragment
310 FunctionModel::extractor_t extractor = model->getFragmentSpecificExtractor();
311 FunctionModel::arguments_t args = extractor(fragment, 1);
312
313 // calculate value from potential
314 const double fitvalue = (*model)(args)[0];
315
316 // insert difference into map
317 const double error = fabs(energy - fitvalue);
318 WorseFragmentMap.insert( std::make_pair( error, index-- ) );
319
320 {
321 // give only the distances in the debugging text
322 std::stringstream streamargs;
323 BOOST_FOREACH (argument_t arg, args) {
324 streamargs << " " << arg.distance*AtomicLengthToAngstroem;
325 }
326 LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
327 << "| = " << error << " for args " << streamargs.str() << ".");
328 }
329 }
330 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
331
332 // print fitted potentials
333 std::stringstream potentials;
334 PotentialSerializer serialize(potentials);
335 serialize();
336 LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str());
337 std::ofstream returnstream(params.potential_file.get().string().c_str());
338 if (returnstream.good()) {
339 returnstream << potentials.str();
340 }
341 }
342 delete model;
343
344 return Action::success;
345}
346
347Action::state_ptr FragmentationFitPotentialAction::performUndo(Action::state_ptr _state) {
348 return Action::success;
349}
350
351Action::state_ptr FragmentationFitPotentialAction::performRedo(Action::state_ptr _state){
352 return Action::success;
353}
354
355bool FragmentationFitPotentialAction::canUndo() {
356 return false;
357}
358
359bool FragmentationFitPotentialAction::shouldUndo() {
360 return false;
361}
362/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.