SumOfCubedDeviations.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. /**
  19.  * Computes the sum of cubed deviations from the sample mean. This
  20.  * statistic is related to the third moment.
  21.  *
  22.  * <p>Uses a recursive updating formula as defined in Manca and Marin (2010), equation 10.
  23.  * Note that the denominator in the third term in that equation has been corrected to
  24.  * \( (N_1 + N_2)^2 \). Two sum of cubed deviations (SC) can be combined using:
  25.  *
  26.  * <p>\[ SC(X) = {SC}_1 + {SC}_2 + \frac{3(m_1 - m_2)({s_1}^2 - {s_2}^2) N_1 N_2}{N_1 + N_2}
  27.  *                               + \frac{(m_1 - m_2)^3((N_2 - N_1) N_1 N_2}{(N_1 + N_2)^2} \]
  28.  *
  29.  * <p>where \( N \) is the group size, \( m \) is the mean, and \( s^2 \) is the biased variance
  30.  * such that \( s^2 * N \) is the sum of squared deviations from the mean. Note the term
  31.  * \( ({s_1}^2 - {s_2}^2) N_1 N_2 == (ss_1 * N_2 - ss_2 * N_1 \) where \( ss \) is the sum
  32.  * of square deviations.
  33.  *
  34.  * <p>If \( N_1 \) is size 1 this reduces to:
  35.  *
  36.  * <p>\[ SC_{N+1} = {SC}_N + \frac{3(x - m) -s^2 N}{N + 1}
  37.  *                         + \frac{(x - m)^3((N - 1) N}{(N + 1)^2} \]
  38.  *
  39.  * <p>where \( s^2 N \) is the sum of squared deviations.
  40.  * This updating formula is identical to that used in
  41.  * {@code org.apache.commons.math3.stat.descriptive.moment.ThirdMoment}.
  42.  *
  43.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  44.  * This implementation does not check for overflow of the count.
  45.  *
  46.  * <p><strong>Note that this implementation is not synchronized.</strong> If
  47.  * multiple threads access an instance of this class concurrently, and at least
  48.  * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
  49.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  50.  *
  51.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  52.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  53.  * as {@code accumulator} and {@code combiner} functions of
  54.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  55.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  56.  * provides the necessary partitioning, isolation, and merging of results for
  57.  * safe and efficient parallel execution.
  58.  *
  59.  * <p>References:
  60.  * <ul>
  61.  *   <li>Manca and Marin (2020)
  62.  *       Decomposition of the Sum of Cubes, the Sum Raised to the
  63.  *       Power of Four and Codeviance.
  64.  *       Applied Mathematics, 11, 1013-1020.
  65.  *       <a href="https://doi.org/10.4236/am.2020.1110067">doi: 10.4236/am.2020.1110067</a>
  66.  * </ul>
  67.  *
  68.  * @since 1.1
  69.  */
  70. class SumOfCubedDeviations extends SumOfSquaredDeviations {
  71.     /** 2, the length limit where the sum-of-cubed deviations is zero. */
  72.     static final int LENGTH_TWO = 2;

  73.     /** Sum of cubed deviations of the values that have been added. */
  74.     protected double sumCubedDev;

  75.     /**
  76.      * Create an instance.
  77.      */
  78.     SumOfCubedDeviations() {
  79.         // No-op
  80.     }

  81.     /**
  82.      * Copy constructor.
  83.      *
  84.      * @param source Source to copy.
  85.      */
  86.     SumOfCubedDeviations(SumOfCubedDeviations source) {
  87.         super(source);
  88.         sumCubedDev = source.sumCubedDev;
  89.     }

  90.     /**
  91.      * Create an instance with the given sum of cubed and squared deviations.
  92.      *
  93.      * @param sc Sum of cubed deviations.
  94.      * @param ss Sum of squared deviations.
  95.      */
  96.     SumOfCubedDeviations(double sc, SumOfSquaredDeviations ss) {
  97.         super(ss);
  98.         this.sumCubedDev = sc;
  99.     }

  100.     /**
  101.      * Create an instance with the given sum of cubed and squared deviations,
  102.      * and first moment.
  103.      *
  104.      * @param sc Sum of cubed deviations.
  105.      * @param ss Sum of squared deviations.
  106.      * @param m1 First moment.
  107.      * @param n Count of values.
  108.      */
  109.     SumOfCubedDeviations(double sc, double ss, double m1, long n) {
  110.         super(ss, m1, n);
  111.         this.sumCubedDev = sc;
  112.     }

  113.     /**
  114.      * Returns an instance populated using the input {@code values}.
  115.      *
  116.      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
  117.      * different from this instance.
  118.      *
  119.      * @param values Values.
  120.      * @return {@code SumOfCubedDeviations} instance.
  121.      */
  122.     static SumOfCubedDeviations of(double... values) {
  123.         if (values.length == 0) {
  124.             return new SumOfCubedDeviations();
  125.         }
  126.         return create(SumOfSquaredDeviations.of(values), values);
  127.     }

  128.     /**
  129.      * Creates the sum of cubed deviations.
  130.      *
  131.      * <p>Uses the provided {@code sum} to create the first moment.
  132.      * This method is used by {@link DoubleStatistics} using a sum that can be reused
  133.      * for the {@link Sum} statistic.
  134.      *
  135.      * @param sum Sum of the values.
  136.      * @param values Values.
  137.      * @return {@code SumOfCubedDeviations} instance.
  138.      */
  139.     static SumOfCubedDeviations create(org.apache.commons.numbers.core.Sum sum, double[] values) {
  140.         if (values.length == 0) {
  141.             return new SumOfCubedDeviations();
  142.         }
  143.         return create(SumOfSquaredDeviations.create(sum, values), values);
  144.     }

  145.     /**
  146.      * Creates the sum of cubed deviations.
  147.      *
  148.      * @param ss Sum of squared deviations.
  149.      * @param values Values.
  150.      * @return {@code SumOfCubedDeviations} instance.
  151.      */
  152.     private static SumOfCubedDeviations create(SumOfSquaredDeviations ss, double[] values) {
  153.         // Edge cases
  154.         final double xbar = ss.getFirstMoment();
  155.         if (!Double.isFinite(xbar)) {
  156.             return new SumOfCubedDeviations(Double.NaN, ss);
  157.         }
  158.         if (!Double.isFinite(ss.sumSquaredDev)) {
  159.             // Note: If the sum-of-squared (SS) overflows then the same deviations when cubed
  160.             // will overflow. The *smallest* deviation to overflow SS is a full-length array of
  161.             // +/- values around a mean of zero, or approximately sqrt(MAX_VALUE / 2^31) = 2.89e149.
  162.             // In this case the sum cubed could be finite due to cancellation
  163.             // but this cannot be computed. Only a small array can be known to be zero.
  164.             return new SumOfCubedDeviations(values.length <= LENGTH_TWO ? 0 : Double.NaN, ss);
  165.         }
  166.         // Compute the sum of cubed deviations.
  167.         double s = 0;
  168.         // n=1: no deviation
  169.         // n=2: the two deviations from the mean are equal magnitude
  170.         // and opposite sign. So the sum-of-cubed deviations is zero.
  171.         if (values.length > LENGTH_TWO) {
  172.             for (final double x : values) {
  173.                 s += pow3(x - xbar);
  174.             }
  175.         }
  176.         return new SumOfCubedDeviations(s, ss);
  177.     }

  178.     /**
  179.      * Returns an instance populated using the input {@code values}.
  180.      *
  181.      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
  182.      * different from this instance.
  183.      *
  184.      * @param values Values.
  185.      * @return {@code SumOfCubedDeviations} instance.
  186.      */
  187.     static SumOfCubedDeviations of(int... values) {
  188.         // Logic shared with the double[] version with int[] lower order moments
  189.         if (values.length == 0) {
  190.             return new SumOfCubedDeviations();
  191.         }
  192.         final IntVariance variance = IntVariance.of(values);
  193.         final double xbar = variance.computeMean();
  194.         final double ss = variance.computeSumOfSquaredDeviations();

  195.         double sc = 0;
  196.         if (values.length > LENGTH_TWO) {
  197.             for (final double x : values) {
  198.                 sc += pow3(x - xbar);
  199.             }
  200.         }
  201.         return new SumOfCubedDeviations(sc, ss, xbar, values.length);
  202.     }

  203.     /**
  204.      * Returns an instance populated using the input {@code values}.
  205.      *
  206.      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
  207.      * different from this instance.
  208.      *
  209.      * @param values Values.
  210.      * @return {@code SumOfCubedDeviations} instance.
  211.      */
  212.     static SumOfCubedDeviations of(long... values) {
  213.         // Logic shared with the double[] version with long[] lower order moments
  214.         if (values.length == 0) {
  215.             return new SumOfCubedDeviations();
  216.         }
  217.         final LongVariance variance = LongVariance.of(values);
  218.         final double xbar = variance.computeMean();
  219.         final double ss = variance.computeSumOfSquaredDeviations();

  220.         double sc = 0;
  221.         if (values.length > LENGTH_TWO) {
  222.             for (final double x : values) {
  223.                 sc += pow3(x - xbar);
  224.             }
  225.         }
  226.         return new SumOfCubedDeviations(sc, ss, xbar, values.length);
  227.     }

  228.     /**
  229.      * Compute {@code x^3}.
  230.      * Uses compound multiplication.
  231.      *
  232.      * @param x Value.
  233.      * @return x^3
  234.      */
  235.     private static double pow3(double x) {
  236.         return x * x * x;
  237.     }

  238.     /**
  239.      * Updates the state of the statistic to reflect the addition of {@code value}.
  240.      *
  241.      * @param value Value.
  242.      */
  243.     @Override
  244.     public void accept(double value) {
  245.         // Require current s^2 * N == sum-of-square deviations
  246.         final double ss = sumSquaredDev;
  247.         final double np = n;
  248.         super.accept(value);
  249.         // Terms are arranged so that values that may be zero
  250.         // (np, ss) are first. This will cancel any overflow in
  251.         // multiplication of later terms (nDev * 3 and nDev^2).
  252.         // This handles initialisation when np in {0, 1) to zero
  253.         // for any deviation (e.g. series MAX_VALUE, -MAX_VALUE).
  254.         // Note: account for the half-deviation representation by scaling by 6=3*2; 8=2^3
  255.         sumCubedDev = sumCubedDev -
  256.             ss * nDev * 6 +
  257.             (np - 1.0) * np * nDev * nDev * dev * 8;
  258.     }

  259.     /**
  260.      * Gets the sum of cubed deviations of all input values.
  261.      *
  262.      * <p>Note that the sum is subject to cancellation of potentially large
  263.      * positive and negative terms. A non-finite result may be returned
  264.      * due to intermediate overflow when the exact result may be a representable
  265.      * {@code double}.
  266.      *
  267.      * <p>Note: Any non-finite result should be considered a failed computation.
  268.      * The result is returned as computed and not consolidated to a single NaN.
  269.      * This is done for testing purposes to allow the result to be reported.
  270.      * In particular the sign of an infinity may not indicate the direction
  271.      * of the asymmetry (if any), only the direction of the first overflow in the
  272.      * computation. In the event of further overflow of a term to an opposite signed
  273.      * infinity the sum will be {@code NaN}.
  274.      *
  275.      * @return sum of cubed deviations of all values.
  276.      */
  277.     double getSumOfCubedDeviations() {
  278.         return Double.isFinite(getFirstMoment()) ? sumCubedDev : Double.NaN;
  279.     }

  280.     /**
  281.      * Combines the state of another {@code SumOfCubedDeviations} into this one.
  282.      *
  283.      * @param other Another {@code SumOfCubedDeviations} to be combined.
  284.      * @return {@code this} instance after combining {@code other}.
  285.      */
  286.     SumOfCubedDeviations combine(SumOfCubedDeviations other) {
  287.         if (n == 0) {
  288.             sumCubedDev = other.sumCubedDev;
  289.         } else if (other.n != 0) {
  290.             // Avoid overflow to compute the difference.
  291.             // This allows any samples of size n=1 to be combined as their SS=0.
  292.             // The result is a SC=0 for the combined n=2.
  293.             final double halfDiffOfMean = getFirstMomentHalfDifference(other);
  294.             sumCubedDev += other.sumCubedDev;
  295.             // Add additional terms that do not cancel to zero
  296.             if (halfDiffOfMean != 0) {
  297.                 final double n1 = n;
  298.                 final double n2 = other.n;
  299.                 if (n1 == n2) {
  300.                     // Optimisation where sizes are equal in double-precision.
  301.                     // This is of use in JDK streams as spliterators use a divide by two
  302.                     // strategy for parallel streams.
  303.                     sumCubedDev += (sumSquaredDev - other.sumSquaredDev) * halfDiffOfMean * 3;
  304.                 } else {
  305.                     final double n1n2 = n1 + n2;
  306.                     final double dm = 2 * (halfDiffOfMean / n1n2);
  307.                     sumCubedDev += (sumSquaredDev * n2 - other.sumSquaredDev * n1) * dm * 3 +
  308.                                    (n2 - n1) * (n1 * n2) * pow3(dm) * n1n2;
  309.                 }
  310.             }
  311.         }
  312.         super.combine(other);
  313.         return this;
  314.     }
  315. }