1 | /*
|
---|
2 | * Project: MoleCuilder
|
---|
3 | * Description: creates and alters molecular systems
|
---|
4 | * Copyright (C) 2013 University of Bonn. All rights reserved.
|
---|
5 | * Copyright (C) 2013 Frederik Heber. All rights reserved.
|
---|
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 | * FitPotentialAction.cpp
|
---|
26 | *
|
---|
27 | * Created on: Apr 09, 2013
|
---|
28 | * Author: heber
|
---|
29 | */
|
---|
30 |
|
---|
31 | // include config.h
|
---|
32 | #ifdef HAVE_CONFIG_H
|
---|
33 | #include <config.h>
|
---|
34 | #endif
|
---|
35 |
|
---|
36 | // needs to come before MemDebug due to placement new
|
---|
37 | #include <boost/archive/text_iarchive.hpp>
|
---|
38 |
|
---|
39 | #include "CodePatterns/MemDebug.hpp"
|
---|
40 |
|
---|
41 | #include <algorithm>
|
---|
42 | #include <boost/bind.hpp>
|
---|
43 | #include <boost/filesystem.hpp>
|
---|
44 | #include <boost/foreach.hpp>
|
---|
45 | #include <map>
|
---|
46 | #include <string>
|
---|
47 | #include <sstream>
|
---|
48 |
|
---|
49 | #include "Actions/FragmentationAction/FitPotentialAction.hpp"
|
---|
50 |
|
---|
51 | #include "CodePatterns/Log.hpp"
|
---|
52 |
|
---|
53 | #include "Element/element.hpp"
|
---|
54 | #include "Fragmentation/Homology/HomologyContainer.hpp"
|
---|
55 | #include "Fragmentation/Homology/HomologyGraph.hpp"
|
---|
56 | #include "Fragmentation/Summation/SetValues/Fragment.hpp"
|
---|
57 | #include "FunctionApproximation/Extractors.hpp"
|
---|
58 | #include "FunctionApproximation/FunctionApproximation.hpp"
|
---|
59 | #include "FunctionApproximation/FunctionModel.hpp"
|
---|
60 | #include "FunctionApproximation/TrainingData.hpp"
|
---|
61 | #include "FunctionApproximation/writeDistanceEnergyTable.hpp"
|
---|
62 | #include "Potentials/CompoundPotential.hpp"
|
---|
63 | #include "Potentials/PotentialDeserializer.hpp"
|
---|
64 | #include "Potentials/PotentialFactory.hpp"
|
---|
65 | #include "Potentials/PotentialRegistry.hpp"
|
---|
66 | #include "Potentials/PotentialSerializer.hpp"
|
---|
67 | #include "Potentials/SerializablePotential.hpp"
|
---|
68 |
|
---|
69 | using namespace MoleCuilder;
|
---|
70 |
|
---|
71 | // and construct the stuff
|
---|
72 | #include "FitPotentialAction.def"
|
---|
73 | #include "Action_impl_pre.hpp"
|
---|
74 | /** =========== define the function ====================== */
|
---|
75 |
|
---|
76 | HomologyGraph getFirstGraphwithSpecifiedElements(
|
---|
77 | const HomologyContainer &homologies,
|
---|
78 | const SerializablePotential::ParticleTypes_t &types)
|
---|
79 | {
|
---|
80 | ASSERT( !types.empty(),
|
---|
81 | "getFirstGraphwithSpecifiedElements() - charges is empty?");
|
---|
82 | // create charges
|
---|
83 | Fragment::charges_t charges;
|
---|
84 | charges.resize(types.size());
|
---|
85 | std::transform(types.begin(), types.end(),
|
---|
86 | charges.begin(), boost::lambda::_1);
|
---|
87 | // convert into count map
|
---|
88 | Extractors::elementcounts_t counts_per_charge =
|
---|
89 | Extractors::_detail::getElementCounts(charges);
|
---|
90 | ASSERT( !counts_per_charge.empty(),
|
---|
91 | "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
|
---|
92 | LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
|
---|
93 | // we want to check each (unique) key only once
|
---|
94 | HomologyContainer::const_key_iterator olditer = homologies.key_end();
|
---|
95 | for (HomologyContainer::const_key_iterator iter =
|
---|
96 | homologies.key_begin(); iter != homologies.key_end(); olditer = iter++) {
|
---|
97 | // if it's the same as the old one, skip it
|
---|
98 | if (*olditer == *iter)
|
---|
99 | continue;
|
---|
100 | // if it's a new key, check if every element has the right number of counts
|
---|
101 | Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
|
---|
102 | for (; countiter != counts_per_charge.end(); ++countiter)
|
---|
103 | if (!(*iter).hasTimesAtomicNumber(
|
---|
104 | static_cast<size_t>(countiter->first),
|
---|
105 | static_cast<size_t>(countiter->second))
|
---|
106 | )
|
---|
107 | break;
|
---|
108 | if( countiter == counts_per_charge.end())
|
---|
109 | return *iter;
|
---|
110 | }
|
---|
111 | return HomologyGraph();
|
---|
112 | }
|
---|
113 |
|
---|
114 | Action::state_ptr FragmentationFitPotentialAction::performCall() {
|
---|
115 | // fragment specifies the homology fragment to use
|
---|
116 | SerializablePotential::ParticleTypes_t fragmentnumbers;
|
---|
117 | {
|
---|
118 | const std::vector<const element *> &fragment = params.fragment.get();
|
---|
119 | std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
|
---|
120 | boost::bind(&element::getAtomicNumber, _1));
|
---|
121 | }
|
---|
122 |
|
---|
123 | // either charges and a potential is specified or a file
|
---|
124 | if (boost::filesystem::exists(params.potential_file.get())) {
|
---|
125 | std::ifstream returnstream(params.potential_file.get().string().c_str());
|
---|
126 | if (returnstream.good()) {
|
---|
127 | PotentialDeserializer deserialize(returnstream);
|
---|
128 | deserialize();
|
---|
129 | } else {
|
---|
130 | ELOG(0, "Failed to parse from " << params.potential_file.get().string() << ".");
|
---|
131 | return Action::failure;
|
---|
132 | }
|
---|
133 | returnstream.close();
|
---|
134 |
|
---|
135 | LOG(0, "STATUS: I'm training now a set of potentials parsed from "
|
---|
136 | << params.potential_file.get().string() << " on a fragment "
|
---|
137 | << fragmentnumbers << " on data from " << params.homology_file.get() << ".");
|
---|
138 |
|
---|
139 | } else {
|
---|
140 | if (params.charges.get().empty()) {
|
---|
141 | ELOG(1, "Neither charges nor potential file given!");
|
---|
142 | return Action::failure;
|
---|
143 | } else {
|
---|
144 | // charges specify the potential type
|
---|
145 | SerializablePotential::ParticleTypes_t chargenumbers;
|
---|
146 | {
|
---|
147 | const std::vector<const element *> &charges = params.charges.get();
|
---|
148 | std::transform(charges.begin(), charges.end(), std::back_inserter(chargenumbers),
|
---|
149 | boost::bind(&element::getAtomicNumber, _1));
|
---|
150 | }
|
---|
151 |
|
---|
152 | LOG(0, "STATUS: I'm training now a " << params.potentialtype.get()
|
---|
153 | << " potential on charges " << chargenumbers << " on data from "
|
---|
154 | << params.homology_file.get() << ".");
|
---|
155 |
|
---|
156 | // register desired potential and an additional constant one
|
---|
157 | EmpiricalPotential *potential =
|
---|
158 | PotentialFactory::getInstance().createInstance(
|
---|
159 | params.potentialtype.get(),
|
---|
160 | chargenumbers);
|
---|
161 | PotentialRegistry::getInstance().registerInstance(potential);
|
---|
162 | EmpiricalPotential *constant =
|
---|
163 | PotentialFactory::getInstance().createInstance(
|
---|
164 | std::string("constant"),
|
---|
165 | SerializablePotential::ParticleTypes_t());
|
---|
166 | PotentialRegistry::getInstance().registerInstance(constant);
|
---|
167 | }
|
---|
168 | }
|
---|
169 |
|
---|
170 | // parse homologies into container
|
---|
171 | HomologyContainer homologies;
|
---|
172 | if (boost::filesystem::exists(params.homology_file.get())) {
|
---|
173 | std::ifstream returnstream(params.homology_file.get().string().c_str());
|
---|
174 | if (returnstream.good()) {
|
---|
175 | boost::archive::text_iarchive ia(returnstream);
|
---|
176 | ia >> homologies;
|
---|
177 | } else {
|
---|
178 | ELOG(0, "Failed to parse from " << params.homology_file.get().string() << ".");
|
---|
179 | return Action::failure;
|
---|
180 | }
|
---|
181 | returnstream.close();
|
---|
182 | } else {
|
---|
183 | ELOG(0, params.homology_file.get() << " does not exist.");
|
---|
184 | return Action::failure;
|
---|
185 | }
|
---|
186 |
|
---|
187 | // first we try to look into the HomologyContainer
|
---|
188 | LOG(1, "INFO: Listing all present homologies ...");
|
---|
189 | for (HomologyContainer::container_t::const_iterator iter =
|
---|
190 | homologies.begin(); iter != homologies.end(); ++iter) {
|
---|
191 | LOG(1, "INFO: graph " << iter->first << " has Fragment " << iter->second.first
|
---|
192 | << " and associated energy " << iter->second.second << ".");
|
---|
193 | }
|
---|
194 |
|
---|
195 | // then we ought to pick the right HomologyGraph ...
|
---|
196 | const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
|
---|
197 | if (graph != HomologyGraph()) {
|
---|
198 | LOG(1, "First representative graph containing fragment "
|
---|
199 | << fragmentnumbers << " is " << graph << ".");
|
---|
200 | } else {
|
---|
201 | ELOG(1, "Specific fragment " << fragmentnumbers << " not found in homologies!");
|
---|
202 | return Action::failure;
|
---|
203 | }
|
---|
204 |
|
---|
205 | // fit potential
|
---|
206 | FunctionModel *model = new CompoundPotential(graph);
|
---|
207 | ASSERT( model != NULL,
|
---|
208 | "FragmentationFitPotentialAction::performCall() - model is NULL.");
|
---|
209 |
|
---|
210 | /******************** TRAINING ********************/
|
---|
211 | // fit potential
|
---|
212 | FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.);
|
---|
213 | {
|
---|
214 | // Afterwards we go through all of this type and gather the distance and the energy value
|
---|
215 | TrainingData data(model->getFragmentSpecificExtractor());
|
---|
216 | data(homologies.getHomologousGraphs(graph));
|
---|
217 |
|
---|
218 | // print distances and energies if desired for debugging
|
---|
219 | if (!data.getTrainingInputs().empty()) {
|
---|
220 | // print which distance is which
|
---|
221 | size_t counter=1;
|
---|
222 | if (DoLog(3)) {
|
---|
223 | const FunctionModel::arguments_t &inputs = data.getTrainingInputs()[0];
|
---|
224 | for (FunctionModel::arguments_t::const_iterator iter = inputs.begin();
|
---|
225 | iter != inputs.end(); ++iter) {
|
---|
226 | const argument_t &arg = *iter;
|
---|
227 | LOG(3, "DEBUG: distance " << counter++ << " is between (#"
|
---|
228 | << arg.indices.first << "c" << arg.types.first << ","
|
---|
229 | << arg.indices.second << "c" << arg.types.second << ").");
|
---|
230 | }
|
---|
231 | }
|
---|
232 |
|
---|
233 | // print table
|
---|
234 | LOG(3, "DEBUG: I gathered the following training data:\n" <<
|
---|
235 | _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()));
|
---|
236 | }
|
---|
237 |
|
---|
238 | // now perform the function approximation by optimizing the model function
|
---|
239 | FunctionApproximation approximator(data, *model);
|
---|
240 | if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) {
|
---|
241 | double l2error = std::numeric_limits<double>::infinity();
|
---|
242 | // seed with current time
|
---|
243 | srand((unsigned)time(0));
|
---|
244 | for (unsigned int runs=0; runs < params.best_of_howmany.get(); ++runs) {
|
---|
245 | // generate new random initial parameter values
|
---|
246 | model->setParametersToRandomInitialValues(data);
|
---|
247 | LOG(1, "INFO: Initial parameters of run " << runs << " are "
|
---|
248 | << model->getParameters() << ".");
|
---|
249 | approximator(FunctionApproximation::ParameterDerivative);
|
---|
250 | LOG(1, "INFO: Final parameters of run " << runs << " are "
|
---|
251 | << model->getParameters() << ".");
|
---|
252 | const double new_l2error = data.getL2Error(*model);
|
---|
253 | if (new_l2error < l2error) {
|
---|
254 | // store currently best parameters
|
---|
255 | l2error = new_l2error;
|
---|
256 | bestparams = model->getParameters();
|
---|
257 | LOG(1, "STATUS: New fit from run " << runs
|
---|
258 | << " has better error of " << l2error << ".");
|
---|
259 | }
|
---|
260 | }
|
---|
261 | // reset parameters from best fit
|
---|
262 | model->setParameters(bestparams);
|
---|
263 | LOG(1, "INFO: Best parameters with L2 error of "
|
---|
264 | << l2error << " are " << model->getParameters() << ".");
|
---|
265 | } else {
|
---|
266 | ELOG(0, "We require parameter derivatives for a box constraint minimization.");
|
---|
267 | return Action::failure;
|
---|
268 | }
|
---|
269 |
|
---|
270 | // create a map of each fragment with error.
|
---|
271 | typedef std::multimap< double, size_t > WorseFragmentMap_t;
|
---|
272 | WorseFragmentMap_t WorseFragmentMap;
|
---|
273 | HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph);
|
---|
274 | // fragments make it into the container in reversed order, hence count from top down
|
---|
275 | size_t index= std::distance(fragmentrange.first, fragmentrange.second)-1;
|
---|
276 | for (HomologyContainer::const_iterator iter = fragmentrange.first;
|
---|
277 | iter != fragmentrange.second;
|
---|
278 | ++iter) {
|
---|
279 | const Fragment& fragment = iter->second.first;
|
---|
280 | const double &energy = iter->second.second;
|
---|
281 |
|
---|
282 | // create arguments from the fragment
|
---|
283 | FunctionModel::extractor_t extractor = model->getFragmentSpecificExtractor();
|
---|
284 | FunctionModel::arguments_t args = extractor(fragment, 1);
|
---|
285 |
|
---|
286 | // calculate value from potential
|
---|
287 | const double fitvalue = (*model)(args)[0];
|
---|
288 |
|
---|
289 | // insert difference into map
|
---|
290 | const double error = fabs(energy - fitvalue);
|
---|
291 | WorseFragmentMap.insert( std::make_pair( error, index-- ) );
|
---|
292 |
|
---|
293 | {
|
---|
294 | // give only the distances in the debugging text
|
---|
295 | std::stringstream streamargs;
|
---|
296 | BOOST_FOREACH (argument_t arg, args) {
|
---|
297 | streamargs << " " << arg.distance*AtomicLengthToAngstroem;
|
---|
298 | }
|
---|
299 | LOG(2, "DEBUG: frag.#" << index+1 << "'s error is |" << energy << " - " << fitvalue
|
---|
300 | << "| = " << error << " for args " << streamargs.str() << ".");
|
---|
301 | }
|
---|
302 | }
|
---|
303 | LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << ".");
|
---|
304 |
|
---|
305 | // print fitted potentials
|
---|
306 | std::stringstream potentials;
|
---|
307 | PotentialSerializer serialize(potentials);
|
---|
308 | serialize();
|
---|
309 | LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str());
|
---|
310 | }
|
---|
311 | delete model;
|
---|
312 |
|
---|
313 | return Action::success;
|
---|
314 | }
|
---|
315 |
|
---|
316 | Action::state_ptr FragmentationFitPotentialAction::performUndo(Action::state_ptr _state) {
|
---|
317 | return Action::success;
|
---|
318 | }
|
---|
319 |
|
---|
320 | Action::state_ptr FragmentationFitPotentialAction::performRedo(Action::state_ptr _state){
|
---|
321 | return Action::success;
|
---|
322 | }
|
---|
323 |
|
---|
324 | bool FragmentationFitPotentialAction::canUndo() {
|
---|
325 | return false;
|
---|
326 | }
|
---|
327 |
|
---|
328 | bool FragmentationFitPotentialAction::shouldUndo() {
|
---|
329 | return false;
|
---|
330 | }
|
---|
331 | /** =========== end of function ====================== */
|
---|