lsq_solver.dart 5.55 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 7
import 'dart:math' as math;
import 'dart:typed_data';
8

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

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

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

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

  final int _length;

  final List<double> _elements;
28

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

Ian Hickson's avatar
Ian Hickson committed
34
  double operator *(_Vector a) {
35
    double result = 0.0;
Ian Hickson's avatar
Ian Hickson committed
36
    for (int i = 0; i < _length; i += 1)
37 38 39 40 41 42 43
      result += this[i] * a[i];
    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) {
Florian Loitsch's avatar
Florian Loitsch committed
103
    if (degree > x.length) // Not enough data to fit a curve.
104 105
      return null;

106
    final PolynomialFit result = PolynomialFit(degree);
107

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

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

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

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

135
      final double norm = q.getRow(j).norm();
136
      if (norm < precisionErrorTolerance) {
Florian Loitsch's avatar
Florian Loitsch committed
137
        // Vectors are linearly dependent or zero so no solution.
138 139 140
        return null;
      }

141
      final double inverseNorm = 1.0 / norm;
Ian Hickson's avatar
Ian Hickson committed
142
      for (int h = 0; h < m; h += 1)
143
        q.set(j, h, q.get(j, h) * inverseNorm);
Ian Hickson's avatar
Ian Hickson committed
144
      for (int i = 0; i < n; i += 1)
145
        r.set(j, i, i < j ? 0.0 : q.getRow(j) * a.getRow(i));
146 147
    }

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

160
    // Calculate the coefficient of determination (confidence) as:
Ian Hickson's avatar
Ian Hickson committed
161 162
    //   1 - (sumSquaredError / sumSquaredTotal)
    // ...where sumSquaredError is the residual sum of squares (variance of the
163 164 165
    // error), and sumSquaredTotal is the total sum of squares (variance of the
    // data) where each has been weighted.
    double yMean = 0.0;
Ian Hickson's avatar
Ian Hickson committed
166
    for (int h = 0; h < m; h += 1)
167 168
      yMean += y[h];
    yMean /= m;
169

170 171
    double sumSquaredError = 0.0;
    double sumSquaredTotal = 0.0;
Ian Hickson's avatar
Ian Hickson committed
172
    for (int h = 0; h < m; h += 1) {
173
      double term = 1.0;
Ian Hickson's avatar
Ian Hickson committed
174 175
      double err = y[h] - result.coefficients[0];
      for (int i = 1; i < n; i += 1) {
176
        term *= x[h];
177
        err -= term * result.coefficients[i];
178
      }
179
      sumSquaredError += w[h] * w[h] * err * err;
Ian Hickson's avatar
Ian Hickson committed
180
      final double v = y[h] - yMean;
181
      sumSquaredTotal += w[h] * w[h] * v * v;
182 183
    }

184
    result.confidence = sumSquaredTotal <= precisionErrorTolerance ? 1.0 :
Ian Hickson's avatar
Ian Hickson committed
185
                          1.0 - (sumSquaredError / sumSquaredTotal);
186 187 188 189 190

    return result;
  }

}