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