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

  77.     /**
  78.      * Create an instance.
  79.      */
  80.     SumOfFourthDeviations() {
  81.         // No-op
  82.     }

  83.     /**
  84.      * Create an instance with the given sum of fourth and squared deviations.
  85.      *
  86.      * @param sq Sum of fourth (quad) deviations.
  87.      * @param sc Sum of fourth deviations.
  88.      */
  89.     private SumOfFourthDeviations(double sq, SumOfCubedDeviations sc) {
  90.         super(sc);
  91.         this.sumFourthDev = sq;
  92.     }

  93.     /**
  94.      * Create an instance with the given sum of cubed and squared deviations,
  95.      * and first moment.
  96.      *
  97.      * @param sq Sum of fouth deviations.
  98.      * @param sc Sum of cubed deviations.
  99.      * @param ss Sum of squared deviations.
  100.      * @param m1 First moment.
  101.      * @param n Count of values.
  102.      */
  103.     private SumOfFourthDeviations(double sq, double sc, double ss, double m1, long n) {
  104.         super(sc, ss, m1, n);
  105.         this.sumFourthDev = sq;
  106.     }

  107.     /**
  108.      * Returns an instance populated using the input {@code values}.
  109.      *
  110.      * <p>Note: {@code SumOfFourthDeviations} computed using {@link #accept accept} may be
  111.      * different from this instance.
  112.      *
  113.      * @param values Values.
  114.      * @return {@code SumOfFourthDeviations} instance.
  115.      */
  116.     static SumOfFourthDeviations of(double... values) {
  117.         if (values.length == 0) {
  118.             return new SumOfFourthDeviations();
  119.         }
  120.         return create(SumOfCubedDeviations.of(values), values);
  121.     }

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

  139.     /**
  140.      * Creates the sum of fourth deviations.
  141.      *
  142.      * @param sc Sum of cubed deviations.
  143.      * @param values Values.
  144.      * @return {@code SumOfFourthDeviations} instance.
  145.      */
  146.     private static SumOfFourthDeviations create(SumOfCubedDeviations sc, double[] values) {
  147.         // Edge cases
  148.         final double xbar = sc.getFirstMoment();
  149.         if (!Double.isFinite(xbar) ||
  150.             !Double.isFinite(sc.sumSquaredDev) ||
  151.             !Double.isFinite(sc.sumCubedDev)) {
  152.             // Overflow computing lower order deviations will overflow
  153.             return new SumOfFourthDeviations(Double.NaN, sc);
  154.         }
  155.         // Compute the sum of fourth (quad) deviations.
  156.         // Note: This handles n=1.
  157.         double s = 0;
  158.         for (final double x : values) {
  159.             s += pow4(x - xbar);
  160.         }
  161.         return new SumOfFourthDeviations(s, sc);
  162.     }

  163.     /**
  164.      * Compute {@code x^4}.
  165.      * Uses compound multiplication.
  166.      *
  167.      * @param x Value.
  168.      * @return x^4
  169.      */
  170.     private static double pow4(double x) {
  171.         final double x2 = x * x;
  172.         return x2 * x2;
  173.     }

  174.     /**
  175.      * Returns an instance populated using the input {@code values}.
  176.      *
  177.      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
  178.      * different from this instance.
  179.      *
  180.      * @param values Values.
  181.      * @return {@code SumOfCubedDeviations} instance.
  182.      */
  183.     static SumOfFourthDeviations of(int... values) {
  184.         // Logic shared with the double[] version with int[] lower order moments
  185.         if (values.length == 0) {
  186.             return new SumOfFourthDeviations();
  187.         }
  188.         final IntVariance variance = IntVariance.of(values);
  189.         final double xbar = variance.computeMean();
  190.         final double ss = variance.computeSumOfSquaredDeviations();
  191.         // Unlike the double[] case, overflow/NaN is not possible:
  192.         // (max value)^4 times max array length ~ (2^31)^4 * 2^31 ~ 2^155.
  193.         // Compute sum of cubed and fourth deviations together.
  194.         double sc = 0;
  195.         double sq = 0;
  196.         for (final double y : values) {
  197.             final double x = y - xbar;
  198.             final double x2 = x * x;
  199.             sc += x2 * x;
  200.             sq += x2 * x2;
  201.         }
  202.         // Edge case to avoid floating-point error for zero
  203.         if (values.length <= LENGTH_TWO) {
  204.             sc = 0;
  205.         }
  206.         return new SumOfFourthDeviations(sq, sc, ss, xbar, values.length);
  207.     }

  208.     /**
  209.      * Returns an instance populated using the input {@code values}.
  210.      *
  211.      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
  212.      * different from this instance.
  213.      *
  214.      * @param values Values.
  215.      * @return {@code SumOfCubedDeviations} instance.
  216.      */
  217.     static SumOfFourthDeviations of(long... values) {
  218.         // Logic shared with the double[] version with long[] lower order moments
  219.         if (values.length == 0) {
  220.             return new SumOfFourthDeviations();
  221.         }
  222.         final LongVariance variance = LongVariance.of(values);
  223.         final double xbar = variance.computeMean();
  224.         final double ss = variance.computeSumOfSquaredDeviations();
  225.         // Unlike the double[] case, overflow/NaN is not possible:
  226.         // (max value)^4 times max array length ~ (2^63)^4 * 2^31 ~ 2^283.
  227.         // Compute sum of cubed and fourth deviations together.
  228.         double sc = 0;
  229.         double sq = 0;
  230.         for (final double y : values) {
  231.             final double x = y - xbar;
  232.             final double x2 = x * x;
  233.             sc += x2 * x;
  234.             sq += x2 * x2;
  235.         }
  236.         // Edge case to avoid floating-point error for zero
  237.         if (values.length <= LENGTH_TWO) {
  238.             sc = 0;
  239.         }
  240.         return new SumOfFourthDeviations(sq, sc, ss, xbar, values.length);
  241.     }

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

  268.     /**
  269.      * Gets the sum of fourth deviations of all input values.
  270.      *
  271.      * <p>Note that the result should be positive. However the updating sum is subject to
  272.      * cancellation of potentially large positive and negative terms. Overflow of these
  273.      * terms can result in a sum of opposite signed infinities and a {@code NaN} result
  274.      * for finite input values where the correct result is positive infinity.
  275.      *
  276.      * <p>Note: Any non-finite result should be considered a failed computation. The
  277.      * result is returned as computed and not consolidated to a single NaN. This is done
  278.      * for testing purposes to allow the result to be reported. It is possible to track
  279.      * input values to finite/non-finite (e.g. using bit mask manipulation of the exponent
  280.      * field). However this statistic in currently used in the kurtosis and in the case
  281.      * of failed computation distinguishing a non-finite result is not useful.
  282.      *
  283.      * @return sum of fourth deviations of all values.
  284.      */
  285.     double getSumOfFourthDeviations() {
  286.         return Double.isFinite(getFirstMoment()) ? sumFourthDev : Double.NaN;
  287.     }

  288.     /**
  289.      * Combines the state of another {@code SumOfFourthDeviations} into this one.
  290.      *
  291.      * @param other Another {@code SumOfFourthDeviations} to be combined.
  292.      * @return {@code this} instance after combining {@code other}.
  293.      */
  294.     SumOfFourthDeviations combine(SumOfFourthDeviations other) {
  295.         if (n == 0) {
  296.             sumFourthDev = other.sumFourthDev;
  297.         } else if (other.n != 0) {
  298.             // Avoid overflow to compute the difference.
  299.             final double halfDiffOfMean = getFirstMomentHalfDifference(other);
  300.             sumFourthDev += other.sumFourthDev;
  301.             // Add additional terms that do not cancel to zero
  302.             if (halfDiffOfMean != 0) {
  303.                 final double n1 = n;
  304.                 final double n2 = other.n;
  305.                 if (n1 == n2) {
  306.                     // Optimisation where sizes are equal in double-precision.
  307.                     // This is of use in JDK streams as spliterators use a divide by two
  308.                     // strategy for parallel streams.
  309.                     // Note: (n1 * n2) * ((n1+n2)^2 - 3 * (n1 * n2)) == n^4
  310.                     sumFourthDev +=
  311.                         (sumCubedDev - other.sumCubedDev) * halfDiffOfMean * 4 +
  312.                         (sumSquaredDev + other.sumSquaredDev) * (halfDiffOfMean * halfDiffOfMean) * 6 +
  313.                         pow4(halfDiffOfMean) * n1 * 2;
  314.                 } else {
  315.                     final double n1n2 = n1 + n2;
  316.                     final double dm = 2 * (halfDiffOfMean / n1n2);
  317.                     // Use the rearrangement for parity with the accept method
  318.                     // n1*n1 - n1*n2 + n2*n2 == (n1+n2)^2 - 3*n1*n2
  319.                     sumFourthDev +=
  320.                         (sumCubedDev * n2 - other.sumCubedDev * n1) * dm * 4 +
  321.                         (n2 * n2 * sumSquaredDev + n1 * n1 * other.sumSquaredDev) * (dm * dm) * 6 +
  322.                         (n1 * n2) * (n1n2 * n1n2 - 3 * (n1 * n2)) * pow4(dm) * n1n2;
  323.                 }
  324.             }
  325.         }
  326.         super.combine(other);
  327.         return this;
  328.     }
  329. }