source: src/LevMartester.cpp@ f48ad3

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

LevMartester now uses FunctionModel::setParameter() to set initial parameters.

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