LevenbergMarquardtOptimizer.java

  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. import java.util.Arrays;
  19. import org.apache.commons.math3.exception.ConvergenceException;
  20. import org.apache.commons.math3.exception.MathUnsupportedOperationException;
  21. import org.apache.commons.math3.exception.util.LocalizedFormats;
  22. import org.apache.commons.math3.optim.PointVectorValuePair;
  23. import org.apache.commons.math3.optim.ConvergenceChecker;
  24. import org.apache.commons.math3.linear.RealMatrix;
  25. import org.apache.commons.math3.util.Precision;
  26. import org.apache.commons.math3.util.FastMath;


  27. /**
  28.  * This class solves a least-squares problem using the Levenberg-Marquardt
  29.  * algorithm.
  30.  * <br/>
  31.  * Constraints are not supported: the call to
  32.  * {@link #optimize(OptimizationData[]) optimize} will throw
  33.  * {@link MathUnsupportedOperationException} if bounds are passed to it.
  34.  *
  35.  * <p>This implementation <em>should</em> work even for over-determined systems
  36.  * (i.e. systems having more point than equations). Over-determined systems
  37.  * are solved by ignoring the point which have the smallest impact according
  38.  * to their jacobian column norm. Only the rank of the matrix and some loop bounds
  39.  * are changed to implement this.</p>
  40.  *
  41.  * <p>The resolution engine is a simple translation of the MINPACK <a
  42.  * href="http://www.netlib.org/minpack/lmder.f">lmder</a> routine with minor
  43.  * changes. The changes include the over-determined resolution, the use of
  44.  * inherited convergence checker and the Q.R. decomposition which has been
  45.  * rewritten following the algorithm described in the
  46.  * P. Lascaux and R. Theodor book <i>Analyse num&eacute;rique matricielle
  47.  * appliqu&eacute;e &agrave; l'art de l'ing&eacute;nieur</i>, Masson 1986.</p>
  48.  * <p>The authors of the original fortran version are:
  49.  * <ul>
  50.  * <li>Argonne National Laboratory. MINPACK project. March 1980</li>
  51.  * <li>Burton S. Garbow</li>
  52.  * <li>Kenneth E. Hillstrom</li>
  53.  * <li>Jorge J. More</li>
  54.  * </ul>
  55.  * The redistribution policy for MINPACK is available <a
  56.  * href="http://www.netlib.org/minpack/disclaimer">here</a>, for convenience, it
  57.  * is reproduced below.</p>
  58.  *
  59.  * <table border="0" width="80%" cellpadding="10" align="center" bgcolor="#E0E0E0">
  60.  * <tr><td>
  61.  *    Minpack Copyright Notice (1999) University of Chicago.
  62.  *    All rights reserved
  63.  * </td></tr>
  64.  * <tr><td>
  65.  * Redistribution and use in source and binary forms, with or without
  66.  * modification, are permitted provided that the following conditions
  67.  * are met:
  68.  * <ol>
  69.  *  <li>Redistributions of source code must retain the above copyright
  70.  *      notice, this list of conditions and the following disclaimer.</li>
  71.  * <li>Redistributions in binary form must reproduce the above
  72.  *     copyright notice, this list of conditions and the following
  73.  *     disclaimer in the documentation and/or other materials provided
  74.  *     with the distribution.</li>
  75.  * <li>The end-user documentation included with the redistribution, if any,
  76.  *     must include the following acknowledgment:
  77.  *     <code>This product includes software developed by the University of
  78.  *           Chicago, as Operator of Argonne National Laboratory.</code>
  79.  *     Alternately, this acknowledgment may appear in the software itself,
  80.  *     if and wherever such third-party acknowledgments normally appear.</li>
  81.  * <li><strong>WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS"
  82.  *     WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE
  83.  *     UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND
  84.  *     THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR
  85.  *     IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES
  86.  *     OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE
  87.  *     OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY
  88.  *     OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR
  89.  *     USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF
  90.  *     THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4)
  91.  *     DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION
  92.  *     UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL
  93.  *     BE CORRECTED.</strong></li>
  94.  * <li><strong>LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT
  95.  *     HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF
  96.  *     ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT,
  97.  *     INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF
  98.  *     ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF
  99.  *     PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER
  100.  *     SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT
  101.  *     (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE,
  102.  *     EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE
  103.  *     POSSIBILITY OF SUCH LOSS OR DAMAGES.</strong></li>
  104.  * <ol></td></tr>
  105.  * </table>
  106.  *
  107.  * @since 2.0
  108.  * @deprecated All classes and interfaces in this package are deprecated.
  109.  * The optimizers that were provided here were moved to the
  110.  * {@link org.apache.commons.math3.fitting.leastsquares} package
  111.  * (cf. MATH-1008).
  112.  */
  113. @Deprecated
  114. public class LevenbergMarquardtOptimizer
  115.     extends AbstractLeastSquaresOptimizer {
  116.     /** Twice the "epsilon machine". */
  117.     private static final double TWO_EPS = 2 * Precision.EPSILON;
  118.     /** Number of solved point. */
  119.     private int solvedCols;
  120.     /** Diagonal elements of the R matrix in the Q.R. decomposition. */
  121.     private double[] diagR;
  122.     /** Norms of the columns of the jacobian matrix. */
  123.     private double[] jacNorm;
  124.     /** Coefficients of the Householder transforms vectors. */
  125.     private double[] beta;
  126.     /** Columns permutation array. */
  127.     private int[] permutation;
  128.     /** Rank of the jacobian matrix. */
  129.     private int rank;
  130.     /** Levenberg-Marquardt parameter. */
  131.     private double lmPar;
  132.     /** Parameters evolution direction associated with lmPar. */
  133.     private double[] lmDir;
  134.     /** Positive input variable used in determining the initial step bound. */
  135.     private final double initialStepBoundFactor;
  136.     /** Desired relative error in the sum of squares. */
  137.     private final double costRelativeTolerance;
  138.     /**  Desired relative error in the approximate solution parameters. */
  139.     private final double parRelativeTolerance;
  140.     /** Desired max cosine on the orthogonality between the function vector
  141.      * and the columns of the jacobian. */
  142.     private final double orthoTolerance;
  143.     /** Threshold for QR ranking. */
  144.     private final double qrRankingThreshold;
  145.     /** Weighted residuals. */
  146.     private double[] weightedResidual;
  147.     /** Weighted Jacobian. */
  148.     private double[][] weightedJacobian;

  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.      * Constructor that allows the specification of a custom convergence
  168.      * checker.
  169.      * Note that all the usual convergence checks will be <em>disabled</em>.
  170.      * The default values for the algorithm settings are:
  171.      * <ul>
  172.      *  <li>Initial step bound factor: 100</li>
  173.      *  <li>Cost relative tolerance: 1e-10</li>
  174.      *  <li>Parameters relative tolerance: 1e-10</li>
  175.      *  <li>Orthogonality tolerance: 1e-10</li>
  176.      *  <li>QR ranking threshold: {@link Precision#SAFE_MIN}</li>
  177.      * </ul>
  178.      *
  179.      * @param checker Convergence checker.
  180.      */
  181.     public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker) {
  182.         this(100, checker, 1e-10, 1e-10, 1e-10, Precision.SAFE_MIN);
  183.     }

  184.     /**
  185.      * Constructor that allows the specification of a custom convergence
  186.      * checker, in addition to the standard ones.
  187.      *
  188.      * @param initialStepBoundFactor Positive input variable used in
  189.      * determining the initial step bound. This bound is set to the
  190.      * product of initialStepBoundFactor and the euclidean norm of
  191.      * {@code diag * x} if non-zero, or else to {@code initialStepBoundFactor}
  192.      * itself. In most cases factor should lie in the interval
  193.      * {@code (0.1, 100.0)}. {@code 100} is a generally recommended value.
  194.      * @param checker Convergence checker.
  195.      * @param costRelativeTolerance Desired relative error in the sum of
  196.      * squares.
  197.      * @param parRelativeTolerance Desired relative error in the approximate
  198.      * solution parameters.
  199.      * @param orthoTolerance Desired max cosine on the orthogonality between
  200.      * the function vector and the columns of the Jacobian.
  201.      * @param threshold Desired threshold for QR ranking. If the squared norm
  202.      * of a column vector is smaller or equal to this threshold during QR
  203.      * decomposition, it is considered to be a zero vector and hence the rank
  204.      * of the matrix is reduced.
  205.      */
  206.     public LevenbergMarquardtOptimizer(double initialStepBoundFactor,
  207.                                        ConvergenceChecker<PointVectorValuePair> checker,
  208.                                        double costRelativeTolerance,
  209.                                        double parRelativeTolerance,
  210.                                        double orthoTolerance,
  211.                                        double threshold) {
  212.         super(checker);
  213.         this.initialStepBoundFactor = initialStepBoundFactor;
  214.         this.costRelativeTolerance = costRelativeTolerance;
  215.         this.parRelativeTolerance = parRelativeTolerance;
  216.         this.orthoTolerance = orthoTolerance;
  217.         this.qrRankingThreshold = threshold;
  218.     }

  219.     /**
  220.      * Build an optimizer for least squares problems with default values
  221.      * for some of the tuning parameters (see the {@link
  222.      * #LevenbergMarquardtOptimizer(double,double,double,double,double)
  223.      * other contructor}.
  224.      * The default values for the algorithm settings are:
  225.      * <ul>
  226.      *  <li>Initial step bound factor}: 100</li>
  227.      *  <li>QR ranking threshold}: {@link Precision#SAFE_MIN}</li>
  228.      * </ul>
  229.      *
  230.      * @param costRelativeTolerance Desired relative error in the sum of
  231.      * squares.
  232.      * @param parRelativeTolerance Desired relative error in the approximate
  233.      * solution parameters.
  234.      * @param orthoTolerance Desired max cosine on the orthogonality between
  235.      * the function vector and the columns of the Jacobian.
  236.      */
  237.     public LevenbergMarquardtOptimizer(double costRelativeTolerance,
  238.                                        double parRelativeTolerance,
  239.                                        double orthoTolerance) {
  240.         this(100,
  241.              costRelativeTolerance, parRelativeTolerance, orthoTolerance,
  242.              Precision.SAFE_MIN);
  243.     }

  244.     /**
  245.      * The arguments control the behaviour of the default convergence checking
  246.      * procedure.
  247.      * Additional criteria can defined through the setting of a {@link
  248.      * ConvergenceChecker}.
  249.      *
  250.      * @param initialStepBoundFactor Positive input variable used in
  251.      * determining the initial step bound. This bound is set to the
  252.      * product of initialStepBoundFactor and the euclidean norm of
  253.      * {@code diag * x} if non-zero, or else to {@code initialStepBoundFactor}
  254.      * itself. In most cases factor should lie in the interval
  255.      * {@code (0.1, 100.0)}. {@code 100} is a generally recommended value.
  256.      * @param costRelativeTolerance Desired relative error in the sum of
  257.      * squares.
  258.      * @param parRelativeTolerance Desired relative error in the approximate
  259.      * solution parameters.
  260.      * @param orthoTolerance Desired max cosine on the orthogonality between
  261.      * the function vector and the columns of the Jacobian.
  262.      * @param threshold Desired threshold for QR ranking. If the squared norm
  263.      * of a column vector is smaller or equal to this threshold during QR
  264.      * decomposition, it is considered to be a zero vector and hence the rank
  265.      * of the matrix is reduced.
  266.      */
  267.     public LevenbergMarquardtOptimizer(double initialStepBoundFactor,
  268.                                        double costRelativeTolerance,
  269.                                        double parRelativeTolerance,
  270.                                        double orthoTolerance,
  271.                                        double threshold) {
  272.         super(null); // No custom convergence criterion.
  273.         this.initialStepBoundFactor = initialStepBoundFactor;
  274.         this.costRelativeTolerance = costRelativeTolerance;
  275.         this.parRelativeTolerance = parRelativeTolerance;
  276.         this.orthoTolerance = orthoTolerance;
  277.         this.qrRankingThreshold = threshold;
  278.     }

  279.     /** {@inheritDoc} */
  280.     @Override
  281.     protected PointVectorValuePair doOptimize() {
  282.         checkParameters();

  283.         final int nR = getTarget().length; // Number of observed data.
  284.         final double[] currentPoint = getStartPoint();
  285.         final int nC = currentPoint.length; // Number of parameters.

  286.         // arrays shared with the other private methods
  287.         solvedCols  = FastMath.min(nR, nC);
  288.         diagR       = new double[nC];
  289.         jacNorm     = new double[nC];
  290.         beta        = new double[nC];
  291.         permutation = new int[nC];
  292.         lmDir       = new double[nC];

  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.         final RealMatrix weightMatrixSqrt = getWeightSquareRoot();

  305.         // Evaluate the function at the starting point and calculate its norm.
  306.         double[] currentObjective = computeObjectiveValue(currentPoint);
  307.         double[] currentResiduals = computeResiduals(currentObjective);
  308.         PointVectorValuePair current = new PointVectorValuePair(currentPoint, currentObjective);
  309.         double currentCost = computeCost(currentResiduals);

  310.         // Outer loop.
  311.         lmPar = 0;
  312.         boolean firstIteration = true;
  313.         final ConvergenceChecker<PointVectorValuePair> checker = getConvergenceChecker();
  314.         while (true) {
  315.             incrementIterationCount();

  316.             final PointVectorValuePair previous = current;

  317.             // QR decomposition of the jacobian matrix
  318.             qrDecomposition(computeWeightedJacobian(currentPoint));

  319.             weightedResidual = weightMatrixSqrt.operate(currentResiduals);
  320.             for (int i = 0; i < nR; i++) {
  321.                 qtf[i] = weightedResidual[i];
  322.             }

  323.             // compute Qt.res
  324.             qTy(qtf);

  325.             // now we don't need Q anymore,
  326.             // so let jacobian contain the R matrix with its diagonal elements
  327.             for (int k = 0; k < solvedCols; ++k) {
  328.                 int pk = permutation[k];
  329.                 weightedJacobian[k][pk] = diagR[pk];
  330.             }

  331.             if (firstIteration) {
  332.                 // scale the point according to the norms of the columns
  333.                 // of the initial jacobian
  334.                 xNorm = 0;
  335.                 for (int k = 0; k < nC; ++k) {
  336.                     double dk = jacNorm[k];
  337.                     if (dk == 0) {
  338.                         dk = 1.0;
  339.                     }
  340.                     double xk = dk * currentPoint[k];
  341.                     xNorm  += xk * xk;
  342.                     diag[k] = dk;
  343.                 }
  344.                 xNorm = FastMath.sqrt(xNorm);

  345.                 // initialize the step bound delta
  346.                 delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);
  347.             }

  348.             // check orthogonality between function vector and jacobian columns
  349.             double maxCosine = 0;
  350.             if (currentCost != 0) {
  351.                 for (int j = 0; j < solvedCols; ++j) {
  352.                     int    pj = permutation[j];
  353.                     double s  = jacNorm[pj];
  354.                     if (s != 0) {
  355.                         double sum = 0;
  356.                         for (int i = 0; i <= j; ++i) {
  357.                             sum += weightedJacobian[i][pj] * qtf[i];
  358.                         }
  359.                         maxCosine = FastMath.max(maxCosine, FastMath.abs(sum) / (s * currentCost));
  360.                     }
  361.                 }
  362.             }
  363.             if (maxCosine <= orthoTolerance) {
  364.                 // Convergence has been reached.
  365.                 setCost(currentCost);
  366.                 return current;
  367.             }

  368.             // rescale if necessary
  369.             for (int j = 0; j < nC; ++j) {
  370.                 diag[j] = FastMath.max(diag[j], jacNorm[j]);
  371.             }

  372.             // Inner loop.
  373.             for (double ratio = 0; ratio < 1.0e-4;) {

  374.                 // save the state
  375.                 for (int j = 0; j < solvedCols; ++j) {
  376.                     int pj = permutation[j];
  377.                     oldX[pj] = currentPoint[pj];
  378.                 }
  379.                 final double previousCost = currentCost;
  380.                 double[] tmpVec = weightedResidual;
  381.                 weightedResidual = oldRes;
  382.                 oldRes    = tmpVec;
  383.                 tmpVec    = currentObjective;
  384.                 currentObjective = oldObj;
  385.                 oldObj    = tmpVec;

  386.                 // determine the Levenberg-Marquardt parameter
  387.                 determineLMParameter(qtf, delta, diag, work1, work2, work3);

  388.                 // compute the new point and the norm of the evolution direction
  389.                 double lmNorm = 0;
  390.                 for (int j = 0; j < solvedCols; ++j) {
  391.                     int pj = permutation[j];
  392.                     lmDir[pj] = -lmDir[pj];
  393.                     currentPoint[pj] = oldX[pj] + lmDir[pj];
  394.                     double s = diag[pj] * lmDir[pj];
  395.                     lmNorm  += s * s;
  396.                 }
  397.                 lmNorm = FastMath.sqrt(lmNorm);
  398.                 // on the first iteration, adjust the initial step bound.
  399.                 if (firstIteration) {
  400.                     delta = FastMath.min(delta, lmNorm);
  401.                 }

  402.                 // Evaluate the function at x + p and calculate its norm.
  403.                 currentObjective = computeObjectiveValue(currentPoint);
  404.                 currentResiduals = computeResiduals(currentObjective);
  405.                 current = new PointVectorValuePair(currentPoint, currentObjective);
  406.                 currentCost = computeCost(currentResiduals);

  407.                 // compute the scaled actual reduction
  408.                 double actRed = -1.0;
  409.                 if (0.1 * currentCost < previousCost) {
  410.                     double r = currentCost / previousCost;
  411.                     actRed = 1.0 - r * r;
  412.                 }

  413.                 // compute the scaled predicted reduction
  414.                 // and the scaled directional derivative
  415.                 for (int j = 0; j < solvedCols; ++j) {
  416.                     int pj = permutation[j];
  417.                     double dirJ = lmDir[pj];
  418.                     work1[j] = 0;
  419.                     for (int i = 0; i <= j; ++i) {
  420.                         work1[i] += weightedJacobian[i][pj] * dirJ;
  421.                     }
  422.                 }
  423.                 double coeff1 = 0;
  424.                 for (int j = 0; j < solvedCols; ++j) {
  425.                     coeff1 += work1[j] * work1[j];
  426.                 }
  427.                 double pc2 = previousCost * previousCost;
  428.                 coeff1 /= pc2;
  429.                 double coeff2 = lmPar * lmNorm * lmNorm / pc2;
  430.                 double preRed = coeff1 + 2 * coeff2;
  431.                 double dirDer = -(coeff1 + coeff2);

  432.                 // ratio of the actual to the predicted reduction
  433.                 ratio = (preRed == 0) ? 0 : (actRed / preRed);

  434.                 // update the step bound
  435.                 if (ratio <= 0.25) {
  436.                     double tmp =
  437.                         (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;
  438.                         if ((0.1 * currentCost >= previousCost) || (tmp < 0.1)) {
  439.                             tmp = 0.1;
  440.                         }
  441.                         delta = tmp * FastMath.min(delta, 10.0 * lmNorm);
  442.                         lmPar /= tmp;
  443.                 } else if ((lmPar == 0) || (ratio >= 0.75)) {
  444.                     delta = 2 * lmNorm;
  445.                     lmPar *= 0.5;
  446.                 }

  447.                 // test for successful iteration.
  448.                 if (ratio >= 1.0e-4) {
  449.                     // successful iteration, update the norm
  450.                     firstIteration = false;
  451.                     xNorm = 0;
  452.                     for (int k = 0; k < nC; ++k) {
  453.                         double xK = diag[k] * currentPoint[k];
  454.                         xNorm += xK * xK;
  455.                     }
  456.                     xNorm = FastMath.sqrt(xNorm);

  457.                     // tests for convergence.
  458.                     if (checker != null && checker.converged(getIterations(), previous, current)) {
  459.                         setCost(currentCost);
  460.                         return current;
  461.                     }
  462.                 } else {
  463.                     // failed iteration, reset the previous values
  464.                     currentCost = previousCost;
  465.                     for (int j = 0; j < solvedCols; ++j) {
  466.                         int pj = permutation[j];
  467.                         currentPoint[pj] = oldX[pj];
  468.                     }
  469.                     tmpVec    = weightedResidual;
  470.                     weightedResidual = oldRes;
  471.                     oldRes    = tmpVec;
  472.                     tmpVec    = currentObjective;
  473.                     currentObjective = oldObj;
  474.                     oldObj    = tmpVec;
  475.                     // Reset "current" to previous values.
  476.                     current = new PointVectorValuePair(currentPoint, currentObjective);
  477.                 }

  478.                 // Default convergence criteria.
  479.                 if ((FastMath.abs(actRed) <= costRelativeTolerance &&
  480.                      preRed <= costRelativeTolerance &&
  481.                      ratio <= 2.0) ||
  482.                     delta <= parRelativeTolerance * xNorm) {
  483.                     setCost(currentCost);
  484.                     return current;
  485.                 }

  486.                 // tests for termination and stringent tolerances
  487.                 if (FastMath.abs(actRed) <= TWO_EPS &&
  488.                     preRed <= TWO_EPS &&
  489.                     ratio <= 2.0) {
  490.                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,
  491.                                                    costRelativeTolerance);
  492.                 } else if (delta <= TWO_EPS * xNorm) {
  493.                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,
  494.                                                    parRelativeTolerance);
  495.                 } else if (maxCosine <= TWO_EPS) {
  496.                     throw new ConvergenceException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,
  497.                                                    orthoTolerance);
  498.                 }
  499.             }
  500.         }
  501.     }

  502.     /**
  503.      * Determine the Levenberg-Marquardt parameter.
  504.      * <p>This implementation is a translation in Java of the MINPACK
  505.      * <a href="http://www.netlib.org/minpack/lmpar.f">lmpar</a>
  506.      * routine.</p>
  507.      * <p>This method sets the lmPar and lmDir attributes.</p>
  508.      * <p>The authors of the original fortran function are:</p>
  509.      * <ul>
  510.      *   <li>Argonne National Laboratory. MINPACK project. March 1980</li>
  511.      *   <li>Burton  S. Garbow</li>
  512.      *   <li>Kenneth E. Hillstrom</li>
  513.      *   <li>Jorge   J. More</li>
  514.      * </ul>
  515.      * <p>Luc Maisonobe did the Java translation.</p>
  516.      *
  517.      * @param qy array containing qTy
  518.      * @param delta upper bound on the euclidean norm of diagR * lmDir
  519.      * @param diag diagonal matrix
  520.      * @param work1 work array
  521.      * @param work2 work array
  522.      * @param work3 work array
  523.      */
  524.     private void determineLMParameter(double[] qy, double delta, double[] diag,
  525.                                       double[] work1, double[] work2, double[] work3) {
  526.         final int nC = weightedJacobian[0].length;

  527.         // compute and store in x the gauss-newton direction, if the
  528.         // jacobian is rank-deficient, obtain a least squares solution
  529.         for (int j = 0; j < rank; ++j) {
  530.             lmDir[permutation[j]] = qy[j];
  531.         }
  532.         for (int j = rank; j < nC; ++j) {
  533.             lmDir[permutation[j]] = 0;
  534.         }
  535.         for (int k = rank - 1; k >= 0; --k) {
  536.             int pk = permutation[k];
  537.             double ypk = lmDir[pk] / diagR[pk];
  538.             for (int i = 0; i < k; ++i) {
  539.                 lmDir[permutation[i]] -= ypk * weightedJacobian[i][pk];
  540.             }
  541.             lmDir[pk] = ypk;
  542.         }

  543.         // evaluate the function at the origin, and test
  544.         // for acceptance of the Gauss-Newton direction
  545.         double dxNorm = 0;
  546.         for (int j = 0; j < solvedCols; ++j) {
  547.             int pj = permutation[j];
  548.             double s = diag[pj] * lmDir[pj];
  549.             work1[pj] = s;
  550.             dxNorm += s * s;
  551.         }
  552.         dxNorm = FastMath.sqrt(dxNorm);
  553.         double fp = dxNorm - delta;
  554.         if (fp <= 0.1 * delta) {
  555.             lmPar = 0;
  556.             return;
  557.         }

  558.         // if the jacobian is not rank deficient, the Newton step provides
  559.         // a lower bound, parl, for the zero of the function,
  560.         // otherwise set this bound to zero
  561.         double sum2;
  562.         double parl = 0;
  563.         if (rank == solvedCols) {
  564.             for (int j = 0; j < solvedCols; ++j) {
  565.                 int pj = permutation[j];
  566.                 work1[pj] *= diag[pj] / dxNorm;
  567.             }
  568.             sum2 = 0;
  569.             for (int j = 0; j < solvedCols; ++j) {
  570.                 int pj = permutation[j];
  571.                 double sum = 0;
  572.                 for (int i = 0; i < j; ++i) {
  573.                     sum += weightedJacobian[i][pj] * work1[permutation[i]];
  574.                 }
  575.                 double s = (work1[pj] - sum) / diagR[pj];
  576.                 work1[pj] = s;
  577.                 sum2 += s * s;
  578.             }
  579.             parl = fp / (delta * sum2);
  580.         }

  581.         // calculate an upper bound, paru, for the zero of the function
  582.         sum2 = 0;
  583.         for (int j = 0; j < solvedCols; ++j) {
  584.             int pj = permutation[j];
  585.             double sum = 0;
  586.             for (int i = 0; i <= j; ++i) {
  587.                 sum += weightedJacobian[i][pj] * qy[i];
  588.             }
  589.             sum /= diag[pj];
  590.             sum2 += sum * sum;
  591.         }
  592.         double gNorm = FastMath.sqrt(sum2);
  593.         double paru = gNorm / delta;
  594.         if (paru == 0) {
  595.             paru = Precision.SAFE_MIN / FastMath.min(delta, 0.1);
  596.         }

  597.         // if the input par lies outside of the interval (parl,paru),
  598.         // set par to the closer endpoint
  599.         lmPar = FastMath.min(paru, FastMath.max(lmPar, parl));
  600.         if (lmPar == 0) {
  601.             lmPar = gNorm / dxNorm;
  602.         }

  603.         for (int countdown = 10; countdown >= 0; --countdown) {

  604.             // evaluate the function at the current value of lmPar
  605.             if (lmPar == 0) {
  606.                 lmPar = FastMath.max(Precision.SAFE_MIN, 0.001 * paru);
  607.             }
  608.             double sPar = FastMath.sqrt(lmPar);
  609.             for (int j = 0; j < solvedCols; ++j) {
  610.                 int pj = permutation[j];
  611.                 work1[pj] = sPar * diag[pj];
  612.             }
  613.             determineLMDirection(qy, work1, work2, work3);

  614.             dxNorm = 0;
  615.             for (int j = 0; j < solvedCols; ++j) {
  616.                 int pj = permutation[j];
  617.                 double s = diag[pj] * lmDir[pj];
  618.                 work3[pj] = s;
  619.                 dxNorm += s * s;
  620.             }
  621.             dxNorm = FastMath.sqrt(dxNorm);
  622.             double previousFP = fp;
  623.             fp = dxNorm - delta;

  624.             // if the function is small enough, accept the current value
  625.             // of lmPar, also test for the exceptional cases where parl is zero
  626.             if ((FastMath.abs(fp) <= 0.1 * delta) ||
  627.                     ((parl == 0) && (fp <= previousFP) && (previousFP < 0))) {
  628.                 return;
  629.             }

  630.             // compute the Newton correction
  631.             for (int j = 0; j < solvedCols; ++j) {
  632.                 int pj = permutation[j];
  633.                 work1[pj] = work3[pj] * diag[pj] / dxNorm;
  634.             }
  635.             for (int j = 0; j < solvedCols; ++j) {
  636.                 int pj = permutation[j];
  637.                 work1[pj] /= work2[j];
  638.                 double tmp = work1[pj];
  639.                 for (int i = j + 1; i < solvedCols; ++i) {
  640.                     work1[permutation[i]] -= weightedJacobian[i][pj] * tmp;
  641.                 }
  642.             }
  643.             sum2 = 0;
  644.             for (int j = 0; j < solvedCols; ++j) {
  645.                 double s = work1[permutation[j]];
  646.                 sum2 += s * s;
  647.             }
  648.             double correction = fp / (delta * sum2);

  649.             // depending on the sign of the function, update parl or paru.
  650.             if (fp > 0) {
  651.                 parl = FastMath.max(parl, lmPar);
  652.             } else if (fp < 0) {
  653.                 paru = FastMath.min(paru, lmPar);
  654.             }

  655.             // compute an improved estimate for lmPar
  656.             lmPar = FastMath.max(parl, lmPar + correction);

  657.         }
  658.     }

  659.     /**
  660.      * Solve a*x = b and d*x = 0 in the least squares sense.
  661.      * <p>This implementation is a translation in Java of the MINPACK
  662.      * <a href="http://www.netlib.org/minpack/qrsolv.f">qrsolv</a>
  663.      * routine.</p>
  664.      * <p>This method sets the lmDir and lmDiag attributes.</p>
  665.      * <p>The authors of the original fortran function are:</p>
  666.      * <ul>
  667.      *   <li>Argonne National Laboratory. MINPACK project. March 1980</li>
  668.      *   <li>Burton  S. Garbow</li>
  669.      *   <li>Kenneth E. Hillstrom</li>
  670.      *   <li>Jorge   J. More</li>
  671.      * </ul>
  672.      * <p>Luc Maisonobe did the Java translation.</p>
  673.      *
  674.      * @param qy array containing qTy
  675.      * @param diag diagonal matrix
  676.      * @param lmDiag diagonal elements associated with lmDir
  677.      * @param work work array
  678.      */
  679.     private void determineLMDirection(double[] qy, double[] diag,
  680.                                       double[] lmDiag, double[] work) {

  681.         // copy R and Qty to preserve input and initialize s
  682.         //  in particular, save the diagonal elements of R in lmDir
  683.         for (int j = 0; j < solvedCols; ++j) {
  684.             int pj = permutation[j];
  685.             for (int i = j + 1; i < solvedCols; ++i) {
  686.                 weightedJacobian[i][pj] = weightedJacobian[j][permutation[i]];
  687.             }
  688.             lmDir[j] = diagR[pj];
  689.             work[j]  = qy[j];
  690.         }

  691.         // eliminate the diagonal matrix d using a Givens rotation
  692.         for (int j = 0; j < solvedCols; ++j) {

  693.             // prepare the row of d to be eliminated, locating the
  694.             // diagonal element using p from the Q.R. factorization
  695.             int pj = permutation[j];
  696.             double dpj = diag[pj];
  697.             if (dpj != 0) {
  698.                 Arrays.fill(lmDiag, j + 1, lmDiag.length, 0);
  699.             }
  700.             lmDiag[j] = dpj;

  701.             //  the transformations to eliminate the row of d
  702.             // modify only a single element of Qty
  703.             // beyond the first n, which is initially zero.
  704.             double qtbpj = 0;
  705.             for (int k = j; k < solvedCols; ++k) {
  706.                 int pk = permutation[k];

  707.                 // determine a Givens rotation which eliminates the
  708.                 // appropriate element in the current row of d
  709.                 if (lmDiag[k] != 0) {

  710.                     final double sin;
  711.                     final double cos;
  712.                     double rkk = weightedJacobian[k][pk];
  713.                     if (FastMath.abs(rkk) < FastMath.abs(lmDiag[k])) {
  714.                         final double cotan = rkk / lmDiag[k];
  715.                         sin   = 1.0 / FastMath.sqrt(1.0 + cotan * cotan);
  716.                         cos   = sin * cotan;
  717.                     } else {
  718.                         final double tan = lmDiag[k] / rkk;
  719.                         cos = 1.0 / FastMath.sqrt(1.0 + tan * tan);
  720.                         sin = cos * tan;
  721.                     }

  722.                     // compute the modified diagonal element of R and
  723.                     // the modified element of (Qty,0)
  724.                     weightedJacobian[k][pk] = cos * rkk + sin * lmDiag[k];
  725.                     final double temp = cos * work[k] + sin * qtbpj;
  726.                     qtbpj = -sin * work[k] + cos * qtbpj;
  727.                     work[k] = temp;

  728.                     // accumulate the tranformation in the row of s
  729.                     for (int i = k + 1; i < solvedCols; ++i) {
  730.                         double rik = weightedJacobian[i][pk];
  731.                         final double temp2 = cos * rik + sin * lmDiag[i];
  732.                         lmDiag[i] = -sin * rik + cos * lmDiag[i];
  733.                         weightedJacobian[i][pk] = temp2;
  734.                     }
  735.                 }
  736.             }

  737.             // store the diagonal element of s and restore
  738.             // the corresponding diagonal element of R
  739.             lmDiag[j] = weightedJacobian[j][permutation[j]];
  740.             weightedJacobian[j][permutation[j]] = lmDir[j];
  741.         }

  742.         // solve the triangular system for z, if the system is
  743.         // singular, then obtain a least squares solution
  744.         int nSing = solvedCols;
  745.         for (int j = 0; j < solvedCols; ++j) {
  746.             if ((lmDiag[j] == 0) && (nSing == solvedCols)) {
  747.                 nSing = j;
  748.             }
  749.             if (nSing < solvedCols) {
  750.                 work[j] = 0;
  751.             }
  752.         }
  753.         if (nSing > 0) {
  754.             for (int j = nSing - 1; j >= 0; --j) {
  755.                 int pj = permutation[j];
  756.                 double sum = 0;
  757.                 for (int i = j + 1; i < nSing; ++i) {
  758.                     sum += weightedJacobian[i][pj] * work[i];
  759.                 }
  760.                 work[j] = (work[j] - sum) / lmDiag[j];
  761.             }
  762.         }

  763.         // permute the components of z back to components of lmDir
  764.         for (int j = 0; j < lmDir.length; ++j) {
  765.             lmDir[permutation[j]] = work[j];
  766.         }
  767.     }

  768.     /**
  769.      * Decompose a matrix A as A.P = Q.R using Householder transforms.
  770.      * <p>As suggested in the P. Lascaux and R. Theodor book
  771.      * <i>Analyse num&eacute;rique matricielle appliqu&eacute;e &agrave;
  772.      * l'art de l'ing&eacute;nieur</i> (Masson, 1986), instead of representing
  773.      * the Householder transforms with u<sub>k</sub> unit vectors such that:
  774.      * <pre>
  775.      * H<sub>k</sub> = I - 2u<sub>k</sub>.u<sub>k</sub><sup>t</sup>
  776.      * </pre>
  777.      * we use <sub>k</sub> non-unit vectors such that:
  778.      * <pre>
  779.      * H<sub>k</sub> = I - beta<sub>k</sub>v<sub>k</sub>.v<sub>k</sub><sup>t</sup>
  780.      * </pre>
  781.      * where v<sub>k</sub> = a<sub>k</sub> - alpha<sub>k</sub> e<sub>k</sub>.
  782.      * The beta<sub>k</sub> coefficients are provided upon exit as recomputing
  783.      * them from the v<sub>k</sub> vectors would be costly.</p>
  784.      * <p>This decomposition handles rank deficient cases since the tranformations
  785.      * are performed in non-increasing columns norms order thanks to columns
  786.      * pivoting. The diagonal elements of the R matrix are therefore also in
  787.      * non-increasing absolute values order.</p>
  788.      *
  789.      * @param jacobian Weighted Jacobian matrix at the current point.
  790.      * @exception ConvergenceException if the decomposition cannot be performed
  791.      */
  792.     private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException {
  793.         // Code in this class assumes that the weighted Jacobian is -(W^(1/2) J),
  794.         // hence the multiplication by -1.
  795.         weightedJacobian = jacobian.scalarMultiply(-1).getData();

  796.         final int nR = weightedJacobian.length;
  797.         final int nC = weightedJacobian[0].length;

  798.         // initializations
  799.         for (int k = 0; k < nC; ++k) {
  800.             permutation[k] = k;
  801.             double norm2 = 0;
  802.             for (int i = 0; i < nR; ++i) {
  803.                 double akk = weightedJacobian[i][k];
  804.                 norm2 += akk * akk;
  805.             }
  806.             jacNorm[k] = FastMath.sqrt(norm2);
  807.         }

  808.         // transform the matrix column after column
  809.         for (int k = 0; k < nC; ++k) {

  810.             // select the column with the greatest norm on active components
  811.             int nextColumn = -1;
  812.             double ak2 = Double.NEGATIVE_INFINITY;
  813.             for (int i = k; i < nC; ++i) {
  814.                 double norm2 = 0;
  815.                 for (int j = k; j < nR; ++j) {
  816.                     double aki = weightedJacobian[j][permutation[i]];
  817.                     norm2 += aki * aki;
  818.                 }
  819.                 if (Double.isInfinite(norm2) || Double.isNaN(norm2)) {
  820.                     throw new ConvergenceException(LocalizedFormats.UNABLE_TO_PERFORM_QR_DECOMPOSITION_ON_JACOBIAN,
  821.                                                    nR, nC);
  822.                 }
  823.                 if (norm2 > ak2) {
  824.                     nextColumn = i;
  825.                     ak2        = norm2;
  826.                 }
  827.             }
  828.             if (ak2 <= qrRankingThreshold) {
  829.                 rank = k;
  830.                 return;
  831.             }
  832.             int pk                  = permutation[nextColumn];
  833.             permutation[nextColumn] = permutation[k];
  834.             permutation[k]          = pk;

  835.             // choose alpha such that Hk.u = alpha ek
  836.             double akk   = weightedJacobian[k][pk];
  837.             double alpha = (akk > 0) ? -FastMath.sqrt(ak2) : FastMath.sqrt(ak2);
  838.             double betak = 1.0 / (ak2 - akk * alpha);
  839.             beta[pk]     = betak;

  840.             // transform the current column
  841.             diagR[pk]        = alpha;
  842.             weightedJacobian[k][pk] -= alpha;

  843.             // transform the remaining columns
  844.             for (int dk = nC - 1 - k; dk > 0; --dk) {
  845.                 double gamma = 0;
  846.                 for (int j = k; j < nR; ++j) {
  847.                     gamma += weightedJacobian[j][pk] * weightedJacobian[j][permutation[k + dk]];
  848.                 }
  849.                 gamma *= betak;
  850.                 for (int j = k; j < nR; ++j) {
  851.                     weightedJacobian[j][permutation[k + dk]] -= gamma * weightedJacobian[j][pk];
  852.                 }
  853.             }
  854.         }
  855.         rank = solvedCols;
  856.     }

  857.     /**
  858.      * Compute the product Qt.y for some Q.R. decomposition.
  859.      *
  860.      * @param y vector to multiply (will be overwritten with the result)
  861.      */
  862.     private void qTy(double[] y) {
  863.         final int nR = weightedJacobian.length;
  864.         final int nC = weightedJacobian[0].length;

  865.         for (int k = 0; k < nC; ++k) {
  866.             int pk = permutation[k];
  867.             double gamma = 0;
  868.             for (int i = k; i < nR; ++i) {
  869.                 gamma += weightedJacobian[i][pk] * y[i];
  870.             }
  871.             gamma *= beta[pk];
  872.             for (int i = k; i < nR; ++i) {
  873.                 y[i] -= gamma * weightedJacobian[i][pk];
  874.             }
  875.         }
  876.     }

  877.     /**
  878.      * @throws MathUnsupportedOperationException if bounds were passed to the
  879.      * {@link #optimize(OptimizationData[]) optimize} method.
  880.      */
  881.     private void checkParameters() {
  882.         if (getLowerBound() != null ||
  883.             getUpperBound() != null) {
  884.             throw new MathUnsupportedOperationException(LocalizedFormats.CONSTRAINT);
  885.         }
  886.     }
  887. }