source: src/LevMartester.cpp@ 105b72

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

Removed typedef charges_t from FunctionModel, using SerializationPotential's instead.

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