source: src/FunctionApproximation/FunctionApproximation.cpp@ 3c1465

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

FunctionApproximation now uses levmar_der, i.e. additionally the derivative of the FunctionModel.

  • Property mode set to 100644
File size: 10.4 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 * FunctionApproximation.cpp
26 *
27 * Created on: 02.10.2012
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "FunctionApproximation.hpp"
39
40#include <algorithm>
41#include <boost/bind.hpp>
42#include <boost/function.hpp>
43#include <iostream>
44#include <iterator>
45#include <numeric>
46#include <sstream>
47
48#include <levmar.h>
49
50#include "CodePatterns/Assert.hpp"
51#include "CodePatterns/Log.hpp"
52
53#include "FunctionApproximation/FunctionModel.hpp"
54
55void FunctionApproximation::setTrainingData(const inputs_t &input, const outputs_t &output)
56{
57 ASSERT( input.size() == output.size(),
58 "FunctionApproximation::setTrainingData() - the number of input and output tuples differ: "+toString(input.size())+"!="
59 +toString(output.size())+".");
60 if (input.size() != 0) {
61 ASSERT( input[0].size() == input_dimension,
62 "FunctionApproximation::setTrainingData() - the dimension of the input tuples and input dimension differ: "+toString(input[0].size())+"!="
63 +toString(input_dimension)+".");
64 input_data = input;
65 ASSERT( output[0].size() == output_dimension,
66 "FunctionApproximation::setTrainingData() - the dimension of the output tuples and output dimension differ: "+toString(output[0].size())+"!="
67 +toString(output_dimension)+".");
68 output_data = output;
69 } else {
70 ELOG(2, "Given vectors of training data are empty, clearing internal vectors accordingly.");
71 input_data.clear();
72 output_data.clear();
73 }
74}
75
76void FunctionApproximation::setModelFunction(FunctionModel &_model)
77{
78 model= _model;
79}
80
81/** Callback to circumvent boost::bind, boost::function and function pointer problem.
82 *
83 * See here (second answer!) to the nature of the problem:
84 * http://stackoverflow.com/questions/282372/demote-boostfunction-to-a-plain-function-pointer
85 *
86 * We cannot use a boost::bind bounded boost::function as a function pointer.
87 * boost::function::target() will just return NULL because the signature does not
88 * match. We have to use a C-style callback function and our luck is that
89 * the levmar signature provides for a void* additional data pointer which we
90 * can cast back to our FunctionApproximation class, as we need access to the
91 * data contained, e.g. the FunctionModel reference FunctionApproximation::model.
92 *
93 */
94void FunctionApproximation::LevMarCallback(double *p, double *x, int m, int n, void *data)
95{
96 FunctionApproximation *approximator = static_cast<FunctionApproximation *>(data);
97 ASSERT( approximator != NULL,
98 "LevMarCallback() - received data does not represent a FunctionApproximation object.");
99 boost::function<void(double*,double*,int,int,void*)> function =
100 boost::bind(&FunctionApproximation::evaluate, approximator, _1, _2, _3, _4, _5);
101 function(p,x,m,n,data);
102}
103
104void FunctionApproximation::LevMarDerivativeCallback(double *p, double *x, int m, int n, void *data)
105{
106 FunctionApproximation *approximator = static_cast<FunctionApproximation *>(data);
107 ASSERT( approximator != NULL,
108 "LevMarDerivativeCallback() - received data does not represent a FunctionApproximation object.");
109 boost::function<void(double*,double*,int,int,void*)> function =
110 boost::bind(&FunctionApproximation::evaluateDerivative, approximator, _1, _2, _3, _4, _5);
111 function(p,x,m,n,data);
112}
113
114
115void FunctionApproximation::operator()()
116{
117 // let levmar optimize
118 register int i, j;
119 int ret;
120 double *p;
121 double *x; // we set zero vector by giving NULL
122 int m, n;
123 double opts[LM_OPTS_SZ], info[LM_INFO_SZ];
124
125 opts[0]=LM_INIT_MU; opts[1]=1E-15; opts[2]=1E-15; opts[3]=1E-20;
126 opts[4]= LM_DIFF_DELTA; // relevant only if the Jacobian is approximated using finite differences; specifies forward differencing
127 //opts[4]=-LM_DIFF_DELTA; // specifies central differencing to approximate Jacobian; more accurate but more expensive to compute!
128
129 m = model.getParameterDimension();
130 n = output_data.size();
131 const FunctionModel::parameters_t params = model.getParameters();
132 {
133 p = new double[m];
134 size_t index = 0;
135 for(FunctionModel::parameters_t::const_iterator paramiter = params.begin();
136 paramiter != params.end();
137 ++paramiter, ++index) {
138 p[index] = *paramiter;
139 }
140 }
141 {
142 x = new double[n];
143 size_t index = 0;
144 for(outputs_t::const_iterator outiter = output_data.begin();
145 outiter != output_data.end();
146 ++outiter, ++index) {
147 x[index] = (*outiter)[0];
148 }
149 }
150
151 {
152 double *work, *covar;
153 work=(double *)malloc((LM_DIF_WORKSZ(m, n)+m*m)*sizeof(double));
154 if(!work){
155 ELOG(0, "FunctionApproximation::operator() - memory allocation request failed.");
156 return;
157 }
158 covar=work+LM_DIF_WORKSZ(m, n);
159
160 // give this pointer as additional data to construct function pointer in
161 // LevMarCallback and call
162// ret=dlevmar_dif(
163// &FunctionApproximation::LevMarCallback,
164// p, x, m, n, 1000, opts, info, work, covar, this); // no Jacobian, caller allocates work memory, covariance estimated
165 ret=dlevmar_der(
166 &FunctionApproximation::LevMarCallback,
167 &FunctionApproximation::LevMarDerivativeCallback,
168 p, x, m, n, 1000, opts, info, work, covar, this); // no Jacobian, caller allocates work memory, covariance estimated
169
170 {
171 std::stringstream covar_msg;
172 covar_msg << "Covariance of the fit:\n";
173 for(i=0; i<m; ++i){
174 for(j=0; j<m; ++j)
175 covar_msg << covar[i*m+j] << " ";
176 covar_msg << std::endl;
177 }
178 covar_msg << std::endl;
179 LOG(1, "INFO: " << covar_msg.str());
180 }
181
182 free(work);
183 }
184
185 {
186 std::stringstream result_msg;
187 result_msg << "Levenberg-Marquardt returned " << ret << " in " << info[5] << " iter, reason " << info[6] << "\nSolution: ";
188 for(i=0; i<m; ++i)
189 result_msg << p[i] << " ";
190 result_msg << "\n\nMinimization info:\n";
191 std::vector<std::string> infonames(LM_INFO_SZ);
192 infonames[0] = std::string("||e||_2 at initial p");
193 infonames[1] = std::string("||e||_2");
194 infonames[2] = std::string("||J^T e||_inf");
195 infonames[3] = std::string("||Dp||_2");
196 infonames[4] = std::string("mu/max[J^T J]_ii");
197 infonames[5] = std::string("# iterations");
198 infonames[6] = std::string("reason for termination");
199 infonames[7] = std::string(" # function evaluations");
200 infonames[8] = std::string(" # Jacobian evaluations");
201 infonames[9] = std::string(" # linear systems solved");
202 for(i=0; i<LM_INFO_SZ; ++i)
203 result_msg << infonames[i] << ": " << info[i] << " ";
204 result_msg << std::endl;
205 LOG(1, "INFO: " << result_msg.str());
206 }
207
208 {
209 double *err = new double[n];
210 dlevmar_chkjac(
211 &FunctionApproximation::LevMarCallback,
212 &FunctionApproximation::LevMarDerivativeCallback,
213 p, m, n, this, err);
214 for(i=0; i<n; ++i)
215 LOG(1, "INFO: gradient " << i << ", err " << err[i] << ".");
216 delete[] err;
217 }
218
219
220 delete[] p;
221 delete[] x;
222}
223
224double SquaredDifference(const double res1, const double res2)
225{
226 return (res1-res2)*(res1-res2);
227}
228
229void FunctionApproximation::prepareModel(double *p, int m)
230{
231 ASSERT( (size_t)m == model.getParameterDimension(),
232 "FunctionApproximation::prepareModel() - LevMar expects "+toString(m)
233 +" parameters but the model function expects "+toString(model.getParameterDimension())+".");
234 FunctionModel::parameters_t params(m, 0.);
235 std::copy(p, p+m, params.begin());
236 model.setParameters(params);
237}
238
239void FunctionApproximation::evaluate(double *p, double *x, int m, int n, void *data)
240{
241 // first set parameters
242 prepareModel(p,m);
243
244 // then evaluate
245 ASSERT( (size_t)n == output_data.size(),
246 "FunctionApproximation::evaluate() - LevMar expects "+toString(n)
247 +" outputs but we provide "+toString(output_data.size())+".");
248 if (!output_data.empty()) {
249 inputs_t::const_iterator initer = input_data.begin();
250 outputs_t::const_iterator outiter = output_data.begin();
251 size_t index = 0;
252 for (; initer != input_data.end(); ++initer, ++outiter) {
253 // result may be a vector, calculate L2 norm
254 const FunctionModel::results_t functionvalue =
255 model(*initer);
256 x[index++] = functionvalue[0];
257// std::vector<double> differences(functionvalue.size(), 0.);
258// std::transform(
259// functionvalue.begin(), functionvalue.end(), outiter->begin(),
260// differences.begin(),
261// &SquaredDifference);
262// x[index] = std::accumulate(differences.begin(), differences.end(), 0.);
263 }
264 }
265}
266
267void FunctionApproximation::evaluateDerivative(double *p, double *jac, int m, int n, void *data)
268{
269 // first set parameters
270 prepareModel(p,m);
271
272 // then evaluate
273 ASSERT( (size_t)n == output_data.size(),
274 "FunctionApproximation::evaluateDerivative() - LevMar expects "+toString(n)
275 +" outputs but we provide "+toString(output_data.size())+".");
276 if (!output_data.empty()) {
277 inputs_t::const_iterator initer = input_data.begin();
278 outputs_t::const_iterator outiter = output_data.begin();
279 size_t index = 0;
280 for (; initer != input_data.end(); ++initer, ++outiter) {
281 // result may be a vector, calculate L2 norm
282 for (int paramindex = 0; paramindex < m; ++paramindex) {
283 const FunctionModel::results_t functionvalue =
284 model.parameter_derivative(*initer, paramindex);
285 jac[index++] = functionvalue[0];
286 }
287// std::vector<double> differences(functionvalue.size(), 0.);
288// std::transform(
289// functionvalue.begin(), functionvalue.end(), outiter->begin(),
290// differences.begin(),
291// &SquaredDifference);
292// x[index] = std::accumulate(differences.begin(), differences.end(), 0.);
293 }
294 }
295}
Note: See TracBrowser for help on using the repository browser.