source: src/LevMartester.cpp@ 52e7da

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

Angle training now also uses TrainingData.

  • Property mode set to 100644
File size: 14.9 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/assign.hpp>
42#include <boost/bind.hpp>
43#include <boost/filesystem.hpp>
44#include <boost/function.hpp>
45#include <boost/program_options.hpp>
46
47#include <cstdlib>
48#include <ctime>
49#include <fstream>
50#include <iostream>
51#include <iterator>
52#include <list>
53#include <vector>
54
55#include <levmar.h>
56
57#include "CodePatterns/Assert.hpp"
58#include "CodePatterns/Log.hpp"
59
60#include "LinearAlgebra/Vector.hpp"
61
62#include "Fragmentation/Homology/HomologyContainer.hpp"
63#include "Fragmentation/SetValues/Fragment.hpp"
64#include "FunctionApproximation/Extractors.hpp"
65#include "FunctionApproximation/FunctionApproximation.hpp"
66#include "FunctionApproximation/FunctionModel.hpp"
67#include "FunctionApproximation/TrainingData.hpp"
68#include "Helpers/defs.hpp"
69#include "Potentials/Specifics/PairPotential_Morse.hpp"
70#include "Potentials/Specifics/PairPotential_Angle.hpp"
71#include "Potentials/Specifics/SaturationPotential.hpp"
72
73namespace po = boost::program_options;
74
75using namespace boost::assign;
76
77HomologyGraph getFirstGraphWithThreeCarbons(const HomologyContainer &homologies)
78{
79 FragmentNode SaturatedCarbon(6,4); // carbon has atomic number 6 and should have 4 bonds for C3H8
80 FragmentNode DanglingCarbon(6,3); // carbon has atomic number 6 and should have 3 pure bonds for C3H8
81 for (HomologyContainer::container_t::const_iterator iter =
82 homologies.begin(); iter != homologies.end(); ++iter) {
83 if ((iter->first.hasNode(SaturatedCarbon,2)) && (iter->first.hasNode(DanglingCarbon,1)))
84 return iter->first;
85 }
86 return HomologyGraph();
87}
88
89HomologyGraph getFirstGraphWithTwoCarbons(const HomologyContainer &homologies)
90{
91 FragmentNode SaturatedCarbon(6,3); // carbon has atomic number 6 and should have 4 bonds for C2H6
92 for (HomologyContainer::container_t::const_iterator iter =
93 homologies.begin(); iter != homologies.end(); ++iter) {
94 if (iter->first.hasNode(SaturatedCarbon,2))
95 return iter->first;
96 }
97 return HomologyGraph();
98}
99
100HomologyGraph getFirstGraphWithOneCarbon(const HomologyContainer &homologies)
101{
102 FragmentNode SaturatedCarbon(6,2); // carbon has atomic number 6 and has 3 bonds (to other Hs)
103 for (HomologyContainer::container_t::const_iterator iter =
104 homologies.begin(); iter != homologies.end(); ++iter) {
105 if (iter->first.hasNode(SaturatedCarbon,1))
106 return iter->first;
107 }
108 return HomologyGraph();
109}
110
111
112/** This function returns the elements of the sum over index "k" for an
113 * argument containing indices "i" and "j"
114 * @param inputs vector of all configuration (containing each a vector of all arguments)
115 * @param arg argument containing indices "i" and "j"
116 * @param cutoff cutoff criterion for sum over k
117 * @return vector of argument pairs (a vector) of ik and jk for at least all k
118 * within distance of \a cutoff to i
119 */
120std::vector<FunctionModel::arguments_t>
121getTripleFromArgument(const FunctionApproximation::inputs_t &inputs, const argument_t &arg, const double cutoff)
122{
123 typedef std::list<argument_t> arg_list_t;
124 typedef std::map<size_t, arg_list_t > k_args_map_t;
125 k_args_map_t tempresult;
126 ASSERT( inputs.size() > arg.globalid,
127 "getTripleFromArgument() - globalid "+toString(arg.globalid)
128 +" is greater than all inputs "+toString(inputs.size())+".");
129 const FunctionModel::arguments_t &listofargs = inputs[arg.globalid];
130 for (FunctionModel::arguments_t::const_iterator argiter = listofargs.begin();
131 argiter != listofargs.end();
132 ++argiter) {
133 // first index must be either i or j but second index not
134 if (((argiter->indices.first == arg.indices.first)
135 || (argiter->indices.first == arg.indices.second))
136 && ((argiter->indices.second != arg.indices.first)
137 && (argiter->indices.second != arg.indices.second))) {
138 // we need arguments ik and jk
139 std::pair< k_args_map_t::iterator, bool> inserter =
140 tempresult.insert( std::make_pair( argiter->indices.second, arg_list_t(1,*argiter)));
141 if (!inserter.second) {
142 // is present one ik or jk, if ik insert jk at back
143 if (inserter.first->second.begin()->indices.first == arg.indices.first)
144 inserter.first->second.push_back(*argiter);
145 else // if jk, insert ik at front
146 inserter.first->second.push_front(*argiter);
147 }
148 }
149// // or second index must be either i or j but first index not
150// else if (((argiter->indices.first != arg.indices.first)
151// && (argiter->indices.first != arg.indices.second))
152// && ((argiter->indices.second == arg.indices.first)
153// || (argiter->indices.second == arg.indices.second))) {
154// // we need arguments ki and kj
155// std::pair< k_args_map_t::iterator, bool> inserter =
156// tempresult.insert( std::make_pair( argiter->indices.first, arg_list_t(1,*argiter)));
157// if (!inserter.second) {
158// // is present one ki or kj, if ki insert kj at back
159// if (inserter.first->second.begin()->indices.second == arg.indices.first)
160// inserter.first->second.push_back(*argiter);
161// else // if kj, insert ki at front
162// inserter.first->second.push_front(*argiter);
163// }
164// }
165 }
166 // check that i,j are NOT contained
167 ASSERT( tempresult.count(arg.indices.first) == 0,
168 "getTripleFromArgument() - first index of argument present in k_args_map?");
169 ASSERT( tempresult.count(arg.indices.second) == 0,
170 "getTripleFromArgument() - first index of argument present in k_args_map?");
171
172 // convert
173 std::vector<FunctionModel::arguments_t> result;
174 for (k_args_map_t::const_iterator iter = tempresult.begin();
175 iter != tempresult.end();
176 ++iter) {
177 ASSERT( iter->second.size() == 2,
178 "getTripleFromArgument() - for index "+toString(iter->first)+" we did not find both ik and jk.");
179 result.push_back( FunctionModel::arguments_t(iter->second.begin(), iter->second.end()) );
180 }
181 return result;
182}
183
184int main(int argc, char **argv)
185{
186 std::cout << "Hello to the World from LevMar!" << std::endl;
187
188 // load homology file
189 po::options_description desc("Allowed options");
190 desc.add_options()
191 ("help", "produce help message")
192 ("homology-file", po::value< boost::filesystem::path >(), "homology file to parse")
193 ;
194
195 po::variables_map vm;
196 po::store(po::parse_command_line(argc, argv, desc), vm);
197 po::notify(vm);
198
199 if (vm.count("help")) {
200 std::cout << desc << "\n";
201 return 1;
202 }
203
204 boost::filesystem::path homology_file;
205 if (vm.count("homology-file")) {
206 homology_file = vm["homology-file"].as<boost::filesystem::path>();
207 LOG(1, "INFO: Parsing " << homology_file.string() << ".");
208 } else {
209 LOG(0, "homology-file level was not set.");
210 }
211 HomologyContainer homologies;
212 if (boost::filesystem::exists(homology_file)) {
213 std::ifstream returnstream(homology_file.string().c_str());
214 if (returnstream.good()) {
215 boost::archive::text_iarchive ia(returnstream);
216 ia >> homologies;
217 } else {
218 ELOG(2, "Failed to parse from " << homology_file.string() << ".");
219 }
220 returnstream.close();
221 } else {
222 ELOG(0, homology_file << " does not exist.");
223 }
224
225 // first we try to look into the HomologyContainer
226 LOG(1, "INFO: Listing all present homologies ...");
227 for (HomologyContainer::container_t::const_iterator iter =
228 homologies.begin(); iter != homologies.end(); ++iter) {
229 LOG(1, "INFO: graph " << iter->first << " has Fragment "
230 << iter->second.first << " and associated energy " << iter->second.second << ".");
231 }
232
233 /******************** Angle TRAINING ********************/
234 {
235 // then we ought to pick the right HomologyGraph ...
236 const HomologyGraph graph = getFirstGraphWithThreeCarbons(homologies);
237 LOG(1, "First representative graph containing three saturated carbons is " << graph << ".");
238
239 // Afterwards we go through all of this type and gather the distance and the energy value
240 TrainingData AngleData(
241 boost::bind(&Extractors::reorderArgumentsByIncreasingDistance,
242 boost::bind(&Extractors::gatherAllSymmetricDistanceArguments,
243 boost::bind(&Extractors::gatherPositionOfTuples,
244 _1, Fragment::charges_t(3,6.)
245 ), _2 // gather carbon triples
246 )
247 )
248 );
249 AngleData(homologies.getHomologousGraphs(graph));
250 LOG(1, "INFO: I gathered the following training data: " << AngleData);
251 // NOTICE that distance are in bohrradi as they come from MPQC!
252
253 // now perform the function approximation by optimizing the model function
254 FunctionModel::parameters_t params(PairPotential_Angle::MAXPARAMS, 0.);
255 params[PairPotential_Angle::energy_offset] = -1.;
256 params[PairPotential_Angle::spring_constant] = 1.;
257 params[PairPotential_Angle::equilibrium_distance] = 0.2;
258 PairPotential_Angle angle;
259 LOG(0, "INFO: Initial parameters are " << params << ".");
260 angle.setParameters(params);
261 FunctionModel &model = angle;
262 FunctionApproximation approximator(AngleData, model);
263 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
264 approximator(FunctionApproximation::ParameterDerivative);
265 else
266 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
267 params = model.getParameters();
268
269 LOG(0, "RESULT: Best parameters are " << params << ".");
270 }
271
272 /******************** MORSE TRAINING ********************/
273 {
274 // then we ought to pick the right HomologyGraph ...
275 const HomologyGraph graph = getFirstGraphWithTwoCarbons(homologies);
276 LOG(1, "First representative graph containing two saturated carbons is " << graph << ".");
277
278 // Afterwards we go through all of this type and gather the distance and the energy value
279 TrainingData MorseData(
280 boost::bind(&Extractors::gatherAllSymmetricDistanceArguments,
281 boost::bind(&Extractors::gatherPositionOfTuples,
282 _1, Fragment::charges_t(2,6.)
283 ), _2 // gather first carbon pair
284 )
285 );
286 MorseData(homologies.getHomologousGraphs(graph));
287 LOG(1, "INFO: I gathered the following training data: " << MorseData);
288 // NOTICE that distance are in bohrradi as they come from MPQC!
289
290 // now perform the function approximation by optimizing the model function
291 FunctionModel::parameters_t params(PairPotential_Morse::MAXPARAMS, 0.);
292 params[PairPotential_Morse::dissociation_energy] = 0.5;
293 params[PairPotential_Morse::energy_offset] = -1.;
294 params[PairPotential_Morse::spring_constant] = 1.;
295 params[PairPotential_Morse::equilibrium_distance] = 2.9;
296 PairPotential_Morse morse;
297 morse.setParameters(params);
298 FunctionModel &model = morse;
299 FunctionApproximation approximator(MorseData, model); // we only give CC distance, hence 1 input dim
300 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
301 approximator(FunctionApproximation::ParameterDerivative);
302 else
303 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
304 params = model.getParameters();
305
306 LOG(0, "RESULT: Best parameters are " << params << ".");
307 }
308
309 /******************* SATURATION TRAINING *******************/
310 FunctionModel::parameters_t params(SaturationPotential::MAXPARAMS, 0.);
311 {
312 // then we ought to pick the right HomologyGraph ...
313 const HomologyGraph graph = getFirstGraphWithOneCarbon(homologies);
314 LOG(1, "First representative graph containing one saturated carbon is " << graph << ".");
315
316 // Afterwards we go through all of this type and gather the distance and the energy value
317 TrainingData TersoffData(
318 TrainingData::extractor_t(&Extractors::gatherAllDistances) // gather first carbon pair
319 );
320 TersoffData( homologies.getHomologousGraphs(graph) );
321 LOG(1, "INFO: I gathered the following training data: " << TersoffData);
322 // NOTICE that distance are in bohrradi as they come from MPQC!
323
324 // now perform the function approximation by optimizing the model function
325 boost::function< std::vector<FunctionModel::arguments_t>(const argument_t &, const double)> triplefunction =
326 boost::bind(&getTripleFromArgument, boost::cref(TersoffData.getTrainingInputs()), _1, _2);
327 srand((unsigned)time(0)); // seed with current time
328 LOG(0, "INFO: Initial parameters are " << params << ".");
329
330 SaturationPotential saturation(triplefunction);
331 saturation.setParameters(params);
332 FunctionModel &model = saturation;
333 FunctionApproximation approximator(TersoffData, model); // CH4 has 5 atoms, hence 5*4/2 distances
334 if (model.isBoxConstraint() && approximator.checkParameterDerivatives())
335 approximator(FunctionApproximation::ParameterDerivative);
336 else
337 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
338
339 params = model.getParameters();
340
341 LOG(0, "RESULT: Best parameters are " << params << ".");
342
343// std::cout << "\tsaturationparticle:";
344// std::cout << "\tparticle_type=C,";
345// std::cout << "\tA=" << params[SaturationPotential::A] << ",";
346// std::cout << "\tB=" << params[SaturationPotential::B] << ",";
347// std::cout << "\tlambda=" << params[SaturationPotential::lambda] << ",";
348// std::cout << "\tmu=" << params[SaturationPotential::mu] << ",";
349// std::cout << "\tbeta=" << params[SaturationPotential::beta] << ",";
350// std::cout << "\tn=" << params[SaturationPotential::n] << ",";
351// std::cout << "\tc=" << params[SaturationPotential::c] << ",";
352// std::cout << "\td=" << params[SaturationPotential::d] << ",";
353// std::cout << "\th=" << params[SaturationPotential::h] << ",";
354//// std::cout << "\toffset=" << params[SaturationPotential::offset] << ",";
355// std::cout << "\tR=" << saturation.R << ",";
356// std::cout << "\tS=" << saturation.S << ";";
357// std::cout << std::endl;
358
359 // check L2 and Lmax error against training set
360 LOG(1, "INFO: L2sum = " << TersoffData.getL2Error(model)
361 << ", LMax = " << TersoffData.getLMaxError(model) << ".");
362 }
363
364 return 0;
365}
Note: See TracBrowser for help on using the repository browser.