Jpp  19.0.0
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  // normal end
204 
205  const result_type result = current.result;
206 
207  lambda = LAMBDA_MIN;
208 
209  reset();
210 
211  update(fit, __begin, __end, args...);
212 
213  try {
214  V.invert();
215  }
216  catch (const exception& error) {
217  V.reset();
218  }
219 
220  for (size_t i = 0; i != N; ++i) {
221  get(error, parameters[i]) = sqrt(V(i,i));
222  }
223 
224  return result;
225  }
226 
227  if (lambda > LAMBDA_MIN) {
228  lambda /= LAMBDA_DOWN;
229  }
230  }
231 
232  // store current values
233 
234  previous.value = value;
235  previous.result = current.result;
236 
237  } else {
238 
239  value = previous.value; // restore value
240 
241  lambda *= LAMBDA_UP;
242 
243  if (lambda > LAMBDA_MAX) {
244  break;
245  }
246 
247  reset();
248 
249  update(fit, __begin, __end, args...);
250  }
251 
252  DEBUG("Hesse matrix:" << endl << V << endl);
253 
254  // force definite positiveness
255 
256  for (size_t i = 0; i != N; ++i) {
257 
258  if (V(i,i) < PIVOT) {
259  V(i,i) = PIVOT;
260  }
261 
262  h[i] = 1.0 / sqrt(V(i,i));
263  }
264 
265  // normalisation
266 
267  for (size_t row = 0; row != N; ++row) {
268  for (size_t col = 0; col != row; ++col) {
269  V(row,col) *= h[row] * h[col];
270  V(col,row) = V(row,col);
271  }
272  }
273 
274  for (size_t i = 0; i != N; ++i) {
275  V(i,i) = 1.0 + lambda;
276  }
277 
278  // solve A x = b
279 
280  for (size_t col = 0; col != N; ++col) {
281  x[col] = h[col] * get(current.result.gradient, parameters[col]);
282  }
283 
284  try {
285  V.solve(x);
286  }
287  catch (const exception& error) {
288 
289  ERROR("JGandalf: " << error.what() << endl << V << endl);
290 
291  break;
292  }
293 
294  // update value
295 
296  for (size_t row = 0; row != N; ++row) {
297 
298  DEBUG("u[" << noshowpos << setw(3) << row << "] = " << showpos << FIXED(15,5) << get(value, parameters[row]));
299 
300  get(value, parameters[row]) -= h[row] * x[row];
301 
302  DEBUG(" -> " << FIXED(15,5) << get(value, parameters[row]) << noshowpos << endl);
303  }
304 
305  model(value);
306  }
307 
308  // abnormal end
309 
310  const result_type result = previous.result;
311 
312  value = previous.value; // restore value
313 
314  lambda = LAMBDA_MIN;
315 
316  reset();
317 
318  update(fit, __begin, __end, args...);
319 
320  try {
321  V.invert();
322  }
323  catch (const exception& error) {
324  V.reset();
325  }
326 
327  for (size_t i = 0; i != N; ++i) {
328  get(error, parameters[i]) = sqrt(V(i,i));
329  }
330 
331  return result;
332  }
333 
334 
335  static int MAXIMUM_ITERATIONS; //!< maximal number of iterations
336  static double EPSILON; //!< maximal distance to minimum
337  static double LAMBDA_MIN; //!< minimal value control parameter
338  static double LAMBDA_MAX; //!< maximal value control parameter
339  static double LAMBDA_UP; //!< multiplication factor control parameter
340  static double LAMBDA_DOWN; //!< multiplication factor control parameter
341  static double PIVOT; //!< minimal value diagonal element of Hesse matrix
342 
344  int numberOfIterations; //!< number of iterations
345  double lambda; //!< control parameter
346  JModel_t value; //!< value
347  JModel_t error; //!< error
348  JMATH::JMatrixNS V; //!< Hesse matrix
349 
350  private:
351  /**
352  * Reset current parameters.
353  */
354  void reset()
355  {
356  using namespace JPP;
357 
358  current.result.chi2 = 0.0;
359  current.result.gradient = zero;
360 
361  V.reset();
362  }
363 
364 
365  /**
366  * Recursive method to update current parameters.
367  *
368  * \param fit fit function
369  * \param __begin begin of data
370  * \param __end end of data
371  * \param args optional data
372  */
373  template<class JFunction_t, class T, class ...Args>
374  inline void update(const JFunction_t& fit, T __begin, T __end, Args ...args)
375  {
376  for (T i = __begin; i != __end; ++i) {
377 
378  const result_type& result = fit(value, *i);
379 
380  current.result.chi2 += result.chi2;
381  current.result.gradient += result.gradient;
382 
383  for (size_t row = 0; row != parameters.size(); ++row) {
384  for (size_t col = row; col != parameters.size(); ++col) {
385  V(row,col) += get(result.gradient, parameters[row]) * get(result.gradient, parameters[col]);
386  }
387  }
388  }
389 
390  update(fit, args...);
391  }
392 
393 
394  /**
395  * Termination method to update current parameters.
396  *
397  * \param fit fit function
398  */
399  template<class JFunction_t>
400  inline void update(const JFunction_t& fit)
401  {
402  for (size_t row = 0; row != parameters.size(); ++row) {
403  for (size_t col = 0; col != row; ++col) {
404  V(row,col) = V(col,row);
405  }
406  }
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(const JModel_t& model, double JModel_t::*parameter)
418  {
419  return model.*parameter;
420  }
421 
422 
423  /**
424  * Read/write access to parameter value by data member.
425  *
426  * \param model model
427  * \param parameter parameter
428  * \return value
429  */
430  static inline double& get(JModel_t& model, double JModel_t::*parameter)
431  {
432  return model.*parameter;
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(const 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(JModel_t& model, const size_t 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(const JModel_t& model, const int index)
470  {
471  return model[index];
472  }
473 
474 
475  /**
476  * Read/write access to parameter value by index.
477  *
478  * \param model model
479  * \param index index
480  * \return value
481  */
482  static inline double& get(JModel_t& model, const int index)
483  {
484  return model[index];
485  }
486 
487  std::vector<double> h; // normalisation vector
489 
490  struct {
491  result_type result; // result
492  } current;
493 
494  struct {
495  JModel_t value; // value
496  result_type result; // result
497  } previous;
498  };
499 
500 
501  /**
502  * maximal number of iterations.
503  */
504  template<class JModel_t>
506 
507 
508  /**
509  * maximal distance to minimum.
510  */
511  template<class JModel_t>
512  double JGandalf<JModel_t>::EPSILON = 1.0e-3;
513 
514 
515  /**
516  * minimal value control parameter
517  */
518  template<class JModel_t>
519  double JGandalf<JModel_t>::LAMBDA_MIN = 0.01;
520 
521 
522  /**
523  * maximal value control parameter
524  */
525  template<class JModel_t>
526  double JGandalf<JModel_t>::LAMBDA_MAX = 100.0;
527 
528 
529  /**
530  * multiplication factor control parameter
531  */
532  template<class JModel_t>
533  double JGandalf<JModel_t>::LAMBDA_UP = 10.0;
534 
535 
536  /**
537  * multiplication factor control parameter
538  */
539  template<class JModel_t>
540  double JGandalf<JModel_t>::LAMBDA_DOWN = 10.0;
541 
542 
543  /**
544  * minimal value diagonal element of matrix
545  */
546  template<class JModel_t>
548 }
549 
550 #endif
551 
static int debug
debug level (default is off).
Definition: JMessage.hh:45
double lambda
control parameter
Definition: JGandalf.hh:345
General exception.
Definition: JException.hh:24
Exceptions.
static double EPSILON
maximal distance to minimum
Definition: JGandalf.hh:336
JMATH::JVectorND x
Definition: JGandalf.hh:488
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:346
static double PIVOT
minimal value diagonal element of Hesse matrix
Definition: JGandalf.hh:341
JMATH::JMatrixNS V
Hesse matrix.
Definition: JGandalf.hh:348
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:343
void resize(const size_t size)
Resize matrix.
Definition: JMatrixND.hh:446
static double LAMBDA_MIN
minimal value control parameter
Definition: JGandalf.hh:337
static double LAMBDA_DOWN
multiplication factor control parameter
Definition: JGandalf.hh:340
Definition of zero value for any class.
void reset()
Reset current parameters.
Definition: JGandalf.hh:354
void update(const JFunction_t &fit)
Termination method to update current parameters.
Definition: JGandalf.hh:400
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:374
N x N symmetric matrix.
Definition: JMatrixNS.hh:28
struct JFIT::JGandalf::@10 current
result_type result
Definition: JGandalf.hh:491
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:339
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:335
int numberOfIterations
number of iterations
Definition: JGandalf.hh:344
static double LAMBDA_MAX
maximal value control parameter
Definition: JGandalf.hh:338
JModel_t error
error
Definition: JGandalf.hh:347
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:487