View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math3.optim.nonlinear.vector.jacobian;
18  
19  import java.util.Arrays;
20  import org.apache.commons.math3.exception.ConvergenceException;
21  import org.apache.commons.math3.exception.MathUnsupportedOperationException;
22  import org.apache.commons.math3.exception.util.LocalizedFormats;
23  import org.apache.commons.math3.optim.PointVectorValuePair;
24  import org.apache.commons.math3.optim.ConvergenceChecker;
25  import org.apache.commons.math3.linear.RealMatrix;
26  import org.apache.commons.math3.util.Precision;
27  import org.apache.commons.math3.util.FastMath;
28  
29  
30  /**
31   * This class solves a least-squares problem using the Levenberg-Marquardt
32   * algorithm.
33   * <br/>
34   * Constraints are not supported: the call to
35   * {@link #optimize(OptimizationData[]) optimize} will throw
36   * {@link MathUnsupportedOperationException} if bounds are passed to it.
37   *
38   * <p>This implementation <em>should</em> work even for over-determined systems
39   * (i.e. systems having more point than equations). Over-determined systems
40   * are solved by ignoring the point which have the smallest impact according
41   * to their jacobian column norm. Only the rank of the matrix and some loop bounds
42   * are changed to implement this.</p>
43   *
44   * <p>The resolution engine is a simple translation of the MINPACK <a
45   * href="http://www.netlib.org/minpack/lmder.f">lmder</a> routine with minor
46   * changes. The changes include the over-determined resolution, the use of
47   * inherited convergence checker and the Q.R. decomposition which has been
48   * rewritten following the algorithm described in the
49   * P. Lascaux and R. Theodor book <i>Analyse num&eacute;rique matricielle
50   * appliqu&eacute;e &agrave; l'art de l'ing&eacute;nieur</i>, Masson 1986.</p>
51   * <p>The authors of the original fortran version are:
52   * <ul>
53   * <li>Argonne National Laboratory. MINPACK project. March 1980</li>
54   * <li>Burton S. Garbow</li>
55   * <li>Kenneth E. Hillstrom</li>
56   * <li>Jorge J. More</li>
57   * </ul>
58   * The redistribution policy for MINPACK is available <a
59   * href="http://www.netlib.org/minpack/disclaimer">here</a>, for convenience, it
60   * is reproduced below.</p>
61   *
62   * <table border="0" width="80%" cellpadding="10" align="center" bgcolor="#E0E0E0">
63   * <tr><td>
64   *    Minpack Copyright Notice (1999) University of Chicago.
65   *    All rights reserved
66   * </td></tr>
67   * <tr><td>
68   * Redistribution and use in source and binary forms, with or without
69   * modification, are permitted provided that the following conditions
70   * are met:
71   * <ol>
72   *  <li>Redistributions of source code must retain the above copyright
73   *      notice, this list of conditions and the following disclaimer.</li>
74   * <li>Redistributions in binary form must reproduce the above
75   *     copyright notice, this list of conditions and the following
76   *     disclaimer in the documentation and/or other materials provided
77   *     with the distribution.</li>
78   * <li>The end-user documentation included with the redistribution, if any,
79   *     must include the following acknowledgment:
80   *     <code>This product includes software developed by the University of
81   *           Chicago, as Operator of Argonne National Laboratory.</code>
82   *     Alternately, this acknowledgment may appear in the software itself,
83   *     if and wherever such third-party acknowledgments normally appear.</li>
84   * <li><strong>WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS"
85   *     WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE
86   *     UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND
87   *     THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR
88   *     IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES
89   *     OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE
90   *     OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY
91   *     OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR
92   *     USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF
93   *     THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4)
94   *     DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION
95   *     UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL
96   *     BE CORRECTED.</strong></li>
97   * <li><strong>LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT
98   *     HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF
99   *     ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT,
100  *     INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF
101  *     ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF
102  *     PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER
103  *     SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT
104  *     (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE,
105  *     EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE
106  *     POSSIBILITY OF SUCH LOSS OR DAMAGES.</strong></li>
107  * <ol></td></tr>
108  * </table>
109  *
110  * @version $Id: LevenbergMarquardtOptimizer.java 1515242 2013-08-18 23:27:29Z erans $
111  * @since 2.0
112  * @deprecated All classes and interfaces in this package are deprecated.
113  * The optimizers that were provided here were moved to the
114  * {@link org.apache.commons.math3.fitting.leastsquares} package
115  * (cf. MATH-1008).
116  */
117 @Deprecated
118 public class LevenbergMarquardtOptimizer
119     extends AbstractLeastSquaresOptimizer {
120     /** Twice the "epsilon machine". */
121     private static final double TWO_EPS = 2 * Precision.EPSILON;
122     /** Number of solved point. */
123     private int solvedCols;
124     /** Diagonal elements of the R matrix in the Q.R. decomposition. */
125     private double[] diagR;
126     /** Norms of the columns of the jacobian matrix. */
127     private double[] jacNorm;
128     /** Coefficients of the Householder transforms vectors. */
129     private double[] beta;
130     /** Columns permutation array. */
131     private int[] permutation;
132     /** Rank of the jacobian matrix. */
133     private int rank;
134     /** Levenberg-Marquardt parameter. */
135     private double lmPar;
136     /** Parameters evolution direction associated with lmPar. */
137     private double[] lmDir;
138     /** Positive input variable used in determining the initial step bound. */
139     private final double initialStepBoundFactor;
140     /** Desired relative error in the sum of squares. */
141     private final double costRelativeTolerance;
142     /**  Desired relative error in the approximate solution parameters. */
143     private final double parRelativeTolerance;
144     /** Desired max cosine on the orthogonality between the function vector
145      * and the columns of the jacobian. */
146     private final double orthoTolerance;
147     /** Threshold for QR ranking. */
148     private final double qrRankingThreshold;
149     /** Weighted residuals. */
150     private double[] weightedResidual;
151     /** Weighted Jacobian. */
152     private double[][] weightedJacobian;
153 
154     /**
155      * Build an optimizer for least squares problems with default values
156      * for all the tuning parameters (see the {@link
157      * #LevenbergMarquardtOptimizer(double,double,double,double,double)
158      * other contructor}.
159      * The default values for the algorithm settings are:
160      * <ul>
161      *  <li>Initial step bound factor: 100</li>
162      *  <li>Cost relative tolerance: 1e-10</li>
163      *  <li>Parameters relative tolerance: 1e-10</li>
164      *  <li>Orthogonality tolerance: 1e-10</li>
165      *  <li>QR ranking threshold: {@link Precision#SAFE_MIN}</li>
166      * </ul>
167      */
168     public LevenbergMarquardtOptimizer() {
169         this(100, 1e-10, 1e-10, 1e-10, Precision.SAFE_MIN);
170     }
171 
172     /**
173      * Constructor that allows the specification of a custom convergence
174      * checker.
175      * Note that all the usual convergence checks will be <em>disabled</em>.
176      * The default values for the algorithm settings are:
177      * <ul>
178      *  <li>Initial step bound factor: 100</li>
179      *  <li>Cost relative tolerance: 1e-10</li>
180      *  <li>Parameters relative tolerance: 1e-10</li>
181      *  <li>Orthogonality tolerance: 1e-10</li>
182      *  <li>QR ranking threshold: {@link Precision#SAFE_MIN}</li>
183      * </ul>
184      *
185      * @param checker Convergence checker.
186      */
187     public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker) {
188         this(100, checker, 1e-10, 1e-10, 1e-10, Precision.SAFE_MIN);
189     }
190 
191     /**
192      * Constructor that allows the specification of a custom convergence
193      * checker, in addition to the standard ones.
194      *
195      * @param initialStepBoundFactor Positive input variable used in
196      * determining the initial step bound. This bound is set to the
197      * product of initialStepBoundFactor and the euclidean norm of
198      * {@code diag * x} if non-zero, or else to {@code initialStepBoundFactor}
199      * itself. In most cases factor should lie in the interval
200      * {@code (0.1, 100.0)}. {@code 100} is a generally recommended value.
201      * @param checker Convergence checker.
202      * @param costRelativeTolerance Desired relative error in the sum of
203      * squares.
204      * @param parRelativeTolerance Desired relative error in the approximate
205      * solution parameters.
206      * @param orthoTolerance Desired max cosine on the orthogonality between
207      * the function vector and the columns of the Jacobian.
208      * @param threshold Desired threshold for QR ranking. If the squared norm
209      * of a column vector is smaller or equal to this threshold during QR
210      * decomposition, it is considered to be a zero vector and hence the rank
211      * of the matrix is reduced.
212      */
213     public LevenbergMarquardtOptimizer(double initialStepBoundFactor,
214                                        ConvergenceChecker<PointVectorValuePair> checker,
215                                        double costRelativeTolerance,
216                                        double parRelativeTolerance,
217                                        double orthoTolerance,
218                                        double threshold) {
219         super(checker);
220         this.initialStepBoundFactor = initialStepBoundFactor;
221         this.costRelativeTolerance = costRelativeTolerance;
222         this.parRelativeTolerance = parRelativeTolerance;
223         this.orthoTolerance = orthoTolerance;
224         this.qrRankingThreshold = threshold;
225     }
226 
227     /**
228      * Build an optimizer for least squares problems with default values
229      * for some of the tuning parameters (see the {@link
230      * #LevenbergMarquardtOptimizer(double,double,double,double,double)
231      * other contructor}.
232      * The default values for the algorithm settings are:
233      * <ul>
234      *  <li>Initial step bound factor}: 100</li>
235      *  <li>QR ranking threshold}: {@link Precision#SAFE_MIN}</li>
236      * </ul>
237      *
238      * @param costRelativeTolerance Desired relative error in the sum of
239      * squares.
240      * @param parRelativeTolerance Desired relative error in the approximate
241      * solution parameters.
242      * @param orthoTolerance Desired max cosine on the orthogonality between
243      * the function vector and the columns of the Jacobian.
244      */
245     public LevenbergMarquardtOptimizer(double costRelativeTolerance,
246                                        double parRelativeTolerance,
247                                        double orthoTolerance) {
248         this(100,
249              costRelativeTolerance, parRelativeTolerance, orthoTolerance,
250              Precision.SAFE_MIN);
251     }
252 
253     /**
254      * The arguments control the behaviour of the default convergence checking
255      * procedure.
256      * Additional criteria can defined through the setting of a {@link
257      * ConvergenceChecker}.
258      *
259      * @param initialStepBoundFactor Positive input variable used in
260      * determining the initial step bound. This bound is set to the
261      * product of initialStepBoundFactor and the euclidean norm of
262      * {@code diag * x} if non-zero, or else to {@code initialStepBoundFactor}
263      * itself. In most cases factor should lie in the interval
264      * {@code (0.1, 100.0)}. {@code 100} is a generally recommended value.
265      * @param costRelativeTolerance Desired relative error in the sum of
266      * squares.
267      * @param parRelativeTolerance Desired relative error in the approximate
268      * solution parameters.
269      * @param orthoTolerance Desired max cosine on the orthogonality between
270      * the function vector and the columns of the Jacobian.
271      * @param threshold Desired threshold for QR ranking. If the squared norm
272      * of a column vector is smaller or equal to this threshold during QR
273      * decomposition, it is considered to be a zero vector and hence the rank
274      * of the matrix is reduced.
275      */
276     public LevenbergMarquardtOptimizer(double initialStepBoundFactor,
277                                        double costRelativeTolerance,
278                                        double parRelativeTolerance,
279                                        double orthoTolerance,
280                                        double threshold) {
281         super(null); // No custom convergence criterion.
282         this.initialStepBoundFactor = initialStepBoundFactor;
283         this.costRelativeTolerance = costRelativeTolerance;
284         this.parRelativeTolerance = parRelativeTolerance;
285         this.orthoTolerance = orthoTolerance;
286         this.qrRankingThreshold = threshold;
287     }
288 
289     /** {@inheritDoc} */
290     @Override
291     protected PointVectorValuePair doOptimize() {
292         checkParameters();
293 
294         final int nR = getTarget().length; // Number of observed data.
295         final double[] currentPoint = getStartPoint();
296         final int nC = currentPoint.length; // Number of parameters.
297 
298         // arrays shared with the other private methods
299         solvedCols  = FastMath.min(nR, nC);
300         diagR       = new double[nC];
301         jacNorm     = new double[nC];
302         beta        = new double[nC];
303         permutation = new int[nC];
304         lmDir       = new double[nC];
305 
306         // local point
307         double   delta   = 0;
308         double   xNorm   = 0;
309         double[] diag    = new double[nC];
310         double[] oldX    = new double[nC];
311         double[] oldRes  = new double[nR];
312         double[] oldObj  = new double[nR];
313         double[] qtf     = new double[nR];
314         double[] work1   = new double[nC];
315         double[] work2   = new double[nC];
316         double[] work3   = new double[nC];
317 
318         final RealMatrix weightMatrixSqrt = getWeightSquareRoot();
319 
320         // Evaluate the function at the starting point and calculate its norm.
321         double[] currentObjective = computeObjectiveValue(currentPoint);
322         double[] currentResiduals = computeResiduals(currentObjective);
323         PointVectorValuePair current = new PointVectorValuePair(currentPoint, currentObjective);
324         double currentCost = computeCost(currentResiduals);
325 
326         // Outer loop.
327         lmPar = 0;
328         boolean firstIteration = true;
329         final ConvergenceChecker<PointVectorValuePair> checker = getConvergenceChecker();
330         while (true) {
331             incrementIterationCount();
332 
333             final PointVectorValuePair previous = current;
334 
335             // QR decomposition of the jacobian matrix
336             qrDecomposition(computeWeightedJacobian(currentPoint));
337 
338             weightedResidual = weightMatrixSqrt.operate(currentResiduals);
339             for (int i = 0; i < nR; i++) {
340                 qtf[i] = weightedResidual[i];
341             }
342 
343             // compute Qt.res
344             qTy(qtf);
345 
346             // now we don't need Q anymore,
347             // so let jacobian contain the R matrix with its diagonal elements
348             for (int k = 0; k < solvedCols; ++k) {
349                 int pk = permutation[k];
350                 weightedJacobian[k][pk] = diagR[pk];
351             }
352 
353             if (firstIteration) {
354                 // scale the point according to the norms of the columns
355                 // of the initial jacobian
356                 xNorm = 0;
357                 for (int k = 0; k < nC; ++k) {
358                     double dk = jacNorm[k];
359                     if (dk == 0) {
360                         dk = 1.0;
361                     }
362                     double xk = dk * currentPoint[k];
363                     xNorm  += xk * xk;
364                     diag[k] = dk;
365                 }
366                 xNorm = FastMath.sqrt(xNorm);
367 
368                 // initialize the step bound delta
369                 delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);
370             }
371 
372             // check orthogonality between function vector and jacobian columns
373             double maxCosine = 0;
374             if (currentCost != 0) {
375                 for (int j = 0; j < solvedCols; ++j) {
376                     int    pj = permutation[j];
377                     double s  = jacNorm[pj];
378                     if (s != 0) {
379                         double sum = 0;
380                         for (int i = 0; i <= j; ++i) {
381                             sum += weightedJacobian[i][pj] * qtf[i];
382                         }
383                         maxCosine = FastMath.max(maxCosine, FastMath.abs(sum) / (s * currentCost));
384                     }
385                 }
386             }
387             if (maxCosine <= orthoTolerance) {
388                 // Convergence has been reached.
389                 setCost(currentCost);
390                 return current;
391             }
392 
393             // rescale if necessary
394             for (int j = 0; j < nC; ++j) {
395                 diag[j] = FastMath.max(diag[j], jacNorm[j]);
396             }
397 
398             // Inner loop.
399             for (double ratio = 0; ratio < 1.0e-4;) {
400 
401                 // save the state
402                 for (int j = 0; j < solvedCols; ++j) {
403                     int pj = permutation[j];
404                     oldX[pj] = currentPoint[pj];
405                 }
406                 final double previousCost = currentCost;
407                 double[] tmpVec = weightedResidual;
408                 weightedResidual = oldRes;
409                 oldRes    = tmpVec;
410                 tmpVec    = currentObjective;
411                 currentObjective = oldObj;
412                 oldObj    = tmpVec;
413 
414                 // determine the Levenberg-Marquardt parameter
415                 determineLMParameter(qtf, delta, diag, work1, work2, work3);
416 
417                 // compute the new point and the norm of the evolution direction
418                 double lmNorm = 0;
419                 for (int j = 0; j < solvedCols; ++j) {
420                     int pj = permutation[j];
421                     lmDir[pj] = -lmDir[pj];
422                     currentPoint[pj] = oldX[pj] + lmDir[pj];
423                     double s = diag[pj] * lmDir[pj];
424                     lmNorm  += s * s;
425                 }
426                 lmNorm = FastMath.sqrt(lmNorm);
427                 // on the first iteration, adjust the initial step bound.
428                 if (firstIteration) {
429                     delta = FastMath.min(delta, lmNorm);
430                 }
431 
432                 // Evaluate the function at x + p and calculate its norm.
433                 currentObjective = computeObjectiveValue(currentPoint);
434                 currentResiduals = computeResiduals(currentObjective);
435                 current = new PointVectorValuePair(currentPoint, currentObjective);
436                 currentCost = computeCost(currentResiduals);
437 
438                 // compute the scaled actual reduction
439                 double actRed = -1.0;
440                 if (0.1 * currentCost < previousCost) {
441                     double r = currentCost / previousCost;
442                     actRed = 1.0 - r * r;
443                 }
444 
445                 // compute the scaled predicted reduction
446                 // and the scaled directional derivative
447                 for (int j = 0; j < solvedCols; ++j) {
448                     int pj = permutation[j];
449                     double dirJ = lmDir[pj];
450                     work1[j] = 0;
451                     for (int i = 0; i <= j; ++i) {
452                         work1[i] += weightedJacobian[i][pj] * dirJ;
453                     }
454                 }
455                 double coeff1 = 0;
456                 for (int j = 0; j < solvedCols; ++j) {
457                     coeff1 += work1[j] * work1[j];
458                 }
459                 double pc2 = previousCost * previousCost;
460                 coeff1 = coeff1 / pc2;
461                 double coeff2 = lmPar * lmNorm * lmNorm / pc2;
462                 double preRed = coeff1 + 2 * coeff2;
463                 double dirDer = -(coeff1 + coeff2);
464 
465                 // ratio of the actual to the predicted reduction
466                 ratio = (preRed == 0) ? 0 : (actRed / preRed);
467 
468                 // update the step bound
469                 if (ratio <= 0.25) {
470                     double tmp =
471                         (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;
472                         if ((0.1 * currentCost >= previousCost) || (tmp < 0.1)) {
473                             tmp = 0.1;
474                         }
475                         delta = tmp * FastMath.min(delta, 10.0 * lmNorm);
476                         lmPar /= tmp;
477                 } else if ((lmPar == 0) || (ratio >= 0.75)) {
478                     delta = 2 * lmNorm;
479                     lmPar *= 0.5;
480                 }
481 
482                 // test for successful iteration.
483                 if (ratio >= 1.0e-4) {
484                     // successful iteration, update the norm
485                     firstIteration = false;
486                     xNorm = 0;
487                     for (int k = 0; k < nC; ++k) {
488                         double xK = diag[k] * currentPoint[k];
489                         xNorm += xK * xK;
490                     }
491                     xNorm = FastMath.sqrt(xNorm);
492 
493                     // tests for convergence.
494                     if (checker != null && checker.converged(getIterations(), previous, current)) {
495                         setCost(currentCost);
496                         return current;
497                     }
498                 } else {
499                     // failed iteration, reset the previous values
500                     currentCost = previousCost;
501                     for (int j = 0; j < solvedCols; ++j) {
502                         int pj = permutation[j];
503                         currentPoint[pj] = oldX[pj];
504                     }
505                     tmpVec    = weightedResidual;
506                     weightedResidual = oldRes;
507                     oldRes    = tmpVec;
508                     tmpVec    = currentObjective;
509                     currentObjective = oldObj;
510                     oldObj    = tmpVec;
511                     // Reset "current" to previous values.
512                     current = new PointVectorValuePair(currentPoint, currentObjective);
513                 }
514 
515                 // Default convergence criteria.
516                 if ((FastMath.abs(actRed) <= costRelativeTolerance &&
517                      preRed <= costRelativeTolerance &&
518                      ratio <= 2.0) ||
519                     delta <= parRelativeTolerance * xNorm) {
520                     setCost(currentCost);
521                     return current;
522                 }
523 
524                 // tests for termination and stringent tolerances
525                 if (FastMath.abs(actRed) <= TWO_EPS &&
526                     preRed <= TWO_EPS &&
527                     ratio <= 2.0) {
528                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,
529                                                    costRelativeTolerance);
530                 } else if (delta <= TWO_EPS * xNorm) {
531                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,
532                                                    parRelativeTolerance);
533                 } else if (maxCosine <= TWO_EPS) {
534                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,
535                                                    orthoTolerance);
536                 }
537             }
538         }
539     }
540 
541     /**
542      * Determine the Levenberg-Marquardt parameter.
543      * <p>This implementation is a translation in Java of the MINPACK
544      * <a href="http://www.netlib.org/minpack/lmpar.f">lmpar</a>
545      * routine.</p>
546      * <p>This method sets the lmPar and lmDir attributes.</p>
547      * <p>The authors of the original fortran function are:</p>
548      * <ul>
549      *   <li>Argonne National Laboratory. MINPACK project. March 1980</li>
550      *   <li>Burton  S. Garbow</li>
551      *   <li>Kenneth E. Hillstrom</li>
552      *   <li>Jorge   J. More</li>
553      * </ul>
554      * <p>Luc Maisonobe did the Java translation.</p>
555      *
556      * @param qy array containing qTy
557      * @param delta upper bound on the euclidean norm of diagR * lmDir
558      * @param diag diagonal matrix
559      * @param work1 work array
560      * @param work2 work array
561      * @param work3 work array
562      */
563     private void determineLMParameter(double[] qy, double delta, double[] diag,
564                                       double[] work1, double[] work2, double[] work3) {
565         final int nC = weightedJacobian[0].length;
566 
567         // compute and store in x the gauss-newton direction, if the
568         // jacobian is rank-deficient, obtain a least squares solution
569         for (int j = 0; j < rank; ++j) {
570             lmDir[permutation[j]] = qy[j];
571         }
572         for (int j = rank; j < nC; ++j) {
573             lmDir[permutation[j]] = 0;
574         }
575         for (int k = rank - 1; k >= 0; --k) {
576             int pk = permutation[k];
577             double ypk = lmDir[pk] / diagR[pk];
578             for (int i = 0; i < k; ++i) {
579                 lmDir[permutation[i]] -= ypk * weightedJacobian[i][pk];
580             }
581             lmDir[pk] = ypk;
582         }
583 
584         // evaluate the function at the origin, and test
585         // for acceptance of the Gauss-Newton direction
586         double dxNorm = 0;
587         for (int j = 0; j < solvedCols; ++j) {
588             int pj = permutation[j];
589             double s = diag[pj] * lmDir[pj];
590             work1[pj] = s;
591             dxNorm += s * s;
592         }
593         dxNorm = FastMath.sqrt(dxNorm);
594         double fp = dxNorm - delta;
595         if (fp <= 0.1 * delta) {
596             lmPar = 0;
597             return;
598         }
599 
600         // if the jacobian is not rank deficient, the Newton step provides
601         // a lower bound, parl, for the zero of the function,
602         // otherwise set this bound to zero
603         double sum2;
604         double parl = 0;
605         if (rank == solvedCols) {
606             for (int j = 0; j < solvedCols; ++j) {
607                 int pj = permutation[j];
608                 work1[pj] *= diag[pj] / dxNorm;
609             }
610             sum2 = 0;
611             for (int j = 0; j < solvedCols; ++j) {
612                 int pj = permutation[j];
613                 double sum = 0;
614                 for (int i = 0; i < j; ++i) {
615                     sum += weightedJacobian[i][pj] * work1[permutation[i]];
616                 }
617                 double s = (work1[pj] - sum) / diagR[pj];
618                 work1[pj] = s;
619                 sum2 += s * s;
620             }
621             parl = fp / (delta * sum2);
622         }
623 
624         // calculate an upper bound, paru, for the zero of the function
625         sum2 = 0;
626         for (int j = 0; j < solvedCols; ++j) {
627             int pj = permutation[j];
628             double sum = 0;
629             for (int i = 0; i <= j; ++i) {
630                 sum += weightedJacobian[i][pj] * qy[i];
631             }
632             sum /= diag[pj];
633             sum2 += sum * sum;
634         }
635         double gNorm = FastMath.sqrt(sum2);
636         double paru = gNorm / delta;
637         if (paru == 0) {
638             paru = Precision.SAFE_MIN / FastMath.min(delta, 0.1);
639         }
640 
641         // if the input par lies outside of the interval (parl,paru),
642         // set par to the closer endpoint
643         lmPar = FastMath.min(paru, FastMath.max(lmPar, parl));
644         if (lmPar == 0) {
645             lmPar = gNorm / dxNorm;
646         }
647 
648         for (int countdown = 10; countdown >= 0; --countdown) {
649 
650             // evaluate the function at the current value of lmPar
651             if (lmPar == 0) {
652                 lmPar = FastMath.max(Precision.SAFE_MIN, 0.001 * paru);
653             }
654             double sPar = FastMath.sqrt(lmPar);
655             for (int j = 0; j < solvedCols; ++j) {
656                 int pj = permutation[j];
657                 work1[pj] = sPar * diag[pj];
658             }
659             determineLMDirection(qy, work1, work2, work3);
660 
661             dxNorm = 0;
662             for (int j = 0; j < solvedCols; ++j) {
663                 int pj = permutation[j];
664                 double s = diag[pj] * lmDir[pj];
665                 work3[pj] = s;
666                 dxNorm += s * s;
667             }
668             dxNorm = FastMath.sqrt(dxNorm);
669             double previousFP = fp;
670             fp = dxNorm - delta;
671 
672             // if the function is small enough, accept the current value
673             // of lmPar, also test for the exceptional cases where parl is zero
674             if ((FastMath.abs(fp) <= 0.1 * delta) ||
675                     ((parl == 0) && (fp <= previousFP) && (previousFP < 0))) {
676                 return;
677             }
678 
679             // compute the Newton correction
680             for (int j = 0; j < solvedCols; ++j) {
681                 int pj = permutation[j];
682                 work1[pj] = work3[pj] * diag[pj] / dxNorm;
683             }
684             for (int j = 0; j < solvedCols; ++j) {
685                 int pj = permutation[j];
686                 work1[pj] /= work2[j];
687                 double tmp = work1[pj];
688                 for (int i = j + 1; i < solvedCols; ++i) {
689                     work1[permutation[i]] -= weightedJacobian[i][pj] * tmp;
690                 }
691             }
692             sum2 = 0;
693             for (int j = 0; j < solvedCols; ++j) {
694                 double s = work1[permutation[j]];
695                 sum2 += s * s;
696             }
697             double correction = fp / (delta * sum2);
698 
699             // depending on the sign of the function, update parl or paru.
700             if (fp > 0) {
701                 parl = FastMath.max(parl, lmPar);
702             } else if (fp < 0) {
703                 paru = FastMath.min(paru, lmPar);
704             }
705 
706             // compute an improved estimate for lmPar
707             lmPar = FastMath.max(parl, lmPar + correction);
708 
709         }
710     }
711 
712     /**
713      * Solve a*x = b and d*x = 0 in the least squares sense.
714      * <p>This implementation is a translation in Java of the MINPACK
715      * <a href="http://www.netlib.org/minpack/qrsolv.f">qrsolv</a>
716      * routine.</p>
717      * <p>This method sets the lmDir and lmDiag attributes.</p>
718      * <p>The authors of the original fortran function are:</p>
719      * <ul>
720      *   <li>Argonne National Laboratory. MINPACK project. March 1980</li>
721      *   <li>Burton  S. Garbow</li>
722      *   <li>Kenneth E. Hillstrom</li>
723      *   <li>Jorge   J. More</li>
724      * </ul>
725      * <p>Luc Maisonobe did the Java translation.</p>
726      *
727      * @param qy array containing qTy
728      * @param diag diagonal matrix
729      * @param lmDiag diagonal elements associated with lmDir
730      * @param work work array
731      */
732     private void determineLMDirection(double[] qy, double[] diag,
733                                       double[] lmDiag, double[] work) {
734 
735         // copy R and Qty to preserve input and initialize s
736         //  in particular, save the diagonal elements of R in lmDir
737         for (int j = 0; j < solvedCols; ++j) {
738             int pj = permutation[j];
739             for (int i = j + 1; i < solvedCols; ++i) {
740                 weightedJacobian[i][pj] = weightedJacobian[j][permutation[i]];
741             }
742             lmDir[j] = diagR[pj];
743             work[j]  = qy[j];
744         }
745 
746         // eliminate the diagonal matrix d using a Givens rotation
747         for (int j = 0; j < solvedCols; ++j) {
748 
749             // prepare the row of d to be eliminated, locating the
750             // diagonal element using p from the Q.R. factorization
751             int pj = permutation[j];
752             double dpj = diag[pj];
753             if (dpj != 0) {
754                 Arrays.fill(lmDiag, j + 1, lmDiag.length, 0);
755             }
756             lmDiag[j] = dpj;
757 
758             //  the transformations to eliminate the row of d
759             // modify only a single element of Qty
760             // beyond the first n, which is initially zero.
761             double qtbpj = 0;
762             for (int k = j; k < solvedCols; ++k) {
763                 int pk = permutation[k];
764 
765                 // determine a Givens rotation which eliminates the
766                 // appropriate element in the current row of d
767                 if (lmDiag[k] != 0) {
768 
769                     final double sin;
770                     final double cos;
771                     double rkk = weightedJacobian[k][pk];
772                     if (FastMath.abs(rkk) < FastMath.abs(lmDiag[k])) {
773                         final double cotan = rkk / lmDiag[k];
774                         sin   = 1.0 / FastMath.sqrt(1.0 + cotan * cotan);
775                         cos   = sin * cotan;
776                     } else {
777                         final double tan = lmDiag[k] / rkk;
778                         cos = 1.0 / FastMath.sqrt(1.0 + tan * tan);
779                         sin = cos * tan;
780                     }
781 
782                     // compute the modified diagonal element of R and
783                     // the modified element of (Qty,0)
784                     weightedJacobian[k][pk] = cos * rkk + sin * lmDiag[k];
785                     final double temp = cos * work[k] + sin * qtbpj;
786                     qtbpj = -sin * work[k] + cos * qtbpj;
787                     work[k] = temp;
788 
789                     // accumulate the tranformation in the row of s
790                     for (int i = k + 1; i < solvedCols; ++i) {
791                         double rik = weightedJacobian[i][pk];
792                         final double temp2 = cos * rik + sin * lmDiag[i];
793                         lmDiag[i] = -sin * rik + cos * lmDiag[i];
794                         weightedJacobian[i][pk] = temp2;
795                     }
796                 }
797             }
798 
799             // store the diagonal element of s and restore
800             // the corresponding diagonal element of R
801             lmDiag[j] = weightedJacobian[j][permutation[j]];
802             weightedJacobian[j][permutation[j]] = lmDir[j];
803         }
804 
805         // solve the triangular system for z, if the system is
806         // singular, then obtain a least squares solution
807         int nSing = solvedCols;
808         for (int j = 0; j < solvedCols; ++j) {
809             if ((lmDiag[j] == 0) && (nSing == solvedCols)) {
810                 nSing = j;
811             }
812             if (nSing < solvedCols) {
813                 work[j] = 0;
814             }
815         }
816         if (nSing > 0) {
817             for (int j = nSing - 1; j >= 0; --j) {
818                 int pj = permutation[j];
819                 double sum = 0;
820                 for (int i = j + 1; i < nSing; ++i) {
821                     sum += weightedJacobian[i][pj] * work[i];
822                 }
823                 work[j] = (work[j] - sum) / lmDiag[j];
824             }
825         }
826 
827         // permute the components of z back to components of lmDir
828         for (int j = 0; j < lmDir.length; ++j) {
829             lmDir[permutation[j]] = work[j];
830         }
831     }
832 
833     /**
834      * Decompose a matrix A as A.P = Q.R using Householder transforms.
835      * <p>As suggested in the P. Lascaux and R. Theodor book
836      * <i>Analyse num&eacute;rique matricielle appliqu&eacute;e &agrave;
837      * l'art de l'ing&eacute;nieur</i> (Masson, 1986), instead of representing
838      * the Householder transforms with u<sub>k</sub> unit vectors such that:
839      * <pre>
840      * H<sub>k</sub> = I - 2u<sub>k</sub>.u<sub>k</sub><sup>t</sup>
841      * </pre>
842      * we use <sub>k</sub> non-unit vectors such that:
843      * <pre>
844      * H<sub>k</sub> = I - beta<sub>k</sub>v<sub>k</sub>.v<sub>k</sub><sup>t</sup>
845      * </pre>
846      * where v<sub>k</sub> = a<sub>k</sub> - alpha<sub>k</sub> e<sub>k</sub>.
847      * The beta<sub>k</sub> coefficients are provided upon exit as recomputing
848      * them from the v<sub>k</sub> vectors would be costly.</p>
849      * <p>This decomposition handles rank deficient cases since the tranformations
850      * are performed in non-increasing columns norms order thanks to columns
851      * pivoting. The diagonal elements of the R matrix are therefore also in
852      * non-increasing absolute values order.</p>
853      *
854      * @param jacobian Weighted Jacobian matrix at the current point.
855      * @exception ConvergenceException if the decomposition cannot be performed
856      */
857     private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException {
858         // Code in this class assumes that the weighted Jacobian is -(W^(1/2) J),
859         // hence the multiplication by -1.
860         weightedJacobian = jacobian.scalarMultiply(-1).getData();
861 
862         final int nR = weightedJacobian.length;
863         final int nC = weightedJacobian[0].length;
864 
865         // initializations
866         for (int k = 0; k < nC; ++k) {
867             permutation[k] = k;
868             double norm2 = 0;
869             for (int i = 0; i < nR; ++i) {
870                 double akk = weightedJacobian[i][k];
871                 norm2 += akk * akk;
872             }
873             jacNorm[k] = FastMath.sqrt(norm2);
874         }
875 
876         // transform the matrix column after column
877         for (int k = 0; k < nC; ++k) {
878 
879             // select the column with the greatest norm on active components
880             int nextColumn = -1;
881             double ak2 = Double.NEGATIVE_INFINITY;
882             for (int i = k; i < nC; ++i) {
883                 double norm2 = 0;
884                 for (int j = k; j < nR; ++j) {
885                     double aki = weightedJacobian[j][permutation[i]];
886                     norm2 += aki * aki;
887                 }
888                 if (Double.isInfinite(norm2) || Double.isNaN(norm2)) {
889                     throw new ConvergenceException(LocalizedFormats.UNABLE_TO_PERFORM_QR_DECOMPOSITION_ON_JACOBIAN,
890                                                    nR, nC);
891                 }
892                 if (norm2 > ak2) {
893                     nextColumn = i;
894                     ak2        = norm2;
895                 }
896             }
897             if (ak2 <= qrRankingThreshold) {
898                 rank = k;
899                 return;
900             }
901             int pk                  = permutation[nextColumn];
902             permutation[nextColumn] = permutation[k];
903             permutation[k]          = pk;
904 
905             // choose alpha such that Hk.u = alpha ek
906             double akk   = weightedJacobian[k][pk];
907             double alpha = (akk > 0) ? -FastMath.sqrt(ak2) : FastMath.sqrt(ak2);
908             double betak = 1.0 / (ak2 - akk * alpha);
909             beta[pk]     = betak;
910 
911             // transform the current column
912             diagR[pk]        = alpha;
913             weightedJacobian[k][pk] -= alpha;
914 
915             // transform the remaining columns
916             for (int dk = nC - 1 - k; dk > 0; --dk) {
917                 double gamma = 0;
918                 for (int j = k; j < nR; ++j) {
919                     gamma += weightedJacobian[j][pk] * weightedJacobian[j][permutation[k + dk]];
920                 }
921                 gamma *= betak;
922                 for (int j = k; j < nR; ++j) {
923                     weightedJacobian[j][permutation[k + dk]] -= gamma * weightedJacobian[j][pk];
924                 }
925             }
926         }
927         rank = solvedCols;
928     }
929 
930     /**
931      * Compute the product Qt.y for some Q.R. decomposition.
932      *
933      * @param y vector to multiply (will be overwritten with the result)
934      */
935     private void qTy(double[] y) {
936         final int nR = weightedJacobian.length;
937         final int nC = weightedJacobian[0].length;
938 
939         for (int k = 0; k < nC; ++k) {
940             int pk = permutation[k];
941             double gamma = 0;
942             for (int i = k; i < nR; ++i) {
943                 gamma += weightedJacobian[i][pk] * y[i];
944             }
945             gamma *= beta[pk];
946             for (int i = k; i < nR; ++i) {
947                 y[i] -= gamma * weightedJacobian[i][pk];
948             }
949         }
950     }
951 
952     /**
953      * @throws MathUnsupportedOperationException if bounds were passed to the
954      * {@link #optimize(OptimizationData[]) optimize} method.
955      */
956     private void checkParameters() {
957         if (getLowerBound() != null ||
958             getUpperBound() != null) {
959             throw new MathUnsupportedOperationException(LocalizedFormats.CONSTRAINT);
960         }
961     }
962 }