source: src/LevMartester.cpp@ e920d3d

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

Added getFirstGraphwithTimesSpecificElement().

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