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