FirstMoment.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.statistics.descriptive;

  18. import java.util.function.DoubleConsumer;

  19. /**
  20.  * Computes the first moment (arithmetic mean) using the definitional formula:
  21.  *
  22.  * <pre>mean = sum(x_i) / n</pre>
  23.  *
  24.  * <p> To limit numeric errors, the value of the statistic is computed using the
  25.  * following recursive updating algorithm:
  26.  * <ol>
  27.  * <li>Initialize {@code m = } the first value</li>
  28.  * <li>For each additional value, update using <br>
  29.  *   {@code m = m + (new value - m) / (number of observations)}</li>
  30.  * </ol>
  31.  *
  32.  * <p>Returns {@code NaN} if the dataset is empty. Note that
  33.  * {@code NaN} may also be returned if the input includes {@code NaN} and / or infinite
  34.  * values of opposite sign.
  35.  *
  36.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  37.  * This implementation does not check for overflow of the count.
  38.  *
  39.  * <p><strong>Note that this implementation is not synchronized.</strong> If
  40.  * multiple threads access an instance of this class concurrently, and at least
  41.  * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
  42.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  43.  *
  44.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  45.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  46.  * as {@code accumulator} and {@code combiner} functions of
  47.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  48.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  49.  * provides the necessary partitioning, isolation, and merging of results for
  50.  * safe and efficient parallel execution.
  51.  *
  52.  * <p>References:
  53.  * <ul>
  54.  *   <li>Chan, Golub, Levesque (1983)
  55.  *       Algorithms for Computing the Sample Variance.
  56.  *       American Statistician, vol. 37, no. 3, pp. 242-247.
  57.  *   <li>Ling (1974)
  58.  *       Comparison of Several Algorithms for Computing Sample Means and Variances.
  59.  *       Journal of the American Statistical Association, Vol. 69, No. 348, pp. 859-866.
  60.  * </ul>
  61.  *
  62.  * @since 1.1
  63.  */
  64. class FirstMoment implements DoubleConsumer {
  65.     /** The downscale constant. Used to avoid overflow for all finite input. */
  66.     private static final double DOWNSCALE = 0.5;
  67.     /** The rescale constant. */
  68.     private static final double RESCALE = 2;

  69.     /** Count of values that have been added. */
  70.     protected long n;

  71.     /**
  72.      * Half the deviation of most recently added value from the previous first moment.
  73.      * Retained to prevent repeated computation in higher order moments.
  74.      *
  75.      * <p>Note: This is (x - m1) / 2. It is computed as a half value to prevent overflow
  76.      * when computing for any finite value x and m.
  77.      *
  78.      * <p>This value is not used in the {@link #combine(FirstMoment)} method.
  79.      */
  80.     protected double dev;

  81.     /**
  82.      * Half the deviation of most recently added value from the previous first moment,
  83.      * normalized by current sample size. Retained to prevent repeated
  84.      * computation in higher order moments.
  85.      *
  86.      * <p>Note: This is (x - m1) / 2n. It is computed as a half value to prevent overflow
  87.      * when computing for any finite value x and m.
  88.      *
  89.      * Note: This value is not used in the {@link #combine(FirstMoment)} method.
  90.      */
  91.     protected double nDev;

  92.     /** First moment of values that have been added.
  93.      * This is stored as a half value to prevent overflow for any finite input.
  94.      * Benchmarks show this has negligible performance impact. */
  95.     private double m1;

  96.     /**
  97.      * Running sum of values seen so far.
  98.      * This is not used in the computation of mean. Used as a return value for first moment when
  99.      * it is non-finite.
  100.      */
  101.     private double nonFiniteValue;

  102.     /**
  103.      * Create an instance.
  104.      */
  105.     FirstMoment() {
  106.         // No-op
  107.     }

  108.     /**
  109.      * Copy constructor.
  110.      *
  111.      * @param source Source to copy.
  112.      */
  113.     FirstMoment(FirstMoment source) {
  114.         m1 = source.m1;
  115.         n = source.n;
  116.         nonFiniteValue = source.nonFiniteValue;
  117.     }

  118.     /**
  119.      * Create an instance with the given first moment.
  120.      *
  121.      * <p>This constructor is used when creating the moment from a finite sum of values.
  122.      *
  123.      * @param m1 First moment.
  124.      * @param n Count of values.
  125.      */
  126.     FirstMoment(double m1, long n) {
  127.         this.m1 = m1 * DOWNSCALE;
  128.         this.n = n;
  129.     }

  130.     /**
  131.      * Returns an instance populated using the input {@code values}.
  132.      *
  133.      * <p>Note: {@code FirstMoment} computed using {@link #accept} may be different from
  134.      * this instance.
  135.      *
  136.      * @param values Values.
  137.      * @return {@code FirstMoment} instance.
  138.      */
  139.     static FirstMoment of(double... values) {
  140.         if (values.length == 0) {
  141.             return new FirstMoment();
  142.         }
  143.         // In the typical use-case a sum of values will not overflow and
  144.         // is faster than the rolling algorithm
  145.         return create(org.apache.commons.numbers.core.Sum.of(values), values);
  146.     }

  147.     /**
  148.      * Creates the first moment.
  149.      *
  150.      * <p>Uses the provided {@code sum} if finite; otherwise reverts to using the rolling moment
  151.      * to protect from overflow and adds a second pass correction term.
  152.      *
  153.      * <p>This method is used by {@link DoubleStatistics} using a sum that can be reused
  154.      * for the {@link Sum} statistic.
  155.      *
  156.      * @param sum Sum of the values.
  157.      * @param values Values.
  158.      * @return {@code FirstMoment} instance.
  159.      */
  160.     static FirstMoment create(org.apache.commons.numbers.core.Sum sum, double[] values) {
  161.         // Protect against empty values
  162.         if (values.length == 0) {
  163.             return new FirstMoment();
  164.         }

  165.         final double s = sum.getAsDouble();
  166.         if (Double.isFinite(s)) {
  167.             return new FirstMoment(s / values.length, values.length);
  168.         }

  169.         // "Corrected two-pass algorithm"

  170.         // First pass
  171.         final FirstMoment m1 = create(values);
  172.         final double xbar = m1.getFirstMoment();
  173.         if (!Double.isFinite(xbar)) {
  174.             return m1;
  175.         }
  176.         // Second pass
  177.         double correction = 0;
  178.         for (final double x : values) {
  179.             correction += x - xbar;
  180.         }
  181.         // Note: Correction may be infinite
  182.         if (Double.isFinite(correction)) {
  183.             // Down scale the correction to the half representation
  184.             m1.m1 += DOWNSCALE * correction / values.length;
  185.         }
  186.         return m1;
  187.     }

  188.     /**
  189.      * Creates the first moment using a rolling algorithm.
  190.      *
  191.      * <p>This duplicates the algorithm in the {@link #accept(double)} method
  192.      * with optimisations due to the processing of an entire array:
  193.      * <ul>
  194.      *  <li>Avoid updating (unused) class level working variables.
  195.      *  <li>Only computing the non-finite value if required.
  196.      * </ul>
  197.      *
  198.      * @param values Values.
  199.      * @return the first moment
  200.      */
  201.     private static FirstMoment create(double[] values) {
  202.         double m1 = 0;
  203.         int n = 0;
  204.         for (final double x : values) {
  205.             // Downscale to avoid overflow for all finite input
  206.             m1 += (x * DOWNSCALE - m1) / ++n;
  207.         }
  208.         final FirstMoment m = new FirstMoment();
  209.         m.n = n;
  210.         // Note: m1 is already downscaled here
  211.         m.m1 = m1;
  212.         // The non-finite value is only relevant if the data contains inf/nan
  213.         if (!Double.isFinite(m1 * RESCALE)) {
  214.             m.nonFiniteValue = computeNonFiniteValue(values);
  215.         }
  216.         return m;
  217.     }

  218.     /**
  219.      * Compute the result in the event of non-finite values.
  220.      *
  221.      * @param values Values.
  222.      * @return the non-finite result
  223.      */
  224.     private static double computeNonFiniteValue(double[] values) {
  225.         double sum = 0;
  226.         for (final double x : values) {
  227.             // Scaling down values prevents overflow of finites.
  228.             sum += x * Double.MIN_NORMAL;
  229.         }
  230.         return sum;
  231.     }

  232.     /**
  233.      * Updates the state of the statistic to reflect the addition of {@code value}.
  234.      *
  235.      * @param value Value.
  236.      */
  237.     @Override
  238.     public void accept(double value) {
  239.         // "Updating one-pass algorithm"
  240.         // See: Chan et al (1983) Equation 1.3a
  241.         // m_{i+1} = m_i + (x - m_i) / (i + 1)
  242.         // This is modified with scaling to avoid overflow for all finite input.
  243.         // Scaling the input down by a factor of two ensures that the scaling is lossless.
  244.         // Sub-classes must alter their scaling factors when using the computed deviations.

  245.         // Note: Maintain the correct non-finite result.
  246.         // Scaling down values prevents overflow of finites.
  247.         nonFiniteValue += value * Double.MIN_NORMAL;
  248.         // Scale down the input
  249.         dev = value * DOWNSCALE - m1;
  250.         nDev = dev / ++n;
  251.         m1 += nDev;
  252.     }

  253.     /**
  254.      * Gets the first moment of all input values.
  255.      *
  256.      * <p>When no values have been added, the result is {@code NaN}.
  257.      *
  258.      * @return {@code First moment} of all values, if it is finite;
  259.      *         {@code +/-Infinity}, if infinities of the same sign have been encountered;
  260.      *         {@code NaN} otherwise.
  261.      */
  262.     double getFirstMoment() {
  263.         // Scale back to the original magnitude
  264.         final double m = m1 * RESCALE;
  265.         if (Double.isFinite(m)) {
  266.             return n == 0 ? Double.NaN : m;
  267.         }
  268.         // A non-finite value must have been encountered, return nonFiniteValue which represents m1.
  269.         return nonFiniteValue;
  270.     }

  271.     /**
  272.      * Combines the state of another {@code FirstMoment} into this one.
  273.      *
  274.      * @param other Another {@code FirstMoment} to be combined.
  275.      * @return {@code this} instance after combining {@code other}.
  276.      */
  277.     FirstMoment combine(FirstMoment other) {
  278.         nonFiniteValue += other.nonFiniteValue;
  279.         final double mu1 = this.m1;
  280.         final double mu2 = other.m1;
  281.         final long n1 = n;
  282.         final long n2 = other.n;
  283.         n = n1 + n2;
  284.         // Adjust the mean with the weighted difference:
  285.         // m1 = m1 + (m2 - m1) * n2 / (n1 + n2)
  286.         // The half-representation ensures the difference of means is at most MAX_VALUE
  287.         // so the combine can avoid scaling.
  288.         if (n1 == n2) {
  289.             // Optimisation for equal sizes: m1 = (m1 + m2) / 2
  290.             m1 = (mu1 + mu2) * 0.5;
  291.         } else {
  292.             m1 = combine(mu1, mu2, n1, n2);
  293.         }
  294.         return this;
  295.     }

  296.     /**
  297.      * Combine the moments. This method is used to enforce symmetry. It assumes that
  298.      * the two sizes are not identical, and at least one size is non-zero.
  299.      *
  300.      * @param m1 Moment 1.
  301.      * @param m2 Moment 2.
  302.      * @param n1 Size of sample 1.
  303.      * @param n2 Size of sample 2.
  304.      * @return the combined first moment
  305.      */
  306.     private static double combine(double m1, double m2, long n1, long n2) {
  307.         // Note: If either size is zero the weighted difference is zero and
  308.         // the other moment is unchanged.
  309.         return n2 < n1 ?
  310.             m1 + (m2 - m1) * ((double) n2 / (n1 + n2)) :
  311.             m2 + (m1 - m2) * ((double) n1 / (n1 + n2));
  312.     }

  313.     /**
  314.      * Gets the difference of the first moment between {@code this} moment and the
  315.      * {@code other} moment. This is provided for sub-classes.
  316.      *
  317.      * @param other Other moment.
  318.      * @return the difference
  319.      */
  320.     double getFirstMomentDifference(FirstMoment other) {
  321.         // Scale back to the original magnitude
  322.         return (m1 - other.m1) * RESCALE;
  323.     }

  324.     /**
  325.      * Gets the half the difference of the first moment between {@code this} moment and
  326.      * the {@code other} moment. This is provided for sub-classes.
  327.      *
  328.      * @param other Other moment.
  329.      * @return the difference
  330.      */
  331.     double getFirstMomentHalfDifference(FirstMoment other) {
  332.         return m1 - other.m1;
  333.     }
  334. }