source: src/LevMartester.cpp@ eb1efe

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

Extended LevMartester to fit a Tersoff potential to the first order fragments.

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