source: src/LevMartester.cpp@ d03292

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

Implemented box constraints for FunctionModel, using a feature of LevMar.

  • we need lower and upper bounds for each parameter. These can be passed on to specific function of LevMar.
  • LevMartester checks whether isBoxConstraints apply and requires parameter derivatives in this case.
  • Property mode set to 100644
File size: 17.4 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 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
321 approximator(FunctionApproximation::ParameterDerivative);
322 else
323 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
324 params = model.getParameters();
325
326 LOG(0, "RESULT: Best parameters are " << params << ".");
327 }
328
329 /******************* TERSOFF TRAINING *******************/
330 FunctionModel::parameters_t params(ManyBodyPotential_Tersoff::MAXPARAMS, 0.);
331 {
332 // then we ought to pick the right HomologyGraph ...
333 const HomologyGraph graph = getFirstGraphWithOneCarbon(homologies);
334 LOG(1, "First representative graph containing one saturated carbon is " << graph << ".");
335
336 // Afterwards we go through all of this type and gather the distance and the energy value
337 typedef std::pair<
338 FunctionApproximation::inputs_t,
339 FunctionApproximation::outputs_t> InputOutputVector_t;
340 InputOutputVector_t DistanceEnergyVector;
341 std::pair<HomologyContainer::const_iterator, HomologyContainer::const_iterator> range =
342 homologies.getHomologousGraphs(graph);
343 for (HomologyContainer::const_iterator iter = range.first; iter != range.second; ++iter) {
344 // get distance out of Fragment
345 const double &energy = iter->second.second;
346 const Fragment &fragment = iter->second.first;
347 const Fragment::charges_t charges = fragment.getCharges();
348 const Fragment::positions_t positions = fragment.getPositions();
349 FunctionModel::arguments_t args =
350 gatherAllDistanceArguments(charges, positions, DistanceEnergyVector.first.size());
351 DistanceEnergyVector.first.push_back( args );
352 DistanceEnergyVector.second.push_back( FunctionModel::results_t(1,energy) );
353 }
354 // print training data for debugging
355 {
356 LOG(1, "INFO: I gathered the following (" << DistanceEnergyVector.first.size()
357 << "," << DistanceEnergyVector.second.size() << ") data pairs: ");
358 FunctionApproximation::inputs_t::const_iterator initer = DistanceEnergyVector.first.begin();
359 FunctionApproximation::outputs_t::const_iterator outiter = DistanceEnergyVector.second.begin();
360 for (; initer != DistanceEnergyVector.first.end(); ++initer, ++outiter) {
361 std::stringstream stream;
362 for (size_t index = 0; index < (*initer).size(); ++index)
363 stream << "(" << (*initer)[index].indices.first << "," << (*initer)[index].indices.second
364 << ") " << (*initer)[index].distance;
365 stream << " with energy " << *outiter;
366 LOG(1, "INFO: " << stream.str());
367 }
368 }
369 // NOTICE that distance are in bohrradi as they come from MPQC!
370
371 // now perform the function approximation by optimizing the model function
372 boost::function< std::vector<FunctionModel::arguments_t>(const argument_t &, const double)> triplefunction =
373 boost::bind(&getTripleFromArgument, DistanceEnergyVector.first, _1, _2);
374// params[ManyBodyPotential_Tersoff::R] = 1./AtomicLengthToAngstroem;
375// params[ManyBodyPotential_Tersoff::S] = 2./AtomicLengthToAngstroem;
376 params[ManyBodyPotential_Tersoff::A] = 1.393600e+03;
377 params[ManyBodyPotential_Tersoff::B] = 3.467000e+02;
378 params[ManyBodyPotential_Tersoff::lambda] = 3.487900e+00;
379 params[ManyBodyPotential_Tersoff::mu] = 2.211900e+00;
380// params[ManyBodyPotential_Tersoff::lambda3] = 0.;
381// params[ManyBodyPotential_Tersoff::alpha] = 0.;
382 params[ManyBodyPotential_Tersoff::beta] = 1.572400e-07;
383// params[ManyBodyPotential_Tersoff::chi] = 1.;
384// params[ManyBodyPotential_Tersoff::omega] = 1.;
385 params[ManyBodyPotential_Tersoff::n] = 7.275100e-01;
386 params[ManyBodyPotential_Tersoff::c] = 3.804900e+04;
387 params[ManyBodyPotential_Tersoff::d] = 4.384000e+00;
388 params[ManyBodyPotential_Tersoff::h] =-5.705800e-01;
389 ManyBodyPotential_Tersoff tersoff(triplefunction);
390 tersoff.setParameters(params);
391 FunctionModel &model = tersoff;
392 FunctionApproximation approximator(
393 DistanceEnergyVector.first.begin()->size(),
394 DistanceEnergyVector.second.begin()->size(),
395 model); // CH4 has 5 atoms, hence 5*4/2 distances
396 approximator.setTrainingData(DistanceEnergyVector.first,DistanceEnergyVector.second);
397 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
398 approximator(FunctionApproximation::ParameterDerivative);
399 else
400 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
401 params = model.getParameters();
402
403 LOG(0, "RESULT: Best parameters are " << params << ".");
404 }
405
406 return 0;
407}
Note: See TracBrowser for help on using the repository browser.