View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.math3.optimization;
19  
20  import org.apache.commons.math3.analysis.MultivariateFunction;
21  import org.apache.commons.math3.analysis.MultivariateVectorFunction;
22  import org.apache.commons.math3.exception.DimensionMismatchException;
23  import org.apache.commons.math3.linear.RealMatrix;
24  
25  /** This class converts {@link MultivariateVectorFunction vectorial
26   * objective functions} to {@link MultivariateFunction scalar objective functions}
27   * when the goal is to minimize them.
28   * <p>
29   * This class is mostly used when the vectorial objective function represents
30   * a theoretical result computed from a point set applied to a model and
31   * the models point must be adjusted to fit the theoretical result to some
32   * reference observations. The observations may be obtained for example from
33   * physical measurements whether the model is built from theoretical
34   * considerations.
35   * </p>
36   * <p>
37   * This class computes a possibly weighted squared sum of the residuals, which is
38   * a scalar value. The residuals are the difference between the theoretical model
39   * (i.e. the output of the vectorial objective function) and the observations. The
40   * class implements the {@link MultivariateFunction} interface and can therefore be
41   * minimized by any optimizer supporting scalar objectives functions.This is one way
42   * to perform a least square estimation. There are other ways to do this without using
43   * this converter, as some optimization algorithms directly support vectorial objective
44   * functions.
45   * </p>
46   * <p>
47   * This class support combination of residuals with or without weights and correlations.
48   * </p>
49    *
50   * @see MultivariateFunction
51   * @see MultivariateVectorFunction
52   * @deprecated As of 3.1 (to be removed in 4.0).
53   * @since 2.0
54   */
55  
56  @Deprecated
57  public class LeastSquaresConverter implements MultivariateFunction {
58  
59      /** Underlying vectorial function. */
60      private final MultivariateVectorFunction function;
61  
62      /** Observations to be compared to objective function to compute residuals. */
63      private final double[] observations;
64  
65      /** Optional weights for the residuals. */
66      private final double[] weights;
67  
68      /** Optional scaling matrix (weight and correlations) for the residuals. */
69      private final RealMatrix scale;
70  
71      /** Build a simple converter for uncorrelated residuals with the same weight.
72       * @param function vectorial residuals function to wrap
73       * @param observations observations to be compared to objective function to compute residuals
74       */
75      public LeastSquaresConverter(final MultivariateVectorFunction function,
76                                   final double[] observations) {
77          this.function     = function;
78          this.observations = observations.clone();
79          this.weights      = null;
80          this.scale        = null;
81      }
82  
83      /** Build a simple converter for uncorrelated residuals with the specific weights.
84       * <p>
85       * The scalar objective function value is computed as:
86       * <pre>
87       * objective = &sum;weight<sub>i</sub>(observation<sub>i</sub>-objective<sub>i</sub>)<sup>2</sup>
88       * </pre>
89       * </p>
90       * <p>
91       * Weights can be used for example to combine residuals with different standard
92       * deviations. As an example, consider a residuals array in which even elements
93       * are angular measurements in degrees with a 0.01&deg; standard deviation and
94       * odd elements are distance measurements in meters with a 15m standard deviation.
95       * In this case, the weights array should be initialized with value
96       * 1.0/(0.01<sup>2</sup>) in the even elements and 1.0/(15.0<sup>2</sup>) in the
97       * odd elements (i.e. reciprocals of variances).
98       * </p>
99       * <p>
100      * The array computed by the objective function, the observations array and the
101      * weights array must have consistent sizes or a {@link DimensionMismatchException}
102      * will be triggered while computing the scalar objective.
103      * </p>
104      * @param function vectorial residuals function to wrap
105      * @param observations observations to be compared to objective function to compute residuals
106      * @param weights weights to apply to the residuals
107      * @exception DimensionMismatchException if the observations vector and the weights
108      * vector dimensions do not match (objective function dimension is checked only when
109      * the {@link #value(double[])} method is called)
110      */
111     public LeastSquaresConverter(final MultivariateVectorFunction function,
112                                  final double[] observations, final double[] weights) {
113         if (observations.length != weights.length) {
114             throw new DimensionMismatchException(observations.length, weights.length);
115         }
116         this.function     = function;
117         this.observations = observations.clone();
118         this.weights      = weights.clone();
119         this.scale        = null;
120     }
121 
122     /** Build a simple converter for correlated residuals with the specific weights.
123      * <p>
124      * The scalar objective function value is computed as:
125      * <pre>
126      * objective = y<sup>T</sup>y with y = scale&times;(observation-objective)
127      * </pre>
128      * </p>
129      * <p>
130      * The array computed by the objective function, the observations array and the
131      * the scaling matrix must have consistent sizes or a {@link DimensionMismatchException}
132      * will be triggered while computing the scalar objective.
133      * </p>
134      * @param function vectorial residuals function to wrap
135      * @param observations observations to be compared to objective function to compute residuals
136      * @param scale scaling matrix
137      * @throws DimensionMismatchException if the observations vector and the scale
138      * matrix dimensions do not match (objective function dimension is checked only when
139      * the {@link #value(double[])} method is called)
140      */
141     public LeastSquaresConverter(final MultivariateVectorFunction function,
142                                  final double[] observations, final RealMatrix scale) {
143         if (observations.length != scale.getColumnDimension()) {
144             throw new DimensionMismatchException(observations.length, scale.getColumnDimension());
145         }
146         this.function     = function;
147         this.observations = observations.clone();
148         this.weights      = null;
149         this.scale        = scale.copy();
150     }
151 
152     /** {@inheritDoc} */
153     public double value(final double[] point) {
154         // compute residuals
155         final double[] residuals = function.value(point);
156         if (residuals.length != observations.length) {
157             throw new DimensionMismatchException(residuals.length, observations.length);
158         }
159         for (int i = 0; i < residuals.length; ++i) {
160             residuals[i] -= observations[i];
161         }
162 
163         // compute sum of squares
164         double sumSquares = 0;
165         if (weights != null) {
166             for (int i = 0; i < residuals.length; ++i) {
167                 final double ri = residuals[i];
168                 sumSquares +=  weights[i] * ri * ri;
169             }
170         } else if (scale != null) {
171             for (final double yi : scale.operate(residuals)) {
172                 sumSquares += yi * yi;
173             }
174         } else {
175             for (final double ri : residuals) {
176                 sumSquares += ri * ri;
177             }
178         }
179 
180         return sumSquares;
181     }
182 }