source: src/LevMartester.cpp@ 2ba2ed

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

FIX: SaturationPotential's parameter derivatives seem to be working now.

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