source: src/Potentials/PotentialTrainer.cpp@ 3400bb

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator 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_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 3400bb was 3400bb, checked in by Frederik Heber <heber@…>, 8 years ago

MEMFIX: PotentialTrainer::operator() had potential memory leak.

  • Property mode set to 100644
File size: 9.3 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2014 Frederik Heber. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * PotentialTrainer.cpp
25 *
26 * Created on: Sep 11, 2014
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// needs to come before MemDebug due to placement new
36#include <boost/archive/text_iarchive.hpp>
37
38#include "CodePatterns/MemDebug.hpp"
39
40#include "PotentialTrainer.hpp"
41
42#include <algorithm>
43#include <boost/lambda/lambda.hpp>
44#include <boost/filesystem.hpp>
45#include <fstream>
46#include <sstream>
47
48#include "CodePatterns/Assert.hpp"
49#include "CodePatterns/Log.hpp"
50
51#include "Element/element.hpp"
52#include "Fragmentation/Homology/HomologyContainer.hpp"
53#include "Fragmentation/Homology/HomologyGraph.hpp"
54#include "FunctionApproximation/Extractors.hpp"
55#include "FunctionApproximation/FunctionApproximation.hpp"
56#include "FunctionApproximation/FunctionModel.hpp"
57#include "FunctionApproximation/TrainingData.hpp"
58#include "FunctionApproximation/writeDistanceEnergyTable.hpp"
59#include "Potentials/CompoundPotential.hpp"
60#include "Potentials/RegistrySerializer.hpp"
61#include "Potentials/SerializablePotential.hpp"
62
63PotentialTrainer::PotentialTrainer()
64{}
65
66PotentialTrainer::~PotentialTrainer()
67{}
68
69bool PotentialTrainer::operator()(
70 const HomologyContainer &_homologies,
71 const HomologyGraph &_graph,
72 const boost::filesystem::path &_trainingfile,
73 const unsigned int _maxiterations,
74 const double _threshold,
75 const unsigned int _best_of_howmany) const
76{
77 // fit potential
78 CompoundPotential compound(_graph);
79 FunctionModel &model = assert_cast<FunctionModel &>(compound);
80
81 if (compound.begin() == compound.end()) {
82 ELOG(1, "Could not find any suitable potentials for the compound potential.");
83 return false;
84 }
85
86 /******************** TRAINING ********************/
87 // fit potential
88 FunctionModel::parameters_t bestparams(model.getParameterDimension(), 0.);
89 {
90 // Afterwards we go through all of this type and gather the distance and the energy value
91 TrainingData data(model.getSpecificFilter());
92 data(_homologies.getHomologousGraphs(_graph));
93
94 // check data
95 const TrainingData::FilteredInputVector_t &inputs = data.getTrainingInputs();
96 for (TrainingData::FilteredInputVector_t::const_iterator iter = inputs.begin();
97 iter != inputs.end(); ++iter)
98 if (((*iter).empty()) || ((*iter).front().empty())) {
99 ELOG(1, "At least one of the training inputs is empty! Correct fragment and potential charges selected?");
100 return false;
101 }
102 const TrainingData::OutputVector_t &outputs = data.getTrainingOutputs();
103 for (TrainingData::OutputVector_t::const_iterator iter = outputs.begin();
104 iter != outputs.end(); ++iter)
105 if ((*iter).empty()) {
106 ELOG(1, "At least one of the training outputs is empty! Correct fragment and potential charges selected?");
107 return false;
108 }
109
110 // print distances and energies if desired for debugging
111 if (!data.getTrainingInputs().empty()) {
112 // print which distance is which
113 size_t counter=1;
114 if (DoLog(3)) {
115 const FunctionModel::arguments_t &inputs = data.getAllArguments()[0];
116 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
117 iter != inputs.end(); ++iter) {
118 const argument_t &arg = *iter;
119 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
120 << arg.indices.first << "c" << arg.types.first << ","
121 << arg.indices.second << "c" << arg.types.second << ").");
122 }
123 }
124
125 // print table
126 if (_trainingfile.string().empty()) {
127 LOG(3, "DEBUG: I gathered the following training data:\n" <<
128 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
129 } else {
130 std::ofstream trainingstream(_trainingfile.string().c_str());
131 if (trainingstream.good()) {
132 LOG(3, "DEBUG: Writing training data to file " <<
133 _trainingfile.string() << ".");
134 trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable());
135 }
136 trainingstream.close();
137 }
138 }
139
140 if ((_threshold < 1.) && (_best_of_howmany))
141 ELOG(2, "threshold parameter always overrules max_runs, both are specified.");
142 // now perform the function approximation by optimizing the model function
143 FunctionApproximation approximator(data, model, _threshold, _maxiterations);
144 if (model.isBoxConstraint() && approximator.checkParameterDerivatives()) {
145 double l2error = std::numeric_limits<double>::max();
146 // seed with current time
147 srand((unsigned)time(0));
148 unsigned int runs=0;
149 // threshold overrules max_runs
150 const double threshold = _threshold;
151 const unsigned int max_runs = (threshold >= 1.) ? _best_of_howmany : 1;
152 LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << ".");
153 do {
154 // generate new random initial parameter values
155 model.setParametersToRandomInitialValues(data);
156 LOG(1, "INFO: Initial parameters of run " << runs << " are "
157 << model.getParameters() << ".");
158 approximator(FunctionApproximation::ParameterDerivative);
159 LOG(1, "INFO: Final parameters of run " << runs << " are "
160 << model.getParameters() << ".");
161 const double new_l2error = data.getL2Error(model);
162 if (new_l2error < l2error) {
163 // store currently best parameters
164 l2error = new_l2error;
165 bestparams = model.getParameters();
166 LOG(1, "STATUS: New fit from run " << runs
167 << " has better error of " << l2error << ".");
168 }
169 } while (( ++runs < max_runs) || (l2error > threshold));
170 // reset parameters from best fit
171 model.setParameters(bestparams);
172 LOG(1, "INFO: Best parameters with L2 error of "
173 << l2error << " are " << model.getParameters() << ".");
174 } else {
175 return false;
176 }
177
178 // create a map of each fragment with error.
179 HomologyContainer::range_t fragmentrange = _homologies.getHomologousGraphs(_graph);
180 TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap =
181 data.getWorstFragmentMap(model, fragmentrange);
182 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
183
184 }
185
186 return true;
187}
188
189HomologyGraph PotentialTrainer::getFirstGraphwithSpecifiedElements(
190 const HomologyContainer &homologies,
191 const SerializablePotential::ParticleTypes_t &types)
192{
193 ASSERT( !types.empty(),
194 "getFirstGraphwithSpecifiedElements() - charges is empty?");
195 // create charges
196 Fragment::charges_t charges;
197 charges.resize(types.size());
198 std::transform(types.begin(), types.end(),
199 charges.begin(), boost::lambda::_1);
200 // convert into count map
201 Extractors::elementcounts_t counts_per_charge =
202 Extractors::_detail::getElementCounts(charges);
203 ASSERT( !counts_per_charge.empty(),
204 "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
205 LOG(1, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
206 // we want to check each (unique) key only once
207 HomologyContainer::const_key_iterator olditer = homologies.key_end();
208 for (HomologyContainer::const_key_iterator iter =
209 homologies.key_begin(); iter != homologies.key_end();
210 iter = homologies.getNextKey(iter)) {
211 // if it's the same as the old one, skip it
212 if (olditer == iter)
213 continue;
214 else
215 olditer = iter;
216 // check whether we have the same set of atomic numbers
217 const HomologyGraph::nodes_t &nodes = (*iter).getNodes();
218 Extractors::elementcounts_t nodes_counts_per_charge;
219 for (HomologyGraph::nodes_t::const_iterator nodeiter = nodes.begin();
220 nodeiter != nodes.end(); ++nodeiter) {
221 const Extractors::element_t elem = nodeiter->first.getAtomicNumber();
222 const std::pair<Extractors::elementcounts_t::iterator, bool> inserter =
223 nodes_counts_per_charge.insert( std::make_pair(elem, (Extractors::count_t)nodeiter->second ) );
224 if (!inserter.second)
225 inserter.first->second += (Extractors::count_t)nodeiter->second;
226 }
227 LOG(1, "DEBUG: Node (" << *iter << ")'s counts_per_charge is " << nodes_counts_per_charge << ".");
228 if (counts_per_charge == nodes_counts_per_charge)
229 return *iter;
230 }
231 return HomologyGraph();
232}
233
234SerializablePotential::ParticleTypes_t PotentialTrainer::getNumbersFromElements(
235 const std::vector<const element *> &fragment)
236{
237 SerializablePotential::ParticleTypes_t fragmentnumbers;
238 std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
239 boost::bind(&element::getAtomicNumber, _1));
240 return fragmentnumbers;
241}
Note: See TracBrowser for help on using the repository browser.