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    *      https://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.hipparchus.fitting.ransac;
18  
19  import java.util.List;
20  import java.util.stream.IntStream;
21  import org.hipparchus.exception.LocalizedCoreFormats;
22  import org.hipparchus.exception.MathIllegalArgumentException;
23  import org.hipparchus.linear.Array2DRowRealMatrix;
24  import org.hipparchus.linear.ArrayRealVector;
25  import org.hipparchus.linear.RealMatrix;
26  import org.hipparchus.linear.RealVector;
27  import org.hipparchus.linear.SingularValueDecomposition;
28  import org.hipparchus.util.FastMath;
29  
30  /**
31   * Fitter for polynomial model.
32   * @since 4.1
33   */
34  public class PolynomialModelFitter implements IModelFitter<PolynomialModelFitter.Model> {
35  
36      /** Class representing the polynomial model to fit. */
37      public static final class Model {
38  
39          /** Coefficients of the polynomial model. */
40          private final double[] coefficients;
41  
42          /**
43           * Constructor.
44           * @param coefficients coefficients of the polynomial model
45           */
46          public Model(final double[] coefficients) {
47              this.coefficients = coefficients.clone();
48          }
49  
50          /**
51           * Predicts the model value for the input point.
52           * @param x point
53           * @return the model value for the given point
54           */
55          public double predict(final double x) {
56              return IntStream.range(0, coefficients.length).mapToDouble(i -> coefficients[i] * FastMath.pow(x, i)).sum();
57          }
58  
59          /**
60           * Get the coefficients of the polynomial model.
61           * <p>
62           * The coefficients are sort by degree.
63           * For instance, for a quadratic equation the coefficients are as followed:
64           * <code>y = coefficients[2] * x * x + coefficients[1] * x + coefficients[0]</code>
65           * </p>
66           * @return the coefficients of the polynomial model
67           */
68          public double[] getCoefficients() {
69              return coefficients.clone();
70          }
71      }
72  
73      /** Degree of the polynomial to fit. */
74      private final int degree;
75  
76      /**
77       * Constructor.
78       * @param degree degree of the polynomial to fit
79       */
80      public PolynomialModelFitter(final int degree) {
81          if (degree < 1) {
82              throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL, degree, 1);
83          }
84          this.degree = degree;
85      }
86  
87      /** {@inheritDoc} */
88      @Override
89      public Model fitModel(final List<Fittable> points) {
90          // Reference: Wikipedia page "Polynomial regression"
91          final int size = points.size();
92          checkSampleSize(size);
93  
94          // Fill the data
95          final double[][] x = new double[size][degree + 1];
96          final double[] y = new double[size];
97          for (int i = 0; i < size; i++) {
98              final double[] point = points.get(i).getPoint();
99              final double currentX = point[0];
100             final double currentY = point[1];
101             double value = 1.0;
102             for (int j = 0; j <= degree; j++) {
103                 x[i][j] = value;
104                 value *= currentX;
105             }
106             y[i] = currentY;
107         }
108 
109         // Computes (X^T.X)^-1 X^T.Y to determine the coefficients "C" of the polynomial (Y = X.C)
110         final RealMatrix matrixX = new Array2DRowRealMatrix(x);
111         final RealVector matrixY = new ArrayRealVector(y);
112         final RealMatrix matrixXTranspose = matrixX.transpose();
113         final RealMatrix xTx = matrixXTranspose.multiply(matrixX);
114         final RealVector xTy = matrixXTranspose.operate(matrixY);
115         final RealVector coefficients = new SingularValueDecomposition(xTx).getSolver().solve(xTy);
116         return new Model(coefficients.toArray());
117     }
118 
119     /** {@inheritDoc}. */
120     @Override
121     public double computeModelError(final Model model, final Fittable point) {
122         return FastMath.abs(point.getPoint()[1] - model.predict(point.getPoint()[0]));
123     }
124 
125     /**
126      * Verifies that the size of the set of observed data is consistent with the degree of the polynomial to fit.
127      * @param size size of the set of observed data
128      */
129     private void checkSampleSize(final int size) {
130         if (size < degree + 1) {
131             throw new IllegalArgumentException(String.format("Not enough points to fit polynomial model, at least %d points are required", degree + 1));
132         }
133     }
134 }