source: src/FunctionApproximation/FunctionApproximation.cpp@ 76e63d

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

Extended FunctionApproximation::operator() to receive JacobianMode parameter.

  • this lets decide between finite differences or supplied parameter derivative.
  • Property mode set to 100644
File size: 10.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 * 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()(const enum JacobianMode mode)
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 if (mode == FiniteDifferences) {
163 ret=dlevmar_dif(
164 &FunctionApproximation::LevMarCallback,
165 p, x, m, n, 1000, opts, info, work, covar, this); // no Jacobian, caller allocates work memory, covariance estimated
166 } else if (mode == ParameterDerivative) {
167 ret=dlevmar_der(
168 &FunctionApproximation::LevMarCallback,
169 &FunctionApproximation::LevMarDerivativeCallback,
170 p, x, m, n, 1000, opts, info, work, covar, this); // no Jacobian, caller allocates work memory, covariance estimated
171 } else {
172 ASSERT(0, "FunctionApproximation::operator() - Unknown jacobian method chosen.");
173 }
174
175 {
176 std::stringstream covar_msg;
177 covar_msg << "Covariance of the fit:\n";
178 for(i=0; i<m; ++i){
179 for(j=0; j<m; ++j)
180 covar_msg << covar[i*m+j] << " ";
181 covar_msg << std::endl;
182 }
183 covar_msg << std::endl;
184 LOG(1, "INFO: " << covar_msg.str());
185 }
186
187 free(work);
188 }
189
190 {
191 std::stringstream result_msg;
192 result_msg << "Levenberg-Marquardt returned " << ret << " in " << info[5] << " iter, reason " << info[6] << "\nSolution: ";
193 for(i=0; i<m; ++i)
194 result_msg << p[i] << " ";
195 result_msg << "\n\nMinimization info:\n";
196 std::vector<std::string> infonames(LM_INFO_SZ);
197 infonames[0] = std::string("||e||_2 at initial p");
198 infonames[1] = std::string("||e||_2");
199 infonames[2] = std::string("||J^T e||_inf");
200 infonames[3] = std::string("||Dp||_2");
201 infonames[4] = std::string("mu/max[J^T J]_ii");
202 infonames[5] = std::string("# iterations");
203 infonames[6] = std::string("reason for termination");
204 infonames[7] = std::string(" # function evaluations");
205 infonames[8] = std::string(" # Jacobian evaluations");
206 infonames[9] = std::string(" # linear systems solved");
207 for(i=0; i<LM_INFO_SZ; ++i)
208 result_msg << infonames[i] << ": " << info[i] << " ";
209 result_msg << std::endl;
210 LOG(1, "INFO: " << result_msg.str());
211 }
212
213 if (mode == ParameterDerivative) {
214 double *err = new double[n];
215 dlevmar_chkjac(
216 &FunctionApproximation::LevMarCallback,
217 &FunctionApproximation::LevMarDerivativeCallback,
218 p, m, n, this, err);
219 for(i=0; i<n; ++i)
220 LOG(1, "INFO: gradient " << i << ", err " << err[i] << ".");
221 delete[] err;
222 }
223
224 delete[] p;
225 delete[] x;
226}
227
228double SquaredDifference(const double res1, const double res2)
229{
230 return (res1-res2)*(res1-res2);
231}
232
233void FunctionApproximation::prepareModel(double *p, int m)
234{
235 ASSERT( (size_t)m == model.getParameterDimension(),
236 "FunctionApproximation::prepareModel() - LevMar expects "+toString(m)
237 +" parameters but the model function expects "+toString(model.getParameterDimension())+".");
238 FunctionModel::parameters_t params(m, 0.);
239 std::copy(p, p+m, params.begin());
240 model.setParameters(params);
241}
242
243void FunctionApproximation::evaluate(double *p, double *x, int m, int n, void *data)
244{
245 // first set parameters
246 prepareModel(p,m);
247
248 // then evaluate
249 ASSERT( (size_t)n == output_data.size(),
250 "FunctionApproximation::evaluate() - LevMar expects "+toString(n)
251 +" outputs but we provide "+toString(output_data.size())+".");
252 if (!output_data.empty()) {
253 inputs_t::const_iterator initer = input_data.begin();
254 outputs_t::const_iterator outiter = output_data.begin();
255 size_t index = 0;
256 for (; initer != input_data.end(); ++initer, ++outiter) {
257 // result may be a vector, calculate L2 norm
258 const FunctionModel::results_t functionvalue =
259 model(*initer);
260 x[index++] = functionvalue[0];
261// std::vector<double> differences(functionvalue.size(), 0.);
262// std::transform(
263// functionvalue.begin(), functionvalue.end(), outiter->begin(),
264// differences.begin(),
265// &SquaredDifference);
266// x[index] = std::accumulate(differences.begin(), differences.end(), 0.);
267 }
268 }
269}
270
271void FunctionApproximation::evaluateDerivative(double *p, double *jac, int m, int n, void *data)
272{
273 // first set parameters
274 prepareModel(p,m);
275
276 // then evaluate
277 ASSERT( (size_t)n == output_data.size(),
278 "FunctionApproximation::evaluateDerivative() - LevMar expects "+toString(n)
279 +" outputs but we provide "+toString(output_data.size())+".");
280 if (!output_data.empty()) {
281 inputs_t::const_iterator initer = input_data.begin();
282 outputs_t::const_iterator outiter = output_data.begin();
283 size_t index = 0;
284 for (; initer != input_data.end(); ++initer, ++outiter) {
285 // result may be a vector, calculate L2 norm
286 for (int paramindex = 0; paramindex < m; ++paramindex) {
287 const FunctionModel::results_t functionvalue =
288 model.parameter_derivative(*initer, paramindex);
289 jac[index++] = functionvalue[0];
290 }
291// std::vector<double> differences(functionvalue.size(), 0.);
292// std::transform(
293// functionvalue.begin(), functionvalue.end(), outiter->begin(),
294// differences.begin(),
295// &SquaredDifference);
296// x[index] = std::accumulate(differences.begin(), differences.end(), 0.);
297 }
298 }
299}
Note: See TracBrowser for help on using the repository browser.