source: src/LevMartester.cpp@ 77552d

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

FIX: LevMartester gives which distance in written table refers to which argument.

  • Property mode set to 100644
File size: 14.0 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/assign/list_of.hpp>
43#include <boost/bind.hpp>
44#include <boost/filesystem.hpp>
45#include <boost/foreach.hpp>
46#include <boost/function.hpp>
47#include <boost/program_options.hpp>
48
49#include <cstdlib>
50#include <ctime>
51#include <fstream>
52#include <iostream>
53#include <iterator>
54#include <list>
55#include <vector>
56
57#include <levmar.h>
58
59#include "CodePatterns/Assert.hpp"
60#include "CodePatterns/Log.hpp"
61
62#include "LinearAlgebra/Vector.hpp"
63
64#include "Fragmentation/Homology/HomologyContainer.hpp"
65#include "Fragmentation/SetValues/Fragment.hpp"
66#include "FunctionApproximation/Extractors.hpp"
67#include "FunctionApproximation/FunctionApproximation.hpp"
68#include "FunctionApproximation/FunctionModel.hpp"
69#include "FunctionApproximation/TrainingData.hpp"
70#include "FunctionApproximation/writeDistanceEnergyTable.hpp"
71#include "Helpers/defs.hpp"
72#include "Potentials/PotentialFactory.hpp"
73#include "Potentials/PotentialRegistry.hpp"
74#include "Potentials/Specifics/PairPotential_Morse.hpp"
75#include "Potentials/Specifics/PairPotential_Angle.hpp"
76#include "Potentials/Specifics/SaturationPotential.hpp"
77#include "types.hpp"
78
79namespace po = boost::program_options;
80
81using namespace boost::assign;
82
83HomologyGraph getFirstGraphwithSpecifiedElements(
84 const HomologyContainer &homologies,
85 const FunctionModel::charges_t &charges)
86{
87 ASSERT( !charges.empty(),
88 "getFirstGraphwithSpecifiedElements() - charges is empty?");
89 // convert into count map
90 Extractors::elementcounts_t counts_per_charge =
91 Extractors::_detail::getElementCounts(charges);
92 ASSERT( !counts_per_charge.empty(),
93 "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
94 LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
95 // we want to check each (unique) key only once
96 HomologyContainer::const_key_iterator olditer = homologies.key_end();
97 for (HomologyContainer::const_key_iterator iter =
98 homologies.key_begin(); iter != homologies.key_end(); olditer = iter++) {
99 // if it's the same as the old one, skip it
100 if (*olditer == *iter)
101 continue;
102 // if it's a new key, check if every element has the right number of counts
103 Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
104 for (; countiter != counts_per_charge.end(); ++countiter)
105 if (!(*iter).hasTimesAtomicNumber(countiter->first,countiter->second))
106 break;
107 if( countiter == counts_per_charge.end())
108 return *iter;
109 }
110 return HomologyGraph();
111}
112
113/** This function returns the elements of the sum over index "k" for an
114 * argument containing indices "i" and "j"
115 * @param inputs vector of all configuration (containing each a vector of all arguments)
116 * @param arg argument containing indices "i" and "j"
117 * @param cutoff cutoff criterion for sum over k
118 * @return vector of argument pairs (a vector) of ik and jk for at least all k
119 * within distance of \a cutoff to i
120 */
121std::vector<FunctionModel::arguments_t>
122getTripleFromArgument(const FunctionApproximation::inputs_t &inputs, const argument_t &arg, const double cutoff)
123{
124 typedef std::list<argument_t> arg_list_t;
125 typedef std::map<size_t, arg_list_t > k_args_map_t;
126 k_args_map_t tempresult;
127 ASSERT( inputs.size() > arg.globalid,
128 "getTripleFromArgument() - globalid "+toString(arg.globalid)
129 +" is greater than all inputs "+toString(inputs.size())+".");
130 const FunctionModel::arguments_t &listofargs = inputs[arg.globalid];
131 for (FunctionModel::arguments_t::const_iterator argiter = listofargs.begin();
132 argiter != listofargs.end();
133 ++argiter) {
134 // first index must be either i or j but second index not
135 if (((argiter->indices.first == arg.indices.first)
136 || (argiter->indices.first == arg.indices.second))
137 && ((argiter->indices.second != arg.indices.first)
138 && (argiter->indices.second != arg.indices.second))) {
139 // we need arguments ik and jk
140 std::pair< k_args_map_t::iterator, bool> inserter =
141 tempresult.insert( std::make_pair( argiter->indices.second, arg_list_t(1,*argiter)));
142 if (!inserter.second) {
143 // is present one ik or jk, if ik insert jk at back
144 if (inserter.first->second.begin()->indices.first == arg.indices.first)
145 inserter.first->second.push_back(*argiter);
146 else // if jk, insert ik at front
147 inserter.first->second.push_front(*argiter);
148 }
149 }
150// // or second index must be either i or j but first index not
151// else 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 ki and kj
156// std::pair< k_args_map_t::iterator, bool> inserter =
157// tempresult.insert( std::make_pair( argiter->indices.first, arg_list_t(1,*argiter)));
158// if (!inserter.second) {
159// // is present one ki or kj, if ki insert kj at back
160// if (inserter.first->second.begin()->indices.second == arg.indices.first)
161// inserter.first->second.push_back(*argiter);
162// else // if kj, insert ki at front
163// inserter.first->second.push_front(*argiter);
164// }
165// }
166 }
167 // check that i,j are NOT contained
168 ASSERT( tempresult.count(arg.indices.first) == 0,
169 "getTripleFromArgument() - first index of argument present in k_args_map?");
170 ASSERT( tempresult.count(arg.indices.second) == 0,
171 "getTripleFromArgument() - first index of argument present in k_args_map?");
172
173 // convert
174 std::vector<FunctionModel::arguments_t> result;
175 for (k_args_map_t::const_iterator iter = tempresult.begin();
176 iter != tempresult.end();
177 ++iter) {
178 ASSERT( iter->second.size() == 2,
179 "getTripleFromArgument() - for index "+toString(iter->first)+" we did not find both ik and jk.");
180 result.push_back( FunctionModel::arguments_t(iter->second.begin(), iter->second.end()) );
181 }
182 return result;
183}
184
185int main(int argc, char **argv)
186{
187 std::cout << "Hello to the World from LevMar!" << std::endl;
188
189 // load homology file
190 po::options_description desc("Allowed options");
191 desc.add_options()
192 ("help", "produce help message")
193 ("homology-file", po::value< boost::filesystem::path >(), "homology file to parse")
194 ("fit-potential", po::value< std::string >(), "potential type to fit")
195 ("charges", po::value< FunctionModel::charges_t >()->multitoken(), "charges specifying the potential")
196 ("fragment", po::value< FunctionModel::charges_t >()->multitoken(), "all charges in the fragment")
197 ;
198
199 po::variables_map vm;
200 po::store(po::parse_command_line(argc, argv, desc), vm);
201 po::notify(vm);
202
203 if (vm.count("help")) {
204 std::cout << desc << "\n";
205 return 1;
206 }
207
208 // homology-file
209 boost::filesystem::path homology_file;
210 if (vm.count("homology-file")) {
211 homology_file = vm["homology-file"].as<boost::filesystem::path>();
212 LOG(1, "INFO: Parsing " << homology_file.string() << ".");
213 } else {
214 ELOG(0, "homology file (homology-file) was not set.");
215 return 1;
216 }
217
218 // type of potential to fit
219 std::string potentialtype;
220 if (vm.count("fit-potential")) {
221 potentialtype = vm["fit-potential"].as<std::string>();
222 } else {
223 ELOG(0, "potential type to fit (fit-potential) was not set.");
224 return 1;
225 }
226
227 // charges
228 FunctionModel::charges_t charges;
229 if (vm.count("charges")) {
230 charges = vm["charges"].as< FunctionModel::charges_t >();
231 } else {
232 ELOG(0, "Vector of charges specifying the potential (charges) was not set.");
233 return 1;
234 }
235
236 // fragment
237 FunctionModel::charges_t fragment;
238 if (vm.count("fragment")) {
239 fragment = vm["fragment"].as< FunctionModel::charges_t >();
240 } else {
241 ELOG(0, "Vector of charges specifying the fragment (charges) was not set.");
242 return 1;
243 }
244
245 // parse homologies into container
246 HomologyContainer homologies;
247 if (boost::filesystem::exists(homology_file)) {
248 std::ifstream returnstream(homology_file.string().c_str());
249 if (returnstream.good()) {
250 boost::archive::text_iarchive ia(returnstream);
251 ia >> homologies;
252 } else {
253 ELOG(0, "Failed to parse from " << homology_file.string() << ".");
254 return 1;
255 }
256 returnstream.close();
257 } else {
258 ELOG(0, homology_file << " does not exist.");
259 return 1;
260 }
261
262 // first we try to look into the HomologyContainer
263 LOG(1, "INFO: Listing all present homologies ...");
264 for (HomologyContainer::container_t::const_iterator iter =
265 homologies.begin(); iter != homologies.end(); ++iter) {
266 LOG(1, "INFO: graph " << iter->first << " has Fragment " << iter->second.first
267 << " and associated energy " << iter->second.second << ".");
268 }
269
270 LOG(0, "STATUS: I'm training now a " << potentialtype << " potential on charges "
271 << charges << ".");
272
273 /******************** TRAINING ********************/
274 // fit potential
275 FunctionModel *model =
276 PotentialFactory::getInstance().createInstance(
277 potentialtype,
278 charges);
279 ASSERT( model != NULL,
280 "main() - model returned from PotentialFactory is NULL.");
281 FunctionModel::parameters_t params(model->getParameterDimension(), 0.);
282 {
283 // then we ought to pick the right HomologyGraph ...
284 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragment);
285 if (graph != HomologyGraph()) {
286 LOG(1, "First representative graph containing fragment "
287 << fragment << " is " << graph << ".");
288
289 // Afterwards we go through all of this type and gather the distance and the energy value
290 TrainingData data(model->getFragmentSpecificExtractor(charges));
291 data(homologies.getHomologousGraphs(graph));
292 if (!data.getTrainingInputs().empty()) {
293 // print which distance is which
294 size_t counter=1;
295 const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
296 for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
297 iter != inputs.end(); ++iter) {
298 const argument_t &arg = *iter;
299 LOG(1, "INFO: distance " << counter++ << " is between (#"
300 << arg.indices.first << "c" << arg.types.first << ","
301 << arg.indices.second << "c" << arg.types.second << ").");
302 }
303
304 // print table
305 LOG(1, "INFO: I gathered the following training data:\n" <<
306 _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
307 }
308 // NOTICE that distance are in bohrradi as they come from MPQC!
309
310 // now perform the function approximation by optimizing the model function
311 FunctionApproximation approximator(data, *model);
312 if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
313 // we set parameters here because we want to test with default ones
314 srand((unsigned)time(0)); // seed with current time
315 model->setParametersToRandomInitialValues(data);
316 LOG(0, "INFO: Initial parameters are " << model->getParameters() << ".");
317 approximator(FunctionApproximation::ParameterDerivative);
318 } else {
319 ELOG(0, "We require parameter derivatives for a box constraint minimization.");
320 return 1;
321 }
322
323 // create a map of each fragment with error.
324 typedef std::multimap< double, size_t > WorseFragmentMap_t;
325 WorseFragmentMap_t WorseFragmentMap;
326 HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
327 // fragments make it into the container in reversed order, hence count from top down
328 size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
329 for (HomologyContainer::const_iterator iter = fragmentrange.first;
330 iter != fragmentrange.second;
331 ++iter) {
332 const Fragment& fragment = iter->second.first;
333 const double &energy = iter->second.second;
334
335 // create arguments from the fragment
336 FunctionModel::extractor_t extractor = model->getFragmentSpecificExtractor(charges);
337 FunctionModel::arguments_t args = extractor(fragment, 1);
338
339 // calculate value from potential
340 const double fitvalue = (*model)(args)[0];
341
342 // insert difference into map
343 const double error = fabs(energy - fitvalue);
344 WorseFragmentMap.insert( std::make_pair( error, index-- ) );
345
346 {
347 // give only the distances in the debugging text
348 std::stringstream streamargs;
349 BOOST_FOREACH (argument_t arg, args) {
350 streamargs << " " << arg.distance*AtomicLengthToAngstroem;
351 }
352 LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
353 << "| = " << error << " for args " << streamargs.str() << ".");
354 }
355 }
356 LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
357
358 params = model->getParameters();
359
360 }
361 }
362 delete model;
363 // remove static instances
364 PotentialFactory::purgeInstance();
365
366 return 0;
367}
368
Note: See TracBrowser for help on using the repository browser.