lsq_solver.dart 5.47 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;
import 'dart:typed_data';
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;
Ian Hickson's avatar
Ian Hickson committed
35
    for (int i = 0; i < _length; i += 1)
36 37 38 39 40 41 42
      result += this[i] * a[i];
    return result;
  }

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

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

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

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

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

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

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

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

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

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

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

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

98
  /// Fits a polynomial of the given degree to the data points.
99
  PolynomialFit solve(int degree) {
Florian Loitsch's avatar
Florian Loitsch committed
100
    if (degree > x.length) // Not enough data to fit a curve.
101 102
      return null;

103
    final PolynomialFit result = PolynomialFit(degree);
104

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

    // Expand the X vector to a matrix A, pre-multiplied by the weights.
110
    final _Matrix a = _Matrix(n, m);
Ian Hickson's avatar
Ian Hickson committed
111
    for (int h = 0; h < m; h += 1) {
112
      a.set(0, h, w[h]);
Ian Hickson's avatar
Ian Hickson committed
113
      for (int i = 1; i < n; i += 1)
114 115 116 117 118 119
        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.
120
    final _Matrix q = _Matrix(n, m);
121
    // Upper triangular matrix, row-major order.
122
    final _Matrix r = _Matrix(n, n);
Ian Hickson's avatar
Ian Hickson committed
123 124
    for (int j = 0; j < n; j += 1) {
      for (int h = 0; h < m; h += 1)
125
        q.set(j, h, a.get(j, h));
Ian Hickson's avatar
Ian Hickson committed
126
      for (int i = 0; i < j; i += 1) {
127
        final double dot = q.getRow(j) * q.getRow(i);
Ian Hickson's avatar
Ian Hickson committed
128
        for (int h = 0; h < m; h += 1)
129 130 131
          q.set(j, h, q.get(j, h) - dot * q.get(i, h));
      }

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

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

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

157
    // Calculate the coefficient of determination (confidence) as:
Ian Hickson's avatar
Ian Hickson committed
158 159
    //   1 - (sumSquaredError / sumSquaredTotal)
    // ...where sumSquaredError is the residual sum of squares (variance of the
160 161 162
    // 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
163
    for (int h = 0; h < m; h += 1)
164 165
      yMean += y[h];
    yMean /= m;
166

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

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

    return result;
  }

}