Jpp  18.6.0-rc.1
the software that should make you happy
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JGandalf.hh
Go to the documentation of this file.
1 #ifndef __JFIT__JGANDALF__
2 #define __JFIT__JGANDALF__
3 
4 #include <limits>
5 #include <vector>
6 #include <cmath>
7 #include <ostream>
8 #include <iomanip>
9 #include <type_traits>
10 
11 #include "Jeep/JMessage.hh"
12 #include "JMath/JVectorND.hh"
13 #include "JMath/JMatrixNS.hh"
14 #include "JMath/JZero.hh"
15 #include "JLang/JManip.hh"
16 #include "JLang/JException.hh"
17 
18 
19 /**
20  * \author mdejong
21  */
22 
23 namespace JFIT {}
24 namespace JPP { using namespace JFIT; }
25 
26 namespace JFIT {
27 
28  using JEEP::JMessage;
29  using JLANG::JException;
30 
31  namespace JFIT_LOCAL {
32 
33  template<class T>
34  class JTypedef {
35  template<class U> static auto parameter_type(U*) -> decltype(std::declval<typename U::parameter_type>());
36  template<typename> static auto parameter_type(...) -> std::false_type;
37 
38  public:
39  static const bool has_parameter_type = !std::is_same<std::false_type, decltype(parameter_type<T> (0))>::value;
40  };
41 
42  template<class T, bool has_parameter_type = JTypedef<T>::has_parameter_type>
43  struct JTypedef_t;
44 
45  template<class T> struct JTypedef_t<T, true> { typedef typename T::parameter_type parameter_type; };
46  template<class T> struct JTypedef_t<T, false> { typedef double T::*parameter_type; };
47  }
48 
49 
50  /**
51  * Auxiliary function to constrain model during fit.
52  *
53  * \param value model (I/O)
54  */
55  template<class JModel_t>
56  inline void model(JModel_t& value)
57  {}
58 
59 
60  /**
61  * Fit method based on the Levenberg-Marquardt method.
62  *
63  * The template argument refers to the model that should be fitted to the data.\n
64  * This data structure should have arithmetic capabilities.
65  *
66  * The data member JGandalf::value corresponds to the start c.q.\ final value of
67  * the model of the fit procedure and JGandalf::error to the uncertainties.\n
68  * The co-variance matrix is stored in data member JGandalf::V.\n
69  *
70  * The data member JGandalf::parameters constitutes a list of those parameters of the model that should actually be fitted.\n
71  * For this, the model should contain the type definition for <tt>parameter_type</tt>.\n
72  * Normally, this type definition corresponds to a pointer to a data member of the model.\n
73  * If not defined, the parameters are assumed to be data members of type <tt>double</tt>.\n
74  * Alternatively, the type definition can be <tt>size_t</tt> or <tt>int</tt>.\n
75  * In that case, the model should provide for the element access <tt>operator[]</tt>.\n
76  *
77  * The first template parameter in the function operator should provide for an implementation of the actual fit function.\n
78  * This function should return the data type JGandalf::result_type.\n
79  * This data structure comprises the values of the chi2 and the gradient for a given data point.\n
80  * The function operator returns the minimal chi2 and summed gradient of all data points.
81  */
82 
83  template<class JModel_t>
84  class JGandalf :
85  public JMessage< JGandalf<JModel_t> >
86  {
87  public:
88 
90 
91 
92  /**
93  * Data type of fit parameter.
94  */
96 
97 
98  /**
99  * Data structure for return value of fit function.
100  */
101  struct result_type {
102  /**
103  * Default constructor.
104  */
106  chi2 (0.0),
107  gradient()
108  {}
109 
110 
111  /**
112  * Constructor.
113  *
114  * \param chi2 chi2
115  * \param model gradient
116  */
117  result_type(const double chi2,
118  const JModel_t& model) :
119  chi2 (chi2),
120  gradient(model)
121  {}
122 
123 
124  /**
125  * Type conversion operator.
126  *
127  * \return chi2
128  */
129  operator double() const
130  {
131  return chi2;
132  }
133 
134 
135  double chi2; //!< chi2
136  JModel_t gradient; //!< partial derivatives of chi2
137  };
138 
139 
140  /**
141  * Default constructor.
142  */
144  {}
145 
146 
147  /**
148  * Multi-dimensional fit of multiple data sets.
149  *
150  * The fit function should return the chi2 as well as the partial derivatives
151  * for the current value of the model and a given data point.
152  *
153  * \param fit fit function
154  * \param __begin begin of data
155  * \param __end end of data
156  * \param args optional data
157  * \return chi2 and gradient
158  */
159  template<class JFunction_t, class T, class ...Args>
160  result_type operator()(const JFunction_t& fit, T __begin, T __end, Args ...args)
161  {
162  using namespace std;
163  using namespace JPP;
164 
165  // note that all model values should be assigned to the start value of the model before use
166  // because the actual list of model parameters can vary from fit to fit
167  // (e.g. if model consists of a container).
168 
169  const size_t N = parameters.size();
170 
171  V.resize(N);
172  h.resize(N);
173  x.resize(N);
174 
175  previous.result.chi2 = numeric_limits<double>::max();
176 
177  current.result.chi2 = numeric_limits<double>::max();
178  current.result.gradient = value;
179  current.result.gradient = zero;
180 
181  error = value;
182  error = zero;
183 
184  lambda = LAMBDA_MIN;
185 
187 
188  DEBUG("step: " << numberOfIterations << endl);
189 
190  reset();
191 
192  update(fit, __begin, __end, args...);
193 
194  DEBUG("lambda: " << FIXED(12,5) << lambda << endl);
195  DEBUG("chi2: " << FIXED(12,5) << current.result.chi2 << endl);
196 
197  if (current.result.chi2 < previous.result.chi2) {
198 
199  if (numberOfIterations != 0) {
200 
201  if (fabs(previous.result.chi2 - current.result.chi2) < EPSILON*fabs(previous.result.chi2)) {
202 
203  const result_type result = current.result;
204 
205  reset();
206 
207  update(fit, __begin, __end, args...);
208 
209  try {
210  V.invert();
211  }
212  catch (const exception& error) {
213  V.reset();
214  }
215 
216  return result; // normal end
217  }
218 
219  if (lambda > LAMBDA_MIN) {
220  lambda /= LAMBDA_DOWN;
221  }
222  }
223  // store current values
224 
225  previous.value = value;
226  previous.error = error;
227  previous.result = current.result;
228 
229  } else {
230 
231  value = previous.value; // restore value
232 
233  lambda *= LAMBDA_UP;
234 
235  if (lambda > LAMBDA_MAX) {
236  break;
237  }
238 
239  reset();
240 
241  update(fit, __begin, __end, args...);
242  }
243 
244  DEBUG("Hesse matrix:" << endl << V << endl);
245 
246  // force definite positiveness
247 
248  for (size_t i = 0; i != N; ++i) {
249 
250  if (V(i,i) < PIVOT) {
251  V(i,i) = PIVOT;
252  }
253 
254  h[i] = 1.0 / sqrt(V(i,i));
255  }
256 
257  // normalisation
258 
259  for (size_t row = 0; row != N; ++row) {
260  for (size_t col = 0; col != row; ++col) {
261  V(row,col) *= h[row] * h[col];
262  V(col,row) = V(row,col);
263  }
264  }
265 
266  for (size_t i = 0; i != N; ++i) {
267  V(i,i) = 1.0 + lambda;
268  }
269 
270  // solve A x = b
271 
272  for (size_t col = 0; col != N; ++col) {
273  x[col] = h[col] * get(current.result.gradient, parameters[col]);
274  }
275 
276  try {
277  V.solve(x);
278  }
279  catch (const exception& error) {
280 
281  ERROR("JGandalf: " << error.what() << endl << V << endl);
282 
283  break;
284  }
285 
286  // update value and error
287 
288  for (size_t row = 0; row != N; ++row) {
289 
290  DEBUG("u[" << noshowpos << setw(3) << row << "] = " << showpos << FIXED(15,5) << get(value, parameters[row]));
291 
292  get(value, parameters[row]) -= h[row] * x[row];
293  get(error, parameters[row]) = h[row];
294 
295  DEBUG(" -> " << FIXED(15,5) << get(value, parameters[row]) << noshowpos << endl);
296  }
297  model(value);
298  }
299 
300  // abnormal end
301 
302  const result_type result = previous.result;
303 
304  value = previous.value; // restore value
305  error = previous.error; // restore error
306 
307  reset();
308 
309  update(fit, __begin, __end, args...);
310 
311  try {
312  V.invert();
313  }
314  catch (const exception& error) {
315  V.reset();
316  }
317 
318  return result;
319  }
320 
321 
322  static int MAXIMUM_ITERATIONS; //!< maximal number of iterations
323  static double EPSILON; //!< maximal distance to minimum
324  static double LAMBDA_MIN; //!< minimal value control parameter
325  static double LAMBDA_MAX; //!< maximal value control parameter
326  static double LAMBDA_UP; //!< multiplication factor control parameter
327  static double LAMBDA_DOWN; //!< multiplication factor control parameter
328  static double PIVOT; //!< minimal value diagonal element of Hesse matrix
329 
331  int numberOfIterations; //!< number of iterations
332  double lambda; //!< control parameter
333  JModel_t value; //!< value
334  JModel_t error; //!< error
335  JMATH::JMatrixNS V; //!< Hesse matrix
336 
337  private:
338  /**
339  * Reset current parameters.
340  */
341  void reset()
342  {
343  using namespace JPP;
344 
345  current.result.chi2 = 0.0;
346  current.result.gradient = zero;
347 
348  V.reset();
349  }
350 
351 
352  /**
353  * Recursive method to update current parameters.
354  *
355  * \param fit fit function
356  * \param __begin begin of data
357  * \param __end end of data
358  * \param args optional data
359  */
360  template<class JFunction_t, class T, class ...Args>
361  inline void update(const JFunction_t& fit, T __begin, T __end, Args ...args)
362  {
363  for (T i = __begin; i != __end; ++i) {
364 
365  const result_type& result = fit(value, *i);
366 
367  current.result.chi2 += result.chi2;
368  current.result.gradient += result.gradient;
369 
370  for (size_t row = 0; row != parameters.size(); ++row) {
371  for (size_t col = row; col != parameters.size(); ++col) {
372  V(row,col) += get(result.gradient, parameters[row]) * get(result.gradient, parameters[col]);
373  }
374  }
375  }
376 
377  update(fit, args...);
378  }
379 
380 
381  /**
382  * Termination method to update current parameters.
383  *
384  * \param fit fit function
385  */
386  template<class JFunction_t>
387  inline void update(const JFunction_t& fit)
388  {
389  for (size_t row = 0; row != parameters.size(); ++row) {
390  for (size_t col = 0; col != row; ++col) {
391  V(row,col) = V(col,row);
392  }
393  }
394  }
395 
396 
397  /**
398  * Read/write access to parameter value by data member.
399  *
400  * \param model model
401  * \param parameter parameter
402  * \return value
403  */
404  static inline double get(const JModel_t& model, double JModel_t::*parameter)
405  {
406  return model.*parameter;
407  }
408 
409 
410  /**
411  * Read/write access to parameter value by data member.
412  *
413  * \param model model
414  * \param parameter parameter
415  * \return value
416  */
417  static inline double& get(JModel_t& model, double JModel_t::*parameter)
418  {
419  return model.*parameter;
420  }
421 
422 
423  /**
424  * Read/write access to parameter value by index.
425  *
426  * \param model model
427  * \param index index
428  * \return value
429  */
430  static inline double get(const JModel_t& model, const size_t index)
431  {
432  return model[index];
433  }
434 
435 
436  /**
437  * Read/write access to parameter value by index.
438  *
439  * \param model model
440  * \param index index
441  * \return value
442  */
443  static inline double& get(JModel_t& model, const size_t index)
444  {
445  return model[index];
446  }
447 
448 
449  /**
450  * Read/write access to parameter value by index.
451  *
452  * \param model model
453  * \param index index
454  * \return value
455  */
456  static inline double get(const JModel_t& model, const int index)
457  {
458  return model[index];
459  }
460 
461 
462  /**
463  * Read/write access to parameter value by index.
464  *
465  * \param model model
466  * \param index index
467  * \return value
468  */
469  static inline double& get(JModel_t& model, const int index)
470  {
471  return model[index];
472  }
473 
474  std::vector<double> h; // normalisation vector
476 
477  struct {
478  result_type result; // result
479  } current;
480 
481  struct {
482  JModel_t value; // value
483  JModel_t error; // error
484  result_type result; // result
485  } previous;
486  };
487 
488 
489  /**
490  * maximal number of iterations.
491  */
492  template<class JModel_t>
494 
495 
496  /**
497  * maximal distance to minimum.
498  */
499  template<class JModel_t>
500  double JGandalf<JModel_t>::EPSILON = 1.0e-3;
501 
502 
503  /**
504  * minimal value control parameter
505  */
506  template<class JModel_t>
507  double JGandalf<JModel_t>::LAMBDA_MIN = 0.01;
508 
509 
510  /**
511  * maximal value control parameter
512  */
513  template<class JModel_t>
514  double JGandalf<JModel_t>::LAMBDA_MAX = 100.0;
515 
516 
517  /**
518  * multiplication factor control parameter
519  */
520  template<class JModel_t>
521  double JGandalf<JModel_t>::LAMBDA_UP = 10.0;
522 
523 
524  /**
525  * multiplication factor control parameter
526  */
527  template<class JModel_t>
528  double JGandalf<JModel_t>::LAMBDA_DOWN = 10.0;
529 
530 
531  /**
532  * minimal value diagonal element of matrix
533  */
534  template<class JModel_t>
536 }
537 
538 #endif
539 
static int debug
debug level (default is off).
Definition: JMessage.hh:45
double lambda
control parameter
Definition: JGandalf.hh:332
General exception.
Definition: JException.hh:24
Exceptions.
static double EPSILON
maximal distance to minimum
Definition: JGandalf.hh:323
JMATH::JVectorND x
Definition: JGandalf.hh:475
JFIT_LOCAL::JTypedef_t< JModel_t >::parameter_type parameter_type
Data type of fit parameter.
Definition: JGandalf.hh:95
JModel_t value
value
Definition: JGandalf.hh:333
static double PIVOT
minimal value diagonal element of Hesse matrix
Definition: JGandalf.hh:328
JMATH::JMatrixNS V
Hesse matrix.
Definition: JGandalf.hh:335
static const JZero zero
Function object to assign zero value.
Definition: JZero.hh:105
JMatrixND & reset()
Set matrix to the null matrix.
Definition: JMatrixND.hh:459
Auxiliary data structure for floating point format specification.
Definition: JManip.hh:446
std::vector< parameter_type > parameters
fit parameters
Definition: JGandalf.hh:330
void resize(const size_t size)
Resize matrix.
Definition: JMatrixND.hh:446
static double LAMBDA_MIN
minimal value control parameter
Definition: JGandalf.hh:324
static double LAMBDA_DOWN
multiplication factor control parameter
Definition: JGandalf.hh:327
Definition of zero value for any class.
void reset()
Reset current parameters.
Definition: JGandalf.hh:341
void update(const JFunction_t &fit)
Termination method to update current parameters.
Definition: JGandalf.hh:387
do set_variable OUTPUT_DIRECTORY $WORKDIR T
JModel_t gradient
partial derivatives of chi2
Definition: JGandalf.hh:136
#define ERROR(A)
Definition: JMessage.hh:66
result_type operator()(const JFunction_t &fit, T __begin, T __end, Args...args)
Multi-dimensional fit of multiple data sets.
Definition: JGandalf.hh:160
void update(const JFunction_t &fit, T __begin, T __end, Args...args)
Recursive method to update current parameters.
Definition: JGandalf.hh:361
N x N symmetric matrix.
Definition: JMatrixNS.hh:28
struct JFIT::JGandalf::@10 current
result_type result
Definition: JGandalf.hh:478
static auto parameter_type(U *) -> decltype(std::declval< typename U::parameter_type >())
General purpose messaging.
I/O manipulators.
static double LAMBDA_UP
multiplication factor control parameter
Definition: JGandalf.hh:326
void invert()
Invert matrix according LDU decomposition.
Definition: JMatrixNS.hh:75
Fit method based on the Levenberg-Marquardt method.
Definition: JGandalf.hh:84
then usage $script< input file >[option[primary[working directory]]] nWhere option can be N
Definition: JMuonPostfit.sh:40
Data structure for return value of fit function.
Definition: JGandalf.hh:101
void solve(JVectorND_t &u)
Get solution of equation A x = b.
Definition: JMatrixNS.hh:308
static const bool has_parameter_type
Definition: JGandalf.hh:39
result_type(const double chi2, const JModel_t &model)
Constructor.
Definition: JGandalf.hh:117
static int MAXIMUM_ITERATIONS
maximal number of iterations
Definition: JGandalf.hh:322
int numberOfIterations
number of iterations
Definition: JGandalf.hh:331
static double LAMBDA_MAX
maximal value control parameter
Definition: JGandalf.hh:325
JModel_t error
error
Definition: JGandalf.hh:334
result_type()
Default constructor.
Definition: JGandalf.hh:105
struct JFIT::JGandalf::@11 previous
const double epsilon
Definition: JQuadrature.cc:21
Nx1 matrix.
Definition: JVectorND.hh:21
#define DEBUG(A)
Message macros.
Definition: JMessage.hh:62
Auxiliary class for handling debug parameter within a class.
Definition: JMessage.hh:44
JGandalf()
Default constructor.
Definition: JGandalf.hh:143
std::vector< double > h
Definition: JGandalf.hh:474