View Javadoc
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  /**
20   * Computes the sum of cubed deviations from the sample mean. This
21   * statistic is related to the third moment.
22   *
23   * <p>Uses a recursive updating formula as defined in Manca and Marin (2010), equation 10.
24   * Note that the denominator in the third term in that equation has been corrected to
25   * \( (N_1 + N_2)^2 \). Two sum of cubed deviations (SC) can be combined using:
26   *
27   * <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}
28   *                               + \frac{(m_1 - m_2)^3((N_2 - N_1) N_1 N_2}{(N_1 + N_2)^2} \]
29   *
30   * <p>where \( N \) is the group size, \( m \) is the mean, and \( s^2 \) is the biased variance
31   * such that \( s^2 * N \) is the sum of squared deviations from the mean. Note the term
32   * \( ({s_1}^2 - {s_2}^2) N_1 N_2 == (ss_1 * N_2 - ss_2 * N_1 \) where \( ss \) is the sum
33   * of square deviations.
34   *
35   * <p>If \( N_1 \) is size 1 this reduces to:
36   *
37   * <p>\[ SC_{N+1} = {SC}_N + \frac{3(x - m) -s^2 N}{N + 1}
38   *                         + \frac{(x - m)^3((N - 1) N}{(N + 1)^2} \]
39   *
40   * <p>where \( s^2 N \) is the sum of squared deviations.
41   * This updating formula is identical to that used in
42   * {@code org.apache.commons.math3.stat.descriptive.moment.ThirdMoment}.
43   *
44   * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
45   * This implementation does not check for overflow of the count.
46   *
47   * <p><strong>Note that this implementation is not synchronized.</strong> If
48   * multiple threads access an instance of this class concurrently, and at least
49   * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
50   * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
51   *
52   * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
53   * and {@link StatisticAccumulator#combine(StatisticResult) combine}
54   * as {@code accumulator} and {@code combiner} functions of
55   * {@link java.util.stream.Collector Collector} on a parallel stream,
56   * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
57   * provides the necessary partitioning, isolation, and merging of results for
58   * safe and efficient parallel execution.
59   *
60   * <p>References:
61   * <ul>
62   *   <li>Manca and Marin (2020)
63   *       Decomposition of the Sum of Cubes, the Sum Raised to the
64   *       Power of Four and Codeviance.
65   *       Applied Mathematics, 11, 1013-1020.
66   *       <a href="https://doi.org/10.4236/am.2020.1110067">doi: 10.4236/am.2020.1110067</a>
67   * </ul>
68   *
69   * @since 1.1
70   */
71  class SumOfCubedDeviations extends SumOfSquaredDeviations {
72      /** 2, the length limit where the sum-of-cubed deviations is zero. */
73      static final int LENGTH_TWO = 2;
74  
75      /** Sum of cubed deviations of the values that have been added. */
76      protected double sumCubedDev;
77  
78      /**
79       * Create an instance.
80       */
81      SumOfCubedDeviations() {
82          // No-op
83      }
84  
85      /**
86       * Copy constructor.
87       *
88       * @param source Source to copy.
89       */
90      SumOfCubedDeviations(SumOfCubedDeviations source) {
91          super(source);
92          sumCubedDev = source.sumCubedDev;
93      }
94  
95      /**
96       * Create an instance with the given sum of cubed and squared deviations.
97       *
98       * @param sc Sum of cubed deviations.
99       * @param ss Sum of squared deviations.
100      */
101     SumOfCubedDeviations(double sc, SumOfSquaredDeviations ss) {
102         super(ss);
103         this.sumCubedDev = sc;
104     }
105 
106     /**
107      * Create an instance with the given sum of cubed and squared deviations,
108      * and first moment.
109      *
110      * @param sc Sum of cubed deviations.
111      * @param ss Sum of squared deviations.
112      * @param m1 First moment.
113      * @param n Count of values.
114      */
115     SumOfCubedDeviations(double sc, double ss, double m1, long n) {
116         super(ss, m1, n);
117         this.sumCubedDev = sc;
118     }
119 
120     /**
121      * Returns an instance populated using the input {@code values}.
122      *
123      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
124      * different from this instance.
125      *
126      * @param values Values.
127      * @return {@code SumOfCubedDeviations} instance.
128      */
129     static SumOfCubedDeviations of(double... values) {
130         if (values.length == 0) {
131             return new SumOfCubedDeviations();
132         }
133         return create(SumOfSquaredDeviations.of(values), values);
134     }
135 
136     /**
137      * Creates the sum of cubed deviations.
138      *
139      * <p>Uses the provided {@code sum} to create the first moment.
140      * This method is used by {@link DoubleStatistics} using a sum that can be reused
141      * for the {@link Sum} statistic.
142      *
143      * @param sum Sum of the values.
144      * @param values Values.
145      * @return {@code SumOfCubedDeviations} instance.
146      */
147     static SumOfCubedDeviations create(org.apache.commons.numbers.core.Sum sum, double[] values) {
148         if (values.length == 0) {
149             return new SumOfCubedDeviations();
150         }
151         return create(SumOfSquaredDeviations.create(sum, values), values);
152     }
153 
154     /**
155      * Creates the sum of cubed deviations.
156      *
157      * @param ss Sum of squared deviations.
158      * @param values Values.
159      * @return {@code SumOfCubedDeviations} instance.
160      */
161     private static SumOfCubedDeviations create(SumOfSquaredDeviations ss, double[] values) {
162         // Edge cases
163         final double xbar = ss.getFirstMoment();
164         if (!Double.isFinite(xbar)) {
165             return new SumOfCubedDeviations(Double.NaN, ss);
166         }
167         if (!Double.isFinite(ss.sumSquaredDev)) {
168             // Note: If the sum-of-squared (SS) overflows then the same deviations when cubed
169             // will overflow. The *smallest* deviation to overflow SS is a full-length array of
170             // +/- values around a mean of zero, or approximately sqrt(MAX_VALUE / 2^31) = 2.89e149.
171             // In this case the sum cubed could be finite due to cancellation
172             // but this cannot be computed. Only a small array can be known to be zero.
173             return new SumOfCubedDeviations(values.length <= LENGTH_TWO ? 0 : Double.NaN, ss);
174         }
175         // Compute the sum of cubed deviations.
176         double s = 0;
177         // n=1: no deviation
178         // n=2: the two deviations from the mean are equal magnitude
179         // and opposite sign. So the sum-of-cubed deviations is zero.
180         if (values.length > LENGTH_TWO) {
181             for (final double x : values) {
182                 s += pow3(x - xbar);
183             }
184         }
185         return new SumOfCubedDeviations(s, ss);
186     }
187 
188     /**
189      * Returns an instance populated using the input {@code values}.
190      *
191      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
192      * different from this instance.
193      *
194      * @param values Values.
195      * @return {@code SumOfCubedDeviations} instance.
196      */
197     static SumOfCubedDeviations of(int... values) {
198         // Logic shared with the double[] version with int[] lower order moments
199         if (values.length == 0) {
200             return new SumOfCubedDeviations();
201         }
202         final IntVariance variance = IntVariance.of(values);
203         final double xbar = variance.computeMean();
204         final double ss = variance.computeSumOfSquaredDeviations();
205 
206         double sc = 0;
207         if (values.length > LENGTH_TWO) {
208             for (final double x : values) {
209                 sc += pow3(x - xbar);
210             }
211         }
212         return new SumOfCubedDeviations(sc, ss, xbar, values.length);
213     }
214 
215     /**
216      * Returns an instance populated using the input {@code values}.
217      *
218      * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
219      * different from this instance.
220      *
221      * @param values Values.
222      * @return {@code SumOfCubedDeviations} instance.
223      */
224     static SumOfCubedDeviations of(long... values) {
225         // Logic shared with the double[] version with long[] lower order moments
226         if (values.length == 0) {
227             return new SumOfCubedDeviations();
228         }
229         final LongVariance variance = LongVariance.of(values);
230         final double xbar = variance.computeMean();
231         final double ss = variance.computeSumOfSquaredDeviations();
232 
233         double sc = 0;
234         if (values.length > LENGTH_TWO) {
235             for (final double x : values) {
236                 sc += pow3(x - xbar);
237             }
238         }
239         return new SumOfCubedDeviations(sc, ss, xbar, values.length);
240     }
241 
242     /**
243      * Compute {@code x^3}.
244      * Uses compound multiplication.
245      *
246      * @param x Value.
247      * @return x^3
248      */
249     private static double pow3(double x) {
250         return x * x * x;
251     }
252 
253     /**
254      * Updates the state of the statistic to reflect the addition of {@code value}.
255      *
256      * @param value Value.
257      */
258     @Override
259     public void accept(double value) {
260         // Require current s^2 * N == sum-of-square deviations
261         final double ss = sumSquaredDev;
262         final double np = n;
263         super.accept(value);
264         // Terms are arranged so that values that may be zero
265         // (np, ss) are first. This will cancel any overflow in
266         // multiplication of later terms (nDev * 3 and nDev^2).
267         // This handles initialisation when np in {0, 1) to zero
268         // for any deviation (e.g. series MAX_VALUE, -MAX_VALUE).
269         // Note: account for the half-deviation representation by scaling by 6=3*2; 8=2^3
270         sumCubedDev = sumCubedDev -
271             ss * nDev * 6 +
272             (np - 1.0) * np * nDev * nDev * dev * 8;
273     }
274 
275     /**
276      * Gets the sum of cubed deviations of all input values.
277      *
278      * <p>Note that the sum is subject to cancellation of potentially large
279      * positive and negative terms. A non-finite result may be returned
280      * due to intermediate overflow when the exact result may be a representable
281      * {@code double}.
282      *
283      * <p>Note: Any non-finite result should be considered a failed computation.
284      * The result is returned as computed and not consolidated to a single NaN.
285      * This is done for testing purposes to allow the result to be reported.
286      * In particular the sign of an infinity may not indicate the direction
287      * of the asymmetry (if any), only the direction of the first overflow in the
288      * computation. In the event of further overflow of a term to an opposite signed
289      * infinity the sum will be {@code NaN}.
290      *
291      * @return sum of cubed deviations of all values.
292      */
293     double getSumOfCubedDeviations() {
294         return Double.isFinite(getFirstMoment()) ? sumCubedDev : Double.NaN;
295     }
296 
297     /**
298      * Combines the state of another {@code SumOfCubedDeviations} into this one.
299      *
300      * @param other Another {@code SumOfCubedDeviations} to be combined.
301      * @return {@code this} instance after combining {@code other}.
302      */
303     SumOfCubedDeviations combine(SumOfCubedDeviations other) {
304         if (n == 0) {
305             sumCubedDev = other.sumCubedDev;
306         } else if (other.n != 0) {
307             // Avoid overflow to compute the difference.
308             // This allows any samples of size n=1 to be combined as their SS=0.
309             // The result is a SC=0 for the combined n=2.
310             final double halfDiffOfMean = getFirstMomentHalfDifference(other);
311             sumCubedDev += other.sumCubedDev;
312             // Add additional terms that do not cancel to zero
313             if (halfDiffOfMean != 0) {
314                 final double n1 = n;
315                 final double n2 = other.n;
316                 if (n1 == n2) {
317                     // Optimisation where sizes are equal in double-precision.
318                     // This is of use in JDK streams as spliterators use a divide by two
319                     // strategy for parallel streams.
320                     sumCubedDev += (sumSquaredDev - other.sumSquaredDev) * halfDiffOfMean * 3;
321                 } else {
322                     final double n1n2 = n1 + n2;
323                     final double dm = 2 * (halfDiffOfMean / n1n2);
324                     sumCubedDev += (sumSquaredDev * n2 - other.sumSquaredDev * n1) * dm * 3 +
325                                    (n2 - n1) * (n1 * n2) * pow3(dm) * n1n2;
326                 }
327             }
328         }
329         super.combine(other);
330         return this;
331     }
332 }