lsq_solver.dart 5.62 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5

6
import 'dart:math' as math;
7

8 9
import 'package:flutter/foundation.dart';

10
// TODO(abarth): Consider using vector_math.
11
class _Vector {
12 13 14 15
  _Vector(int size)
    : _offset = 0,
      _length = size,
      _elements = Float64List(size);
16

17
  _Vector.fromVOL(List<double> values, int offset, int length)
18 19 20
    : _offset = offset,
      _length = length,
      _elements = values;
21

Ian Hickson's avatar
Ian Hickson committed
22 23 24 25 26
  final int _offset;

  final int _length;

  final List<double> _elements;
27

Ian Hickson's avatar
Ian Hickson committed
28 29 30 31
  double operator [](int i) => _elements[i + _offset];
  void operator []=(int i, double value) {
    _elements[i + _offset] = value;
  }
32

Ian Hickson's avatar
Ian Hickson committed
33
  double operator *(_Vector a) {
34
    double result = 0.0;
35
    for (int i = 0; i < _length; i += 1) {
36
      result += this[i] * a[i];
37
    }
38 39 40 41 42 43
    return result;
  }

  double norm() => math.sqrt(this * this);
}

44
// TODO(abarth): Consider using vector_math.
45 46
class _Matrix {
  _Matrix(int rows, int cols)
47 48
    : _columns = cols,
      _elements = Float64List(rows * cols);
49

Ian Hickson's avatar
Ian Hickson committed
50 51 52
  final int _columns;
  final List<double> _elements;

53
  double get(int row, int col) => _elements[row * _columns + col];
54
  void set(int row, int col, double value) {
55
    _elements[row * _columns + col] = value;
56 57
  }

58
  _Vector getRow(int row) => _Vector.fromVOL(
59 60
    _elements,
    row * _columns,
61
    _columns,
62
  );
63 64
}

65
/// An nth degree polynomial fit to a dataset.
66
class PolynomialFit {
67 68 69
  /// Creates a polynomial fit of the given degree.
  ///
  /// There are n + 1 coefficients in a fit of degree n.
70
  PolynomialFit(int degree) : coefficients = Float64List(degree + 1);
71

72
  /// The polynomial coefficients of the fit.
73
  final List<double> coefficients;
74 75 76 77

  /// An indicator of the quality of the fit.
  ///
  /// Larger values indicate greater quality.
78
  late double confidence;
79 80
}

81
/// Uses the least-squares algorithm to fit a polynomial to a set of data.
82
class LeastSquaresSolver {
83 84
  /// Creates a least-squares solver.
  ///
85
  /// The [x], [y], and [w] arguments must not be null.
86 87 88
  LeastSquaresSolver(this.x, this.y, this.w)
    : assert(x.length == y.length),
      assert(y.length == w.length);
89

90
  /// The x-coordinates of each data point.
91
  final List<double> x;
92 93

  /// The y-coordinates of each data point.
94
  final List<double> y;
95 96

  /// The weight to use for each data point.
97 98
  final List<double> w;

99
  /// Fits a polynomial of the given degree to the data points.
100 101 102
  ///
  /// When there is not enough data to fit a curve null is returned.
  PolynomialFit? solve(int degree) {
103 104
    if (degree > x.length) {
      // Not enough data to fit a curve.
105
      return null;
106
    }
107

108
    final PolynomialFit result = PolynomialFit(degree);
109

Florian Loitsch's avatar
Florian Loitsch committed
110
    // Shorthands for the purpose of notation equivalence to original C++ code.
111 112 113 114
    final int m = x.length;
    final int n = degree + 1;

    // Expand the X vector to a matrix A, pre-multiplied by the weights.
115
    final _Matrix a = _Matrix(n, m);
Ian Hickson's avatar
Ian Hickson committed
116
    for (int h = 0; h < m; h += 1) {
117
      a.set(0, h, w[h]);
118
      for (int i = 1; i < n; i += 1) {
119
        a.set(i, h, a.get(i - 1, h) * x[h]);
120
      }
121 122 123 124 125
    }

    // Apply the Gram-Schmidt process to A to obtain its QR decomposition.

    // Orthonormal basis, column-major ordVectorer.
126
    final _Matrix q = _Matrix(n, m);
127
    // Upper triangular matrix, row-major order.
128
    final _Matrix r = _Matrix(n, n);
Ian Hickson's avatar
Ian Hickson committed
129
    for (int j = 0; j < n; j += 1) {
130
      for (int h = 0; h < m; h += 1) {
131
        q.set(j, h, a.get(j, h));
132
      }
Ian Hickson's avatar
Ian Hickson committed
133
      for (int i = 0; i < j; i += 1) {
134
        final double dot = q.getRow(j) * q.getRow(i);
135
        for (int h = 0; h < m; h += 1) {
136
          q.set(j, h, q.get(j, h) - dot * q.get(i, h));
137
        }
138 139
      }

140
      final double norm = q.getRow(j).norm();
141
      if (norm < precisionErrorTolerance) {
Florian Loitsch's avatar
Florian Loitsch committed
142
        // Vectors are linearly dependent or zero so no solution.
143 144 145
        return null;
      }

146
      final double inverseNorm = 1.0 / norm;
147
      for (int h = 0; h < m; h += 1) {
148
        q.set(j, h, q.get(j, h) * inverseNorm);
149 150
      }
      for (int i = 0; i < n; i += 1) {
151
        r.set(j, i, i < j ? 0.0 : q.getRow(j) * a.getRow(i));
152
      }
153 154
    }

155
    // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
156
    // We just work from bottom-right to top-left calculating B's coefficients.
157
    final _Vector wy = _Vector(m);
158
    for (int h = 0; h < m; h += 1) {
159
      wy[h] = y[h] * w[h];
160
    }
Ian Hickson's avatar
Ian Hickson committed
161
    for (int i = n - 1; i >= 0; i -= 1) {
162
      result.coefficients[i] = q.getRow(i) * wy;
163
      for (int j = n - 1; j > i; j -= 1) {
164
        result.coefficients[i] -= r.get(i, j) * result.coefficients[j];
165
      }
166
      result.coefficients[i] /= r.get(i, i);
167 168
    }

169
    // Calculate the coefficient of determination (confidence) as:
Ian Hickson's avatar
Ian Hickson committed
170 171
    //   1 - (sumSquaredError / sumSquaredTotal)
    // ...where sumSquaredError is the residual sum of squares (variance of the
172 173 174
    // error), and sumSquaredTotal is the total sum of squares (variance of the
    // data) where each has been weighted.
    double yMean = 0.0;
175
    for (int h = 0; h < m; h += 1) {
176
      yMean += y[h];
177
    }
178
    yMean /= m;
179

180 181
    double sumSquaredError = 0.0;
    double sumSquaredTotal = 0.0;
Ian Hickson's avatar
Ian Hickson committed
182
    for (int h = 0; h < m; h += 1) {
183
      double term = 1.0;
Ian Hickson's avatar
Ian Hickson committed
184 185
      double err = y[h] - result.coefficients[0];
      for (int i = 1; i < n; i += 1) {
186
        term *= x[h];
187
        err -= term * result.coefficients[i];
188
      }
189
      sumSquaredError += w[h] * w[h] * err * err;
Ian Hickson's avatar
Ian Hickson committed
190
      final double v = y[h] - yMean;
191
      sumSquaredTotal += w[h] * w[h] * v * v;
192 193
    }

194
    result.confidence = sumSquaredTotal <= precisionErrorTolerance ? 1.0 :
Ian Hickson's avatar
Ian Hickson committed
195
                          1.0 - (sumSquaredError / sumSquaredTotal);
196 197 198 199 200

    return result;
  }

}