001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.math;
016
017import static com.google.common.base.Preconditions.checkState;
018import static com.google.common.primitives.Doubles.isFinite;
019import static java.lang.Double.NaN;
020import static java.lang.Double.isNaN;
021
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.primitives.Doubles;
025
026/**
027 * A mutable object which accumulates paired double values (e.g. points on a plane) and tracks some
028 * basic statistics over all the values added so far. This class is not thread safe.
029 *
030 * @author Pete Gillin
031 * @since 20.0
032 */
033@J2ktIncompatible
034@GwtIncompatible
035@ElementTypesAreNonnullByDefault
036public final class PairedStatsAccumulator {
037  /** Creates a new accumulator. */
038  public PairedStatsAccumulator() {}
039
040  // These fields must satisfy the requirements of PairedStats' constructor as well as those of the
041  // stat methods of this class.
042  private final StatsAccumulator xStats = new StatsAccumulator();
043  private final StatsAccumulator yStats = new StatsAccumulator();
044  private double sumOfProductsOfDeltas = 0.0;
045
046  /** Adds the given pair of values to the dataset. */
047  public void add(double x, double y) {
048    // We extend the recursive expression for the one-variable case at Art of Computer Programming
049    // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i.
050    // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i.
051    // We also define the sum of the products of the differences from the means
052    //           C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n
053    // for all n >= 1. Then for all n > 1:
054    //       C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1}
055    // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1}
056    //               = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1}
057    //               = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1}
058    //               = (x_n - X_n) (y_n - Y_{n-1})
059    xStats.add(x);
060    if (isFinite(x) && isFinite(y)) {
061      if (xStats.count() > 1) {
062        sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean());
063      }
064    } else {
065      sumOfProductsOfDeltas = NaN;
066    }
067    yStats.add(y);
068  }
069
070  /**
071   * Adds the given statistics to the dataset, as if the individual values used to compute the
072   * statistics had been added directly.
073   */
074  public void addAll(PairedStats values) {
075    if (values.count() == 0) {
076      return;
077    }
078
079    xStats.addAll(values.xStats());
080    if (yStats.count() == 0) {
081      sumOfProductsOfDeltas = values.sumOfProductsOfDeltas();
082    } else {
083      // This is a generalized version of the calculation in add(double, double) above. Note that
084      // non-finite inputs will have sumOfProductsOfDeltas = NaN, so non-finite values will result
085      // in NaN naturally.
086      sumOfProductsOfDeltas +=
087          values.sumOfProductsOfDeltas()
088              + (values.xStats().mean() - xStats.mean())
089                  * (values.yStats().mean() - yStats.mean())
090                  * values.count();
091    }
092    yStats.addAll(values.yStats());
093  }
094
095  /** Returns an immutable snapshot of the current statistics. */
096  public PairedStats snapshot() {
097    return new PairedStats(xStats.snapshot(), yStats.snapshot(), sumOfProductsOfDeltas);
098  }
099
100  /** Returns the number of pairs in the dataset. */
101  public long count() {
102    return xStats.count();
103  }
104
105  /** Returns an immutable snapshot of the statistics on the {@code x} values alone. */
106  public Stats xStats() {
107    return xStats.snapshot();
108  }
109
110  /** Returns an immutable snapshot of the statistics on the {@code y} values alone. */
111  public Stats yStats() {
112    return yStats.snapshot();
113  }
114
115  /**
116   * Returns the population covariance of the values. The count must be non-zero.
117   *
118   * <p>This is guaranteed to return zero if the dataset contains a single pair of finite values. It
119   * is not guaranteed to return zero when the dataset consists of the same pair of values multiple
120   * times, due to numerical errors.
121   *
122   * <h3>Non-finite values</h3>
123   *
124   * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
125   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
126   *
127   * @throws IllegalStateException if the dataset is empty
128   */
129  public double populationCovariance() {
130    checkState(count() != 0);
131    return sumOfProductsOfDeltas / count();
132  }
133
134  /**
135   * Returns the sample covariance of the values. The count must be greater than one.
136   *
137   * <p>This is not guaranteed to return zero when the dataset consists of the same pair of values
138   * multiple times, due to numerical errors.
139   *
140   * <h3>Non-finite values</h3>
141   *
142   * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
143   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
144   *
145   * @throws IllegalStateException if the dataset is empty or contains a single pair of values
146   */
147  public final double sampleCovariance() {
148    checkState(count() > 1);
149    return sumOfProductsOfDeltas / (count() - 1);
150  }
151
152  /**
153   * Returns the <a href="http://mathworld.wolfram.com/CorrelationCoefficient.html">Pearson's or
154   * product-moment correlation coefficient</a> of the values. The count must greater than one, and
155   * the {@code x} and {@code y} values must both have non-zero population variance (i.e. {@code
156   * xStats().populationVariance() > 0.0 && yStats().populationVariance() > 0.0}). The result is not
157   * guaranteed to be exactly +/-1 even when the data are perfectly (anti-)correlated, due to
158   * numerical errors. However, it is guaranteed to be in the inclusive range [-1, +1].
159   *
160   * <h3>Non-finite values</h3>
161   *
162   * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
163   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
164   *
165   * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or
166   *     either the {@code x} and {@code y} dataset has zero population variance
167   */
168  public final double pearsonsCorrelationCoefficient() {
169    checkState(count() > 1);
170    if (isNaN(sumOfProductsOfDeltas)) {
171      return NaN;
172    }
173    double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas();
174    double ySumOfSquaresOfDeltas = yStats.sumOfSquaresOfDeltas();
175    checkState(xSumOfSquaresOfDeltas > 0.0);
176    checkState(ySumOfSquaresOfDeltas > 0.0);
177    // The product of two positive numbers can be zero if the multiplication underflowed. We
178    // force a positive value by effectively rounding up to MIN_VALUE.
179    double productOfSumsOfSquaresOfDeltas =
180        ensurePositive(xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas);
181    return ensureInUnitRange(sumOfProductsOfDeltas / Math.sqrt(productOfSumsOfSquaresOfDeltas));
182  }
183
184  /**
185   * Returns a linear transformation giving the best fit to the data according to <a
186   * href="http://mathworld.wolfram.com/LeastSquaresFitting.html">Ordinary Least Squares linear
187   * regression</a> of {@code y} as a function of {@code x}. The count must be greater than one, and
188   * either the {@code x} or {@code y} data must have a non-zero population variance (i.e. {@code
189   * xStats().populationVariance() > 0.0 || yStats().populationVariance() > 0.0}). The result is
190   * guaranteed to be horizontal if there is variance in the {@code x} data but not the {@code y}
191   * data, and vertical if there is variance in the {@code y} data but not the {@code x} data.
192   *
193   * <p>This fit minimizes the root-mean-square error in {@code y} as a function of {@code x}. This
194   * error is defined as the square root of the mean of the squares of the differences between the
195   * actual {@code y} values of the data and the values predicted by the fit for the {@code x}
196   * values (i.e. it is the square root of the mean of the squares of the vertical distances between
197   * the data points and the best fit line). For this fit, this error is a fraction {@code sqrt(1 -
198   * R*R)} of the population standard deviation of {@code y}, where {@code R} is the Pearson's
199   * correlation coefficient (as given by {@link #pearsonsCorrelationCoefficient()}).
200   *
201   * <p>The corresponding root-mean-square error in {@code x} as a function of {@code y} is a
202   * fraction {@code sqrt(1/(R*R) - 1)} of the population standard deviation of {@code x}. This fit
203   * does not normally minimize that error: to do that, you should swap the roles of {@code x} and
204   * {@code y}.
205   *
206   * <h3>Non-finite values</h3>
207   *
208   * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
209   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link
210   * LinearTransformation#forNaN()}.
211   *
212   * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or
213   *     both the {@code x} and {@code y} dataset have zero population variance
214   */
215  public final LinearTransformation leastSquaresFit() {
216    checkState(count() > 1);
217    if (isNaN(sumOfProductsOfDeltas)) {
218      return LinearTransformation.forNaN();
219    }
220    double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas();
221    if (xSumOfSquaresOfDeltas > 0.0) {
222      if (yStats.sumOfSquaresOfDeltas() > 0.0) {
223        return LinearTransformation.mapping(xStats.mean(), yStats.mean())
224            .withSlope(sumOfProductsOfDeltas / xSumOfSquaresOfDeltas);
225      } else {
226        return LinearTransformation.horizontal(yStats.mean());
227      }
228    } else {
229      checkState(yStats.sumOfSquaresOfDeltas() > 0.0);
230      return LinearTransformation.vertical(xStats.mean());
231    }
232  }
233
234  private double ensurePositive(double value) {
235    if (value > 0.0) {
236      return value;
237    } else {
238      return Double.MIN_VALUE;
239    }
240  }
241
242  private static double ensureInUnitRange(double value) {
243    return Doubles.constrainToRange(value, -1.0, 1.0);
244  }
245}