GaussNewtonOptimizer.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 org.apache.commons.math3.exception.ConvergenceException;
  19. import org.apache.commons.math3.exception.NullArgumentException;
  20. import org.apache.commons.math3.exception.MathInternalError;
  21. import org.apache.commons.math3.exception.MathUnsupportedOperationException;
  22. import org.apache.commons.math3.exception.util.LocalizedFormats;
  23. import org.apache.commons.math3.linear.ArrayRealVector;
  24. import org.apache.commons.math3.linear.BlockRealMatrix;
  25. import org.apache.commons.math3.linear.DecompositionSolver;
  26. import org.apache.commons.math3.linear.LUDecomposition;
  27. import org.apache.commons.math3.linear.QRDecomposition;
  28. import org.apache.commons.math3.linear.RealMatrix;
  29. import org.apache.commons.math3.linear.SingularMatrixException;
  30. import org.apache.commons.math3.optim.ConvergenceChecker;
  31. import org.apache.commons.math3.optim.PointVectorValuePair;

  32. /**
  33.  * Gauss-Newton least-squares solver.
  34.  * <br/>
  35.  * Constraints are not supported: the call to
  36.  * {@link #optimize(OptimizationData[]) optimize} will throw
  37.  * {@link MathUnsupportedOperationException} if bounds are passed to it.
  38.  *
  39.  * <p>
  40.  * This class solve a least-square problem by solving the normal equations
  41.  * of the linearized problem at each iteration. Either LU decomposition or
  42.  * QR decomposition can be used to solve the normal equations. LU decomposition
  43.  * is faster but QR decomposition is more robust for difficult problems.
  44.  * </p>
  45.  *
  46.  * @since 2.0
  47.  * @deprecated All classes and interfaces in this package are deprecated.
  48.  * The optimizers that were provided here were moved to the
  49.  * {@link org.apache.commons.math3.fitting.leastsquares} package
  50.  * (cf. MATH-1008).
  51.  */
  52. @Deprecated
  53. public class GaussNewtonOptimizer extends AbstractLeastSquaresOptimizer {
  54.     /** Indicator for using LU decomposition. */
  55.     private final boolean useLU;

  56.     /**
  57.      * Simple constructor with default settings.
  58.      * The normal equations will be solved using LU decomposition.
  59.      *
  60.      * @param checker Convergence checker.
  61.      */
  62.     public GaussNewtonOptimizer(ConvergenceChecker<PointVectorValuePair> checker) {
  63.         this(true, checker);
  64.     }

  65.     /**
  66.      * @param useLU If {@code true}, the normal equations will be solved
  67.      * using LU decomposition, otherwise they will be solved using QR
  68.      * decomposition.
  69.      * @param checker Convergence checker.
  70.      */
  71.     public GaussNewtonOptimizer(final boolean useLU,
  72.                                 ConvergenceChecker<PointVectorValuePair> checker) {
  73.         super(checker);
  74.         this.useLU = useLU;
  75.     }

  76.     /** {@inheritDoc} */
  77.     @Override
  78.     public PointVectorValuePair doOptimize() {
  79.         checkParameters();

  80.         final ConvergenceChecker<PointVectorValuePair> checker
  81.             = getConvergenceChecker();

  82.         // Computation will be useless without a checker (see "for-loop").
  83.         if (checker == null) {
  84.             throw new NullArgumentException();
  85.         }

  86.         final double[] targetValues = getTarget();
  87.         final int nR = targetValues.length; // Number of observed data.

  88.         final RealMatrix weightMatrix = getWeight();
  89.         // Diagonal of the weight matrix.
  90.         final double[] residualsWeights = new double[nR];
  91.         for (int i = 0; i < nR; i++) {
  92.             residualsWeights[i] = weightMatrix.getEntry(i, i);
  93.         }

  94.         final double[] currentPoint = getStartPoint();
  95.         final int nC = currentPoint.length;

  96.         // iterate until convergence is reached
  97.         PointVectorValuePair current = null;
  98.         for (boolean converged = false; !converged;) {
  99.             incrementIterationCount();

  100.             // evaluate the objective function and its jacobian
  101.             PointVectorValuePair previous = current;
  102.             // Value of the objective function at "currentPoint".
  103.             final double[] currentObjective = computeObjectiveValue(currentPoint);
  104.             final double[] currentResiduals = computeResiduals(currentObjective);
  105.             final RealMatrix weightedJacobian = computeWeightedJacobian(currentPoint);
  106.             current = new PointVectorValuePair(currentPoint, currentObjective);

  107.             // build the linear problem
  108.             final double[]   b = new double[nC];
  109.             final double[][] a = new double[nC][nC];
  110.             for (int i = 0; i < nR; ++i) {

  111.                 final double[] grad   = weightedJacobian.getRow(i);
  112.                 final double weight   = residualsWeights[i];
  113.                 final double residual = currentResiduals[i];

  114.                 // compute the normal equation
  115.                 final double wr = weight * residual;
  116.                 for (int j = 0; j < nC; ++j) {
  117.                     b[j] += wr * grad[j];
  118.                 }

  119.                 // build the contribution matrix for measurement i
  120.                 for (int k = 0; k < nC; ++k) {
  121.                     double[] ak = a[k];
  122.                     double wgk = weight * grad[k];
  123.                     for (int l = 0; l < nC; ++l) {
  124.                         ak[l] += wgk * grad[l];
  125.                     }
  126.                 }
  127.             }

  128.             // Check convergence.
  129.             if (previous != null) {
  130.                 converged = checker.converged(getIterations(), previous, current);
  131.                 if (converged) {
  132.                     setCost(computeCost(currentResiduals));
  133.                     return current;
  134.                 }
  135.             }

  136.             try {
  137.                 // solve the linearized least squares problem
  138.                 RealMatrix mA = new BlockRealMatrix(a);
  139.                 DecompositionSolver solver = useLU ?
  140.                         new LUDecomposition(mA).getSolver() :
  141.                         new QRDecomposition(mA).getSolver();
  142.                 final double[] dX = solver.solve(new ArrayRealVector(b, false)).toArray();
  143.                 // update the estimated parameters
  144.                 for (int i = 0; i < nC; ++i) {
  145.                     currentPoint[i] += dX[i];
  146.                 }
  147.             } catch (SingularMatrixException e) {
  148.                 throw new ConvergenceException(LocalizedFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM);
  149.             }
  150.         }
  151.         // Must never happen.
  152.         throw new MathInternalError();
  153.     }

  154.     /**
  155.      * @throws MathUnsupportedOperationException if bounds were passed to the
  156.      * {@link #optimize(OptimizationData[]) optimize} method.
  157.      */
  158.     private void checkParameters() {
  159.         if (getLowerBound() != null ||
  160.             getUpperBound() != null) {
  161.             throw new MathUnsupportedOperationException(LocalizedFormats.CONSTRAINT);
  162.         }
  163.     }
  164. }