1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
32
33
34 public class PolynomialModelFitter implements IModelFitter<PolynomialModelFitter.Model> {
35
36
37 public static final class Model {
38
39
40 private final double[] coefficients;
41
42
43
44
45
46 public Model(final double[] coefficients) {
47 this.coefficients = coefficients.clone();
48 }
49
50
51
52
53
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
61
62
63
64
65
66
67
68 public double[] getCoefficients() {
69 return coefficients.clone();
70 }
71 }
72
73
74 private final int degree;
75
76
77
78
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
88 @Override
89 public Model fitModel(final List<Fittable> points) {
90
91 final int size = points.size();
92 checkSampleSize(size);
93
94
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
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
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
127
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 }