Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
Minpack.hh
1 /*
2 This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4 Copyright (C) 2003-2009 (see file CONTACT for details)
5  Multimediale Systeme der Informationsverarbeitung
6  Institut fuer Informatik
7  Christian-Albrechts-Universitaet Kiel
8 
9 
10 BIAS is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14 
15 BIAS 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 Lesser General Public License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with BIAS; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24 
25 
26 #ifndef __Minpack_hh__
27 #define __Minpack_hh__
28 
29 #include <bias_config.h>
30 
31 #include <Base/Math/Matrix.hh>
32 #include <Base/Math/Vector.hh>
33 #include <MathAlgo/minpack/cminpack.h>
34 
35 #include "Lapack.hh"
36 
37 #define MINPACK_DEF_TOLERANCE 1e-7
38 #define LM_DEF_MAX_ITER -1
39 #define LM_DEF_EPSILON 1e-15
40 
41 #define LM_IMPROPER_INPUT -1
42 #define LM_OK 0
43 #define LM_TOO_MANY_IT 5
44 #define LM_SMALL_FTOL 6.
45 #define LM_SMALL_XTOL 7
46 #define LM_SMALL_GTOL 8
47 
48 namespace BIAS
49 {
50 /** @addtogroup g_mathalgo
51  \brief C++ Wrappers for important Lapack fortran77 functions
52  @{
53 */
54 
55  /** Solve a system f(x) = 0 of n non-linear equations with n unknowns using the
56  Powell hybrid method. The Jacobian matrix J(x) is calculated numerically by
57  forward-difference approximation. The error is assumed to be within the
58  range of machine precision.
59 
60  @param fun is the name of the user-supplied subroutine which calculates
61  the target function f at x and returns the values in array fvec.
62  fun must be declared e.g. in the user calling program and have the following
63  interface:
64 
65  int fun(void *p, int n, const double *x, double *fvec, int iflag)
66 
67  - p points to an object with additional data used for evaluating f(x)
68  - n is a positive integer input variable set to the number of residuals
69  and parameters (i.e. size of array x and fvec).
70  - x is the parameter array of length n. On input, x must contain an
71  initial estimate of the solution vector. On output, x contains the final
72  estimate of the solution vector x_res.
73  - fvec is an output array of length n which contains the function values
74  f(x) evaluated at the input parameter vector x.
75  - iflag should not be changed by fun unless the user wants to terminate
76  execution, in this case set iflag to a negative integer.
77 
78  @param Tolerance is a non-negative input variable. Termination occurs when
79  the algorithm estimates that the relative error between x and the solution x_res
80  is at most Tolerance.
81 
82  @return 0 if everything worked fine. If the user has terminated execution by
83  setting iflag to < 0 in fun, the value of iflag is returned. Otherwise, return is:
84  - return = -1: Improper input parameters
85  - return = 0: Algorithm estimated that the relative error between x and the
86  solution is within tolerance range.
87  - return = 2: Number of calls to fun has reached or exceeded 200*(n+1).
88  - return = 3: Tolerance is too small. No further improvement in the approximate
89  solution x is possible.
90  - return = 4: Iteration is not making good progress.
91 
92  @see minpack/hybrd1.f
93  @author woelk
94  */
95  BIASMathAlgo_EXPORT
96  long int Powell(minpack_func_nn fun, void *p,
97  Vector<double>& InitialGuess, Vector<double>& Result,
98  double Tolerance = MINPACK_DEF_TOLERANCE);
99 
100  /** Solve a system f(n) = 0 of n non-linear equations with n unknowns using the
101  Powell hybrid method. The Jacobian matrix J(x) is approximated numerically by
102  forward-difference approximation.
103 
104  See description of method Powell above for further parameter documentation.
105 
106  @param EpsilonFun Non-negative step width used to approximate the Jacobian numerically.
107 
108  @see minpack/hybrd.f
109  @author woelk
110  */
111  BIASMathAlgo_EXPORT
112  long int PowellExtended(minpack_func_nn fun, void *p,
113  Vector<double>& InitialGuess, Vector<double>& Result,
114  double EpsilonFun = LM_DEF_EPSILON,
115  double Tolerance = MINPACK_DEF_TOLERANCE);
116 
117  /** Solves an overdetermined system f(x) = 0 of m non-linear equations with n
118  parameters using the Levenberg-Marquardt algorithm. A least squares
119  solution is used. Jacobian J(x) of target function f(x) is given analytically.
120 
121  @param fun Defines the target function f(x) (resp. the Jacobian matrix J(x))
122  which is supposed to have the following interface:
123 
124  int fun(void *p, int m, int n, const double *x, double *fvec,
125  double *fjac, int ldfjac, int iflag)
126 
127  - p points to an object with additional data used for evaluating f(x)
128  - m is number of residuals (size of array fvec)
129  - n is number of parameters (size of array x)
130  - x points to an array of size n containing the input parameter values
131  - fvec points to an array of size m where the output residuals f(x)
132  are written to
133  - fjac points to an array of size m*n where the elements of the Jacobian
134  matrix J(x) are written to
135  - ldfjac specifies the leading dimension used to describe the Jacobian
136  matrix J(x) by the array fjac (if ldfjac = m then J(x) is written
137  column-wise into array fjac).
138  - iflag is a flag that specifies if the function should compute the
139  residuals f(x) and write them to fvec (when iflag == 1), or if the
140  Jacobian matrix J(x) should be computed and written to fjac (when
141  iflag == 2). The value of iflag should not be changed!
142 
143  @param m Number of residuals f(x) with m>=n
144  @param n Number of variables x with m>=n
145  @param InitialGuess Starting point x_0 for optimization (input, size must be n)
146  @param Result Solution x_res after optimization (output, size must be n)
147 
148  @param Tolerance Non-negative threshold used to determine convergence.
149 
150  @return 0 determines success in optimization, other return values are:
151  - return = -1: Improper input parameters
152  - return = 0: A termination condition became true.
153  - return = 5: Number of calls to fun has reached or exceeded maxfev iterations.
154  - return = 6: Tolerance ftol is too small. No further reduction in sum of
155  residual squares possible.
156  - return = 7: Tolerance xtol is too small. No further improvement in
157  approximate solution x is possible.
158  - return = 8: Tolerance gtol is too small. Vector fvec is orthogonal to the
159  columns of the Jacobian to machine precision.
160 
161  @see minpack/lmder1.f
162  @author woelk
163  */
164  BIASMathAlgo_EXPORT
165  long int LevenbergMarquardt(minpack_funcder_mn fun,
166  void *p,
167  long int m,
168  long int n,
169  Vector<double>& InitialGuess,
170  Vector<double>& Result,
171  double Tolerance = MINPACK_DEF_TOLERANCE);
172 
173  /** Solves an overdetermined system f(x) = 0 of m non-linear equations with n
174  parameters using the extended Levenberg-Marquardt algorithm. A least squares
175  solution is used. Jacobian J(x) of target function f(x) is given analytically.
176 
177  @param fun Defines the target function f(x) (resp. the Jacobian matrix J(x))
178  which is supposed to have the following interface:
179 
180  int fun(void *p, int m, int n, const double *x, double *fvec,
181  double *fjac, int ldfjac, int iflag)
182 
183  - p points to an object with additional data used for evaluating f(x)
184  - m is number of residuals (size of array fvec)
185  - n is number of parameters (size of array x)
186  - x points to an array of size n containing the input parameter values
187  - fvec points to an array of size m where the output residuals f(x)
188  are written to
189  - fjac points to an array of size m*n where the elements of the Jacobian
190  matrix J(x) are written to
191  - ldfjac specifies the leading dimension used to describe the Jacobian
192  matrix J(x) by the array fjac (if ldfjac = m then J(x) is written
193  column-wise into array fjac).
194  - iflag is a flag that specifies if the function should compute the
195  residuals f(x) and write them to fvec (when iflag == 1), or if the
196  Jacobian matrix J(x) should be computed and written to fjac (when
197  iflag == 2). The value of iflag should not be changed!
198 
199  @param m Number of residuals f(x) with m>=n
200  @param n Number of variables x with m>=n
201  @param InitialGuess Starting point x_0 for optimization (input, size must be n)
202  @param Result Solution x_res after optimization (output, size must be n)
203 
204  @param Tolerance Non-negative threshold used to determine convergence.
205 
206  @param MaxIter Max. number of evaluations of target function f(x). Note that
207  the complete numerical approximation of the Jacobian J(x) is always done as a
208  whole before this value is checked. Set MaxIter to -1 if you want to use the
209  default number of max. iterations from the fortran code (= 200*(n+1)).
210 
211  @return 0 determines success in optimization, for other return see description
212  for method LevenbergMarquardt above.
213 
214  @see minpack/lmder.f
215  @author woelk
216  */
217  BIASMathAlgo_EXPORT
218  long int LevenbergMarquardtExtended(minpack_funcder_mn fun,
219  void *p,
220  long int m,
221  long int n,
222  Vector<double>& InitialGuess,
223  Vector<double>& Result,
224  double Tolerance = MINPACK_DEF_TOLERANCE,
225  long int MaxIter = LM_DEF_MAX_ITER);
226 
227  /** Solves an overdetermined system f(x) = 0 of m non-linear equations with n
228  parameters using the Levenberg-Marquardt algorithm. A least squares
229  solution is used. The Jacobian J(x) of target function f(x) is calculated
230  numerically by forward-difference approximation and must not be provided
231  analytically.
232 
233  @param fun Defines the target function f(x) which is supposed to have the
234  following interface:
235 
236  int fun(void *p, int m, int n, const double *x, double *fvec, int iflag)
237 
238  - p points to an object with additional data used for evaluating f(x)
239  - m is number of residuals (size of array fvec)
240  - n is number of parameters (size of array x)
241  - x points to an array of size n containing the input parameter values
242  - fvec points to an array of size m where the output residuals f(x)
243  are written to
244  - iflag can be ignores here
245 
246  @param m Number of residuals f(x) with m>=n
247  @param n Number of variables x with m>=n
248  @param InitialGuess Starting point x_0 for optimization (input, size must be n)
249  @param Result Solution x_res after optimization (output, size must be n)
250 
251  @param Tolerance Non-negative threshold used to determine convergence.
252 
253  @param MaxIter This parameter is ignored and should be removed!
254 
255  @return 0 determines success in optimization, for other return see description
256  for method LevenbergMarquardt above.
257 
258  @see minpack/lmdif1.f
259  @author woelk
260  */
261  BIASMathAlgo_EXPORT
262  long int LevenbergMarquardt(minpack_func_mn fun,void *p,
263  long int M,
264  long int N,
265  Vector<double>& InitialGuess,
266  Vector<double>& Result,
267  double Tolerance = MINPACK_DEF_TOLERANCE,
268  long int MaxIter = LM_DEF_MAX_ITER);
269 
270  /** Solves an overdetermined system f(x) = 0 of m non-linear equations with n
271  parameters using the Levenberg-Marquardt algorithm. A least squares
272  solution is used. The Jacobian J(x) of target function f(x) is calculated
273  numerically by forward-difference approximation and must not be provided
274  analytically.
275 
276  @param fun Defines the target function f(x) which is supposed to have the
277  following interface:
278 
279  int fun(void *p, int m, int n, const double *x, double *fvec, int iflag)
280 
281  - p points to an object with additional data used for evaluating f(x)
282  - m is number of residuals (size of array fvec)
283  - n is number of parameters (size of array x)
284  - x points to an array of size n containing the input parameter values
285  - fvec points to an array of size m where the output residuals f(x)
286  are written to
287  - iflag can be ignores here
288 
289  @param m Number of residuals f(x) with m>=n
290  @param n Number of variables x with m>=n
291  @param InitialGuess Starting point x_0 for optimization (input, size must be n)
292  @param Result Solution x_res after optimization (output, size must be n)
293 
294  @param EpsilonFun Non-negative step width used to approximate the Jacobian numerically.
295 
296  @param Tolerance Non-negative threshold used to determine convergence.
297 
298  @param MaxIter Max. number of evaluations of target function f(x) (-1: default).
299 
300  @param ResultingJacobian Pointer to array of size m*n to write the Jacobian J(x_res)
301  evaluated numerically at the solution x_res. Pass NULL if it should be omitted.
302 
303  @param ipvt If Jacobian J(x_res) should be returned in ResultingJacobian,
304  you must specify here a pointer to an integer array of size n to write the
305  permutation matrix P to. Otherwise pass NULL.
306 
307  P is computed so that J(x_res)*P = Q*R, where J(x_res) is the final calculated
308  Jacobian, Q is an orthogonal matrix, and R is an upper triangular matrix with
309  diagonal elements of nonincreasing magnitude. Column j of P is column ipvt[j]
310  of the identity matrix.
311  Search minpack/minpack-documentation.txt for IPVT for a detailed description
312  of this parameter!
313 
314  @return 0 determines success in optimization, for other return see description
315  for method LevenbergMarquardt above.
316 
317  @see minpack/lmdif.f
318  @author woelk
319  */
320  BIASMathAlgo_EXPORT
321  long int LevenbergMarquardtExtended(minpack_func_mn fun,
322  void *p,
323  long int M,
324  long int N,
325  Vector<double>& InitialGuess,
326  Vector<double>& Result,
327  double EpsilonFun = LM_DEF_EPSILON,
328  double Tolerance = MINPACK_DEF_TOLERANCE,
329  long int MaxIter = LM_DEF_MAX_ITER,
330  double* ResultingJacobian = NULL,
331  int* ipvt = NULL,
332  double *SumOfSquaredErrors = NULL);
333 
334  /** @brief Compute covariance matrix from Levenberg-Marquardt resulting Jacobian matrix
335  J(x) and permutation matrix P (see description for method LevenbergMarquardtExtended
336  above or search in minpack/minpack-documentation.txt for IPVT).
337 
338  @param M Number of residuals (= rows of Jacobian)
339  @param N Number of parameters (= columns of Jacobian)
340  @param ResultingJacobian Pointer to array of size M*N containing the resulting
341  Jacobian J(x_res) computed from call to ExtendedLevenbergMarquardt.
342  @param ipvt Pointer to integer array of size N describing the permutation matrix
343  P computed from call to ExtendedLevenbergMarquardt (i.e. J(x_res)*P = Q*R).
344  @param SumOfSquaredErrors Sum of squared errors computed by ExtendedLevenbergMarquardt
345  @param Cov Output matrix to store covariance in
346 
347  @author woelk 06/2006
348  */
349  BIASMathAlgo_EXPORT
350  long int ComputeCovariance(long int M, long int N, double *ResultingJacobian,
351  int *ipvt, double &SumOfSquaredErrors,
352  Matrix<double>& Cov);
353 
354  /** @brief Convenience wrapper for ComputeCovariance.
355 
356  Compute covariance matrix from Levenberg-Marquardt resulting Jacobian matrix
357  J(x) and permutation matrix P (see description for method LevenbergMarquardtExtended
358  above or search in minpack/minpack-documentation.txt for IPVT).
359 
360  @param NumErrors Number of residuals (= rows of Jacobian)
361  @param NumParams Number of parameters (= columns of Jacobian)
362  @param Jac Matrix of size NumErrors x NumParams containing the resulting
363  Jacobian J(x_res) computed from ExtendedLevenbergMarquardt.
364  @param Permutation Integer vector of size NumParams describing the permutation matrix
365  P computed from ExtendedLevenbergMarquardt (i.e. J(x_res)*P = Q*R).
366  @param SumOfSquaredErrors Sum of squared errors computed by ExtendedLevenbergMarquardt
367  @param Cov Output matrix to store covariance int
368 
369  @author koeser
370  */
371  BIASMathAlgo_EXPORT
372  long int ComputeCovariance(const long int NumErrors, const long int NumParams,
373  const Matrix<double> &Jac,
374  const Vector<int>& Permutation,
375  const double &SumOfSquaredErrors,
376  Matrix<double>& Cov);
377 
378  /** @brief Convenience function to check correctness of user supplied Jacobians
379  J(x) needed by the analytical version of the Levenberg-Marquardt algorithm.
380 
381  First, the user defined Jacobian J(x) of f at x is calculated by calling fun
382  with iflag = 2. Then the minpack function chkder is used to evaluate the Jacobian.
383 
384  @warning CheckJacobian does not perform reliably if cancellation or
385  rounding errors cause a severe loss of significance in the evaluation
386  of a function!
387 
388  @param fun The target function fun is supposed to have the same interface
389  as described above in LevenbergMarquardt (version WITH Jacobian computation):
390 
391  int fun(void *p, int m, int n, const double *x, double *fvec,
392  double *fjac, int ldfjac, int iflag)
393 
394  @param p points to an object with additional data used for evaluating J(x)
395  @param NumErrors is the number m of residuals of f(x) (i.e. the number of rows of J(x))
396  @param x is a vector of size n that defines where the Jacobian J(x) is evaluated at
397 
398  @param error The function returns an error measure for each row of the Jacobian J(x)
399  in the output vector error of size NumErrors.
400 
401  On output, error contains measures of correctness of the respective gradients.
402  If there is no severe loss of significance, then if error[i] is 1.0, the i-th gradient
403  is correct, while if error[i] is 0.0, the i-th gradient is incorrect. For values
404  of error[i] between 0.0 and 1.0, the categorization is less certain.
405  In general, a value of error[i] > 0.5 indicates that the i-th gradient is probably
406  correct, while a value of error[i] < 0.5 indicates that the i-th gradient is probably
407  incorrect.
408 
409  @author woelk 07/2006
410  */
411  BIASMathAlgo_EXPORT
412  void CheckJacobian(minpack_funcder_mn fun, void *p,
413  const long int NumErrors, const Vector<double> &x,
414  Vector<double> &error);
415 
416  /** @brief Compute the Jacobian J(x) of function f at x.
417  @param fun specifies the target function f(x) to compute the Jacobian J(x) for
418  @param p points to an object with additional data used for evaluating J(x)
419  @param x is a vector of size n that defines where the Jacobian J(x) is evaluated at
420  @param Jac is an output matrix to which the Jacobian J(x) of function f evaluated
421  at x is written to
422  @note Wrapper for fdjac2
423  @see minpack/fdjac2.c
424  @author woelk 07/2007
425  */
426  BIASMathAlgo_EXPORT
427  long int ComputeJacobian(minpack_func_mn fun, void *p,
428  const int NumErrors, const Vector<double> &x,
429  Matrix<double>& Jac,
430  const double gradientEpsilon = LM_DEF_EPSILON);
431 
432  /** @brief Compute the QR decomposition of input matrix A using Householder
433  transformations without column pivoting.
434  @param[in] A is the input matrix which will be QR decomposed.
435  @param[out] Q is the resulting Q matrix which is orthogonal (A = Q*R)
436  @param[out] R is the resulting R matrix which is upper trapezoidal (A = Q*R)
437  @note Wrapper for qrfac
438  @see minpack/qrfac.c
439  */
440  BIASMathAlgo_EXPORT
441  void QRFrac(const Matrix<double> &A, Matrix<double>& Q, Matrix<double>& R);
442  // @}
443 } // namespace
444 
445 #endif // __Minpack_hh__
long int LevenbergMarquardtExtended(minpack_funcder_mn fun, void *p, long int m, long int n, Vector< double > &InitialGuess, Vector< double > &Result, double Tolerance, long int MaxIter)
Solves an overdetermined system f(x) = 0 of m non-linear equations with n parameters using the extend...
Definition: Minpack.cpp:131
long int ComputeCovariance(long int NumErrors, long int NumParams, double *Jac, int *Permutation, double &SumOfSquaredErrors, Matrix< double > &Cov)
Compute covariance matrix from Levenberg-Marquardt resulting Jacobian matrix J(x) and permutation mat...
Definition: Minpack.cpp:289
void QRFrac(const Matrix< double > &A, Matrix< double > &Q, Matrix< double > &R)
Compute the QR decomposition of input matrix A using Householder transformations without column pivot...
Definition: Minpack.cpp:473
void CheckJacobian(minpack_funcder_mn fun, void *p, const long int NumErrors, const Vector< double > &x, Vector< double > &error)
Convenience function to check correctness of user supplied Jacobians J(x) needed by the analytical ve...
Definition: Minpack.cpp:406
long int ComputeJacobian(minpack_func_mn fun, void *p, const int NumErrors, const Vector< double > &x, Matrix< double > &fjac, const double gradientEpsilon)
Compute the Jacobian J(x) of function f at x.
Definition: Minpack.cpp:443
long int LevenbergMarquardt(minpack_funcder_mn fun, void *p, long int m, long int n, Vector< double > &InitialGuess, Vector< double > &Result, double Tolerance)
Solves an overdetermined system f(x) = 0 of m non-linear equations with n parameters using the Levenb...
Definition: Minpack.cpp:97
long int Powell(minpack_func_nn fun, void *p, Vector< double > &InitialGuess, Vector< double > &Result, double Tolerance)
Solve a system f(x) = 0 of n non-linear equations with n unknowns using the Powell hybrid method...
Definition: Minpack.cpp:35
long int PowellExtended(minpack_func_nn fun, void *p, Vector< double > &InitialGuess, Vector< double > &Result, double EpsilonFun, double Tolerance)
Solve a system f(n) = 0 of n non-linear equations with n unknowns using the Powell hybrid method...
Definition: Minpack.cpp:56