source: src/LevMartester.cpp@ 19fa3b

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

FIX: Removing average energy from order1-fit to Saturation potential.

  • Property mode set to 100644
File size: 18.7 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Please see the COPYING file or "Copyright notice" in builder.cpp for details.
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 * LevMartester.cpp
26 *
27 * Created on: Sep 27, 2012
28 * Author: heber
29 */
30
31
32// include config.h
33#ifdef HAVE_CONFIG_H
34#include <config.h>
35#endif
36
37#include <boost/archive/text_iarchive.hpp>
38
39#include "CodePatterns/MemDebug.hpp"
40
41#include <boost/filesystem.hpp>
42#include <boost/program_options.hpp>
43
44#include <cstdlib>
45#include <ctime>
46#include <fstream>
47#include <iostream>
48#include <iterator>
49#include <list>
50#include <vector>
51
52#include <levmar.h>
53
54#include "CodePatterns/Assert.hpp"
55#include "CodePatterns/Log.hpp"
56
57#include "LinearAlgebra/Vector.hpp"
58
59#include "Fragmentation/Homology/HomologyContainer.hpp"
60#include "Fragmentation/SetValues/Fragment.hpp"
61#include "FunctionApproximation/FunctionApproximation.hpp"
62#include "FunctionApproximation/FunctionModel.hpp"
63#include "Helpers/defs.hpp"
64#include "Potentials/Specifics/PairPotential_Morse.hpp"
65#include "Potentials/Specifics/SaturationPotential.hpp"
66
67namespace po = boost::program_options;
68
69HomologyGraph getFirstGraphWithTwoCarbons(const HomologyContainer &homologies)
70{
71 FragmentNode SaturatedCarbon(6,4); // carbon has atomic number 6 and should have 4 bonds for C2H6
72 for (HomologyContainer::container_t::const_iterator iter =
73 homologies.begin(); iter != homologies.end(); ++iter) {
74 if (iter->first.hasNode(SaturatedCarbon,2))
75 return iter->first;
76 }
77 return HomologyGraph();
78}
79
80HomologyGraph getFirstGraphWithOneCarbon(const HomologyContainer &homologies)
81{
82 FragmentNode SaturatedCarbon(6,3); // carbon has atomic number 6 and has 3 bonds (to other Hs)
83 for (HomologyContainer::container_t::const_iterator iter =
84 homologies.begin(); iter != homologies.end(); ++iter) {
85 if (iter->first.hasNode(SaturatedCarbon,1))
86 return iter->first;
87 }
88 return HomologyGraph();
89}
90
91FunctionModel::arguments_t
92gatherAllDistanceArguments(
93 const Fragment::charges_t &charges,
94 const Fragment::positions_t &positions,
95 const size_t globalid)
96{
97 FunctionModel::arguments_t result;
98
99 // go through current configuration and gather all other distances
100 Fragment::charges_t::const_iterator firstchargeiter = charges.begin();
101 Fragment::positions_t::const_iterator firstpositer = positions.begin();
102 for (;firstchargeiter != charges.end();
103 ++firstchargeiter, ++firstpositer) {
104 Fragment::charges_t::const_iterator secondchargeiter = charges.begin();//firstchargeiter;
105 Fragment::positions_t::const_iterator secondpositer = positions.begin();//firstpositer;
106 for (;
107 secondchargeiter != charges.end();
108 ++secondchargeiter, ++secondpositer) {
109 if (firstchargeiter == secondchargeiter)
110 continue;
111 argument_t arg;
112 const Vector firsttemp((*firstpositer)[0],(*firstpositer)[1],(*firstpositer)[2]);
113 const Vector secondtemp((*secondpositer)[0],(*secondpositer)[1],(*secondpositer)[2]);
114 arg.distance = firsttemp.distance(secondtemp);
115 arg.indices = std::make_pair(
116 std::distance(
117 charges.begin(), firstchargeiter),
118 std::distance(
119 charges.begin(), secondchargeiter)
120 );
121 arg.globalid = globalid;
122 result.push_back(arg);
123 }
124 ASSERT( secondpositer == positions.end(),
125 "gatherAllDistanceArguments() - there are not as many positions as charges.");
126 }
127 ASSERT( firstpositer == positions.end(),
128 "gatherAllDistanceArguments() - there are not as many positions as charges.");
129
130 return result;
131}
132
133/** This function returns the elements of the sum over index "k" for an
134 * argument containing indices "i" and "j"
135 * @param inputs vector of all configuration (containing each a vector of all arguments)
136 * @param arg argument containing indices "i" and "j"
137 * @param cutoff cutoff criterion for sum over k
138 * @return vector of argument pairs (a vector) of ik and jk for at least all k
139 * within distance of \a cutoff to i
140 */
141std::vector<FunctionModel::arguments_t>
142getTripleFromArgument(const FunctionApproximation::inputs_t &inputs, const argument_t &arg, const double cutoff)
143{
144 typedef std::list<argument_t> arg_list_t;
145 typedef std::map<size_t, arg_list_t > k_args_map_t;
146 k_args_map_t tempresult;
147 ASSERT( inputs.size() > arg.globalid,
148 "getTripleFromArgument() - globalid "+toString(arg.globalid)
149 +" is greater than all inputs "+toString(inputs.size())+".");
150 const FunctionModel::arguments_t &listofargs = inputs[arg.globalid];
151 for (FunctionModel::arguments_t::const_iterator argiter = listofargs.begin();
152 argiter != listofargs.end();
153 ++argiter) {
154 // first index must be either i or j but second index not
155 if (((argiter->indices.first == arg.indices.first)
156 || (argiter->indices.first == arg.indices.second))
157 && ((argiter->indices.second != arg.indices.first)
158 && (argiter->indices.second != arg.indices.second))) {
159 // we need arguments ik and jk
160 std::pair< k_args_map_t::iterator, bool> inserter =
161 tempresult.insert( std::make_pair( argiter->indices.second, arg_list_t(1,*argiter)));
162 if (!inserter.second) {
163 // is present one ik or jk, if ik insert jk at back
164 if (inserter.first->second.begin()->indices.first == arg.indices.first)
165 inserter.first->second.push_back(*argiter);
166 else // if jk, insert ik at front
167 inserter.first->second.push_front(*argiter);
168 }
169 }
170// // or second index must be either i or j but first index not
171// else if (((argiter->indices.first != arg.indices.first)
172// && (argiter->indices.first != arg.indices.second))
173// && ((argiter->indices.second == arg.indices.first)
174// || (argiter->indices.second == arg.indices.second))) {
175// // we need arguments ki and kj
176// std::pair< k_args_map_t::iterator, bool> inserter =
177// tempresult.insert( std::make_pair( argiter->indices.first, arg_list_t(1,*argiter)));
178// if (!inserter.second) {
179// // is present one ki or kj, if ki insert kj at back
180// if (inserter.first->second.begin()->indices.second == arg.indices.first)
181// inserter.first->second.push_back(*argiter);
182// else // if kj, insert ki at front
183// inserter.first->second.push_front(*argiter);
184// }
185// }
186 }
187 // check that i,j are NOT contained
188 ASSERT( tempresult.count(arg.indices.first) == 0,
189 "getTripleFromArgument() - first index of argument present in k_args_map?");
190 ASSERT( tempresult.count(arg.indices.second) == 0,
191 "getTripleFromArgument() - first index of argument present in k_args_map?");
192
193 // convert
194 std::vector<FunctionModel::arguments_t> result;
195 for (k_args_map_t::const_iterator iter = tempresult.begin();
196 iter != tempresult.end();
197 ++iter) {
198 ASSERT( iter->second.size() == 2,
199 "getTripleFromArgument() - for index "+toString(iter->first)+" we did not find both ik and jk.");
200 result.push_back( FunctionModel::arguments_t(iter->second.begin(), iter->second.end()) );
201 }
202 return result;
203}
204
205
206int main(int argc, char **argv)
207{
208 std::cout << "Hello to the World from LevMar!" << std::endl;
209
210 // load homology file
211 po::options_description desc("Allowed options");
212 desc.add_options()
213 ("help", "produce help message")
214 ("homology-file", po::value< boost::filesystem::path >(), "homology file to parse")
215 ;
216
217 po::variables_map vm;
218 po::store(po::parse_command_line(argc, argv, desc), vm);
219 po::notify(vm);
220
221 if (vm.count("help")) {
222 std::cout << desc << "\n";
223 return 1;
224 }
225
226 boost::filesystem::path homology_file;
227 if (vm.count("homology-file")) {
228 homology_file = vm["homology-file"].as<boost::filesystem::path>();
229 LOG(1, "INFO: Parsing " << homology_file.string() << ".");
230 } else {
231 LOG(0, "homology-file level was not set.");
232 }
233 HomologyContainer homologies;
234 if (boost::filesystem::exists(homology_file)) {
235 std::ifstream returnstream(homology_file.string().c_str());
236 if (returnstream.good()) {
237 boost::archive::text_iarchive ia(returnstream);
238 ia >> homologies;
239 } else {
240 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
241 }
242 returnstream.close();
243 } else {
244 ELOG(0, homology_file << " does not exist.");
245 }
246
247 // first we try to look into the HomologyContainer
248 LOG(1, "INFO: Listing all present homologies ...");
249 for (HomologyContainer::container_t::const_iterator iter =
250 homologies.begin(); iter != homologies.end(); ++iter) {
251 LOG(1, "INFO: graph " << iter->first << " has Fragment "
252 << iter->second.first << " and associated energy " << iter->second.second << ".");
253 }
254
255 /******************** MORSE TRAINING ********************/
256 {
257 // then we ought to pick the right HomologyGraph ...
258 const HomologyGraph graph = getFirstGraphWithTwoCarbons(homologies);
259 LOG(1, "First representative graph containing two saturated carbons is " << graph << ".");
260
261 // Afterwards we go through all of this type and gather the distance and the energy value
262 typedef std::pair<
263 FunctionApproximation::inputs_t,
264 FunctionApproximation::outputs_t> InputOutputVector_t;
265 InputOutputVector_t DistanceEnergyVector;
266 std::pair<HomologyContainer::const_iterator, HomologyContainer::const_iterator> range =
267 homologies.getHomologousGraphs(graph);
268 for (HomologyContainer::const_iterator iter = range.first; iter != range.second; ++iter) {
269 // get distance out of Fragment
270 const double &energy = iter->second.second;
271 const Fragment &fragment = iter->second.first;
272 const Fragment::charges_t charges = fragment.getCharges();
273 const Fragment::positions_t positions = fragment.getPositions();
274 std::vector< std::pair<Vector, size_t> > DistanceVectors;
275 for (Fragment::charges_t::const_iterator chargeiter = charges.begin();
276 chargeiter != charges.end(); ++chargeiter) {
277 if (*chargeiter == 6) {
278 Fragment::positions_t::const_iterator positer = positions.begin();
279 const size_t steps = std::distance(charges.begin(), chargeiter);
280 std::advance(positer, steps);
281 DistanceVectors.push_back(
282 std::make_pair(Vector((*positer)[0], (*positer)[1], (*positer)[2]),
283 steps));
284 }
285 }
286 if (DistanceVectors.size() == (size_t)2) {
287 argument_t arg;
288 arg.indices.first = DistanceVectors[0].second;
289 arg.indices.second = DistanceVectors[1].second;
290 arg.distance = DistanceVectors[0].first.distance(DistanceVectors[1].first);
291 arg.globalid = DistanceEnergyVector.first.size();
292 DistanceEnergyVector.first.push_back( FunctionModel::arguments_t(1,arg) );
293 DistanceEnergyVector.second.push_back( FunctionModel::results_t(1,energy) );
294 } else {
295 ELOG(2, "main() - found not exactly two carbon atoms in fragment "
296 << fragment << ".");
297 }
298 }
299 // print training data for debugging
300 {
301 LOG(1, "INFO: I gathered the following (" << DistanceEnergyVector.first.size()
302 << "," << DistanceEnergyVector.second.size() << ") data pairs: ");
303 FunctionApproximation::inputs_t::const_iterator initer = DistanceEnergyVector.first.begin();
304 FunctionApproximation::outputs_t::const_iterator outiter = DistanceEnergyVector.second.begin();
305 for (; initer != DistanceEnergyVector.first.end(); ++initer, ++outiter) {
306 LOG(1, "INFO: (" << (*initer)[0].indices.first << "," << (*initer)[0].indices.second
307 << ") " << (*initer)[0].distance << " with energy " << *outiter);
308 }
309 }
310 // NOTICE that distance are in bohrradi as they come from MPQC!
311
312 // now perform the function approximation by optimizing the model function
313 FunctionModel::parameters_t params(PairPotential_Morse::MAXPARAMS, 0.);
314 params[PairPotential_Morse::dissociation_energy] = 0.5;
315 params[PairPotential_Morse::energy_offset] = -1.;
316 params[PairPotential_Morse::spring_constant] = 1.;
317 params[PairPotential_Morse::equilibrium_distance] = 2.9;
318 PairPotential_Morse morse;
319 morse.setParameters(params);
320 FunctionModel &model = morse;
321 FunctionApproximation approximator(1, 1, model);
322 approximator.setTrainingData(DistanceEnergyVector.first,DistanceEnergyVector.second);
323 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
324 approximator(FunctionApproximation::ParameterDerivative);
325 else
326 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
327 params = model.getParameters();
328
329 LOG(0, "RESULT: Best parameters are " << params << ".");
330 }
331
332 /******************* SATURATION TRAINING *******************/
333 FunctionModel::parameters_t params(SaturationPotential::MAXPARAMS, 0.);
334 {
335 // then we ought to pick the right HomologyGraph ...
336 const HomologyGraph graph = getFirstGraphWithOneCarbon(homologies);
337 LOG(1, "First representative graph containing one saturated carbon is " << graph << ".");
338
339 // Afterwards we go through all of this type and gather the distance and the energy value
340 typedef std::pair<
341 FunctionApproximation::inputs_t,
342 FunctionApproximation::outputs_t> InputOutputVector_t;
343 InputOutputVector_t DistanceEnergyVector;
344 std::pair<HomologyContainer::const_iterator, HomologyContainer::const_iterator> range =
345 homologies.getHomologousGraphs(graph);
346 double EnergySum = 0.; //std::numeric_limits<double>::max();
347 size_t counter = 0.;
348 for (HomologyContainer::const_iterator iter = range.first; iter != range.second; ++iter) {
349 const double &energy = iter->second.second;
350// if (energy <= EnergySum)
351// EnergySum = energy;
352 EnergySum += energy;
353 ++counter;
354 }
355 EnergySum *= 1./(double)counter;
356 for (HomologyContainer::const_iterator iter = range.first; iter != range.second; ++iter) {
357 // get distance out of Fragment
358 const double &energy = iter->second.second;
359 const Fragment &fragment = iter->second.first;
360 const Fragment::charges_t charges = fragment.getCharges();
361 const Fragment::positions_t positions = fragment.getPositions();
362 FunctionModel::arguments_t args =
363 gatherAllDistanceArguments(charges, positions, DistanceEnergyVector.first.size());
364 DistanceEnergyVector.first.push_back( args );
365 DistanceEnergyVector.second.push_back( FunctionModel::results_t(1,energy-EnergySum) );
366 }
367 // print training data for debugging
368 {
369 LOG(1, "INFO: I gathered the following (" << DistanceEnergyVector.first.size()
370 << "," << DistanceEnergyVector.second.size() << ") data pairs: ");
371 FunctionApproximation::inputs_t::const_iterator initer = DistanceEnergyVector.first.begin();
372 FunctionApproximation::outputs_t::const_iterator outiter = DistanceEnergyVector.second.begin();
373 for (; initer != DistanceEnergyVector.first.end(); ++initer, ++outiter) {
374 std::stringstream stream;
375 for (size_t index = 0; index < (*initer).size(); ++index)
376 stream << "(" << (*initer)[index].indices.first << "," << (*initer)[index].indices.second
377 << ") " << (*initer)[index].distance;
378 stream << " with energy " << *outiter;
379 LOG(1, "INFO: " << stream.str());
380 }
381 }
382 // NOTICE that distance are in bohrradi as they come from MPQC!
383
384 // now perform the function approximation by optimizing the model function
385 boost::function< std::vector<FunctionModel::arguments_t>(const argument_t &, const double)> triplefunction =
386 boost::bind(&getTripleFromArgument, DistanceEnergyVector.first, _1, _2);
387 srand((unsigned)time(0)); // seed with current time
388 LOG(0, "INFO: Initial parameters are " << params << ".");
389
390 SaturationPotential saturation(triplefunction);
391 saturation.setParameters(params);
392 FunctionModel &model = saturation;
393 FunctionApproximation approximator(
394 DistanceEnergyVector.first.begin()->size(),
395 DistanceEnergyVector.second.begin()->size(),
396 model); // CH4 has 5 atoms, hence 5*4/2 distances
397 approximator.setTrainingData(DistanceEnergyVector.first,DistanceEnergyVector.second);
398 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
399 approximator(FunctionApproximation::ParameterDerivative);
400 else
401 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
402
403 params = model.getParameters();
404
405 LOG(0, "RESULT: Best parameters are " << params << ".");
406
407// std::cout << "\tsaturationparticle:";
408// std::cout << "\tparticle_type=C,";
409// std::cout << "\tA=" << params[SaturationPotential::A] << ",";
410// std::cout << "\tB=" << params[SaturationPotential::B] << ",";
411// std::cout << "\tlambda=" << params[SaturationPotential::lambda] << ",";
412// std::cout << "\tmu=" << params[SaturationPotential::mu] << ",";
413// std::cout << "\tbeta=" << params[SaturationPotential::beta] << ",";
414// std::cout << "\tn=" << params[SaturationPotential::n] << ",";
415// std::cout << "\tc=" << params[SaturationPotential::c] << ",";
416// std::cout << "\td=" << params[SaturationPotential::d] << ",";
417// std::cout << "\th=" << params[SaturationPotential::h] << ",";
418//// std::cout << "\toffset=" << params[SaturationPotential::offset] << ",";
419// std::cout << "\tR=" << saturation.R << ",";
420// std::cout << "\tS=" << saturation.S << ";";
421// std::cout << std::endl;
422
423 // check L2 and Lmax error against training set
424 double L2sum = 0.;
425 double Lmax = 0.;
426 size_t maxindex = -1;
427 FunctionApproximation::inputs_t::const_iterator initer = DistanceEnergyVector.first.begin();
428 FunctionApproximation::outputs_t::const_iterator outiter = DistanceEnergyVector.second.begin();
429 for (; initer != DistanceEnergyVector.first.end(); ++initer, ++outiter) {
430 const FunctionModel::results_t result = model((*initer));
431 const double temp = fabs((*outiter)[0] - result[0]);
432 if (temp > Lmax) {
433 Lmax = temp;
434 maxindex = std::distance(const_cast<const FunctionApproximation::inputs_t &>(DistanceEnergyVector.first).begin(), initer);
435 }
436 L2sum += temp*temp;
437 }
438 LOG(1, "INFO: L2sum = " << L2sum << ", LMax = " << Lmax << " from " << maxindex);
439 }
440
441 return 0;
442}
Note: See TracBrowser for help on using the repository browser.