source: src/Actions/FragmentationAction/FitPotentialAction.cpp@ 5aaa43

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

FIX: Fixed new copyright line since start of 2013 in CodeChecks test.

  • we must look for either Uni Bonn or myself.
  • added second copyright line since from 1st of Jan 2013 I am not employed by University of Bonn anymore, hence changes to the code are my own copyright.
  • Property mode set to 100644
File size: 11.1 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/PotentialFactory.hpp"
63#include "Potentials/SerializablePotential.hpp"
64
65using namespace MoleCuilder;
66
67// and construct the stuff
68#include "FitPotentialAction.def"
69#include "Action_impl_pre.hpp"
70/** =========== define the function ====================== */
71
72HomologyGraph getFirstGraphwithSpecifiedElements(
73 const HomologyContainer &homologies,
74 const SerializablePotential::ParticleTypes_t &types)
75{
76 ASSERT( !types.empty(),
77 "getFirstGraphwithSpecifiedElements() - charges is empty?");
78 // create charges
79 Fragment::charges_t charges;
80 charges.resize(types.size());
81 std::transform(types.begin(), types.end(),
82 charges.begin(), boost::lambda::_1);
83 // convert into count map
84 Extractors::elementcounts_t counts_per_charge =
85 Extractors::_detail::getElementCounts(charges);
86 ASSERT( !counts_per_charge.empty(),
87 "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
88 LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
89 // we want to check each (unique) key only once
90 HomologyContainer::const_key_iterator olditer = homologies.key_end();
91 for (HomologyContainer::const_key_iterator iter =
92 homologies.key_begin(); iter != homologies.key_end(); olditer = iter++) {
93 // if it's the same as the old one, skip it
94 if (*olditer == *iter)
95 continue;
96 // if it's a new key, check if every element has the right number of counts
97 Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
98 for (; countiter != counts_per_charge.end(); ++countiter)
99 if (!(*iter).hasTimesAtomicNumber(countiter->first,countiter->second))
100 break;
101 if( countiter == counts_per_charge.end())
102 return *iter;
103 }
104 return HomologyGraph();
105}
106
107Action::state_ptr FragmentationFitPotentialAction::performCall() {
108 // charges specify the potential type
109 SerializablePotential::ParticleTypes_t chargenumbers;
110 {
111 const std::vector<const element *> &charges = params.charges.get();
112 std::transform(charges.begin(), charges.end(), std::back_inserter(chargenumbers),
113 boost::bind(&element::getAtomicNumber, _1));
114 }
115 // fragment specifies the homology fragment to use
116 SerializablePotential::ParticleTypes_t fragmentnumbers;
117 {
118 const std::vector<const element *> &fragment = params.fragment.get();
119 std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
120 boost::bind(&element::getAtomicNumber, _1));
121 }
122
123 // parse homologies into container
124 HomologyContainer homologies;
125 if (boost::filesystem::exists(params.homology_file.get())) {
126 std::ifstream returnstream(params.homology_file.get().string().c_str());
127 if (returnstream.good()) {
128 boost::archive::text_iarchive ia(returnstream);
129 ia >> homologies;
130 } else {
131 ELOG(0, "Failed to parse from " << params.homology_file.get().string() << ".");
132 return Action::failure;
133 }
134 returnstream.close();
135 } else {
136 ELOG(0, params.homology_file.get() << " does not exist.");
137 return Action::failure;
138 }
139
140 // first we try to look into the HomologyContainer
141 LOG(1, "INFO: Listing all present homologies ...");
142 for (HomologyContainer::container_t::const_iterator iter =
143 homologies.begin(); iter != homologies.end(); ++iter) {
144 LOG(1, "INFO: graph " << iter->first << " has Fragment " << iter->second.first
145 << " and associated energy " << iter->second.second << ".");
146 }
147
148 LOG(0, "STATUS: I'm training now a " << params.potentialtype.get() << " potential on charges "
149 << chargenumbers << " on data from " << params.homology_file.get() << ".");
150
151 /******************** TRAINING ********************/
152 // fit potential
153 FunctionModel *model =
154 PotentialFactory::getInstance().createInstance(
155 params.potentialtype.get(),
156 chargenumbers);
157 ASSERT( model != NULL,
158 "main() - model returned from PotentialFactory is NULL.");
159 FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
160 {
161 // then we ought to pick the right HomologyGraph ...
162 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
163 if (graph != HomologyGraph()) {
164 LOG(1, "First representative graph containing fragment "
165 << fragmentnumbers << " is " << graph << ".");
166
167 // Afterwards we go through all of this type and gather the distance and the energy value
168 TrainingData data(model->getFragmentSpecificExtractor());
169 data(homologies.getHomologousGraphs(graph));
170
171 // print distances and energies if desired for debugging
172 if (!data.getTrainingInputs().empty()) {
173 // print which distance is which
174 size_t counter=1;
175 if (DoLog(3)) {
176 const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
177 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
178 iter != inputs.end(); ++iter) {
179 const argument_t &arg = *iter;
180 LOG(3, "DEBUG: distance " << counter++ << " is between (#"
181 << arg.indices.first << "c" << arg.types.first << ","
182 << arg.indices.second << "c" << arg.types.second << ").");
183 }
184 }
185
186 // print table
187 LOG(3, "DEBUG: I gathered the following training data:\n" <<
188 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
189 }
190
191 // now perform the function approximation by optimizing the model function
192 FunctionApproximation approximator(data, *model);
193 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
194 double l2error = std::numeric_limits<double>::infinity();
195 // seed with current time
196 srand((unsigned)time(0));
197 for (unsigned int runs=0; runs < params.best_of_howmany.get(); ++runs) {
198 // generate new random initial parameter values
199 model->setParametersToRandomInitialValues(data);
200 LOG(1, "INFO: Initial parameters of run " << runs << " are "
201 << model->getParameters() << ".");
202 approximator(FunctionApproximation::ParameterDerivative);
203 LOG(1, "INFO: Final parameters of run " << runs << " are "
204 << model->getParameters() << ".");
205 const double new_l2error = data.getL2Error(*model);
206 if (new_l2error < l2error) {
207 // store currently best parameters
208 l2error = new_l2error;
209 bestparams = model->getParameters();
210 LOG(1, "STATUS: New fit from run " << runs
211 << " has better error of " << l2error << ".");
212 }
213 }
214 // reset parameters from best fit
215 model->setParameters(bestparams);
216 LOG(1, "INFO: Best parameters with L2 error of "
217 << l2error << " are " << model->getParameters() << ".");
218 } else {
219 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
220 return Action::failure;
221 }
222
223 // create a map of each fragment with error.
224 typedef std::multimap< double, size_t > WorseFragmentMap_t;
225 WorseFragmentMap_t WorseFragmentMap;
226 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
227 // fragments make it into the container in reversed order, hence count from top down
228 size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
229 for (HomologyContainer::const_iterator iter = fragmentrange.first;
230 iter != fragmentrange.second;
231 ++iter) {
232 const Fragment& fragment = iter->second.first;
233 const double &energy = iter->second.second;
234
235 // create arguments from the fragment
236 FunctionModel::extractor_t extractor = model->getFragmentSpecificExtractor();
237 FunctionModel::arguments_t args = extractor(fragment, 1);
238
239 // calculate value from potential
240 const double fitvalue = (*model)(args)[0];
241
242 // insert difference into map
243 const double error = fabs(energy - fitvalue);
244 WorseFragmentMap.insert( std::make_pair( error, index-- ) );
245
246 {
247 // give only the distances in the debugging text
248 std::stringstream streamargs;
249 BOOST_FOREACH (argument_t arg, args) {
250 streamargs << " " << arg.distance*AtomicLengthToAngstroem;
251 }
252 LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
253 << "| = " << error << " for args " << streamargs.str() << ".");
254 }
255 }
256 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
257
258 SerializablePotential *potential = dynamic_cast<SerializablePotential *>(model);
259 if (potential != NULL) {
260 LOG(1, "STATUS: Resulting parameters are " << std::endl << *potential);
261 } else {
262 LOG(1, "INFO: FunctionModel is no serializable potential.");
263 }
264 }
265 }
266 delete model;
267
268 return Action::success;
269}
270
271Action::state_ptr FragmentationFitPotentialAction::performUndo(Action::state_ptr _state) {
272 return Action::success;
273}
274
275Action::state_ptr FragmentationFitPotentialAction::performRedo(Action::state_ptr _state){
276 return Action::success;
277}
278
279bool FragmentationFitPotentialAction::canUndo() {
280 return false;
281}
282
283bool FragmentationFitPotentialAction::shouldUndo() {
284 return false;
285}
286/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.