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