001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.commons.math3.stat.descriptive.moment;
018    
019    import java.io.Serializable;
020    
021    import org.apache.commons.math3.exception.MathIllegalArgumentException;
022    import org.apache.commons.math3.exception.NullArgumentException;
023    import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
024    import org.apache.commons.math3.util.FastMath;
025    import org.apache.commons.math3.util.MathUtils;
026    
027    
028    /**
029     * Computes the Kurtosis of the available values.
030     * <p>
031     * We use the following (unbiased) formula to define kurtosis:</p>
032     *  <p>
033     *  kurtosis = { [n(n+1) / (n -1)(n - 2)(n-3)] sum[(x_i - mean)^4] / std^4 } - [3(n-1)^2 / (n-2)(n-3)]
034     *  </p><p>
035     *  where n is the number of values, mean is the {@link Mean} and std is the
036     * {@link StandardDeviation}</p>
037     * <p>
038     *  Note that this statistic is undefined for n < 4.  <code>Double.Nan</code>
039     *  is returned when there is not sufficient data to compute the statistic.</p>
040     * <p>
041     * <strong>Note that this implementation is not synchronized.</strong> If
042     * multiple threads access an instance of this class concurrently, and at least
043     * one of the threads invokes the <code>increment()</code> or
044     * <code>clear()</code> method, it must be synchronized externally.</p>
045     *
046     * @version $Id: Kurtosis.java 1416643 2012-12-03 19:37:14Z tn $
047     */
048    public class Kurtosis extends AbstractStorelessUnivariateStatistic  implements Serializable {
049    
050        /** Serializable version identifier */
051        private static final long serialVersionUID = 2784465764798260919L;
052    
053        /**Fourth Moment on which this statistic is based */
054        protected FourthMoment moment;
055    
056        /**
057         * Determines whether or not this statistic can be incremented or cleared.
058         * <p>
059         * Statistics based on (constructed from) external moments cannot
060         * be incremented or cleared.</p>
061        */
062        protected boolean incMoment;
063    
064        /**
065         * Construct a Kurtosis
066         */
067        public Kurtosis() {
068            incMoment = true;
069            moment = new FourthMoment();
070        }
071    
072        /**
073         * Construct a Kurtosis from an external moment
074         *
075         * @param m4 external Moment
076         */
077        public Kurtosis(final FourthMoment m4) {
078            incMoment = false;
079            this.moment = m4;
080        }
081    
082        /**
083         * Copy constructor, creates a new {@code Kurtosis} identical
084         * to the {@code original}
085         *
086         * @param original the {@code Kurtosis} instance to copy
087         * @throws NullArgumentException if original is null
088         */
089        public Kurtosis(Kurtosis original) throws NullArgumentException {
090            copy(original, this);
091        }
092    
093        /**
094         * {@inheritDoc}
095         * <p>Note that when {@link #Kurtosis(FourthMoment)} is used to
096         * create a Variance, this method does nothing. In that case, the
097         * FourthMoment should be incremented directly.</p>
098         */
099        @Override
100        public void increment(final double d) {
101            if (incMoment) {
102                moment.increment(d);
103            }
104        }
105    
106        /**
107         * {@inheritDoc}
108         */
109        @Override
110        public double getResult() {
111            double kurtosis = Double.NaN;
112            if (moment.getN() > 3) {
113                double variance = moment.m2 / (moment.n - 1);
114                    if (moment.n <= 3 || variance < 10E-20) {
115                        kurtosis = 0.0;
116                    } else {
117                        double n = moment.n;
118                        kurtosis =
119                            (n * (n + 1) * moment.getResult() -
120                                    3 * moment.m2 * moment.m2 * (n - 1)) /
121                                    ((n - 1) * (n -2) * (n -3) * variance * variance);
122                    }
123            }
124            return kurtosis;
125        }
126    
127        /**
128         * {@inheritDoc}
129         */
130        @Override
131        public void clear() {
132            if (incMoment) {
133                moment.clear();
134            }
135        }
136    
137        /**
138         * {@inheritDoc}
139         */
140        public long getN() {
141            return moment.getN();
142        }
143    
144        /* UnvariateStatistic Approach  */
145    
146        /**
147         * Returns the kurtosis of the entries in the specified portion of the
148         * input array.
149         * <p>
150         * See {@link Kurtosis} for details on the computing algorithm.</p>
151         * <p>
152         * Throws <code>IllegalArgumentException</code> if the array is null.</p>
153         *
154         * @param values the input array
155         * @param begin index of the first array element to include
156         * @param length the number of elements to include
157         * @return the kurtosis of the values or Double.NaN if length is less than 4
158         * @throws MathIllegalArgumentException if the input array is null or the array
159         * index parameters are not valid
160         */
161        @Override
162        public double evaluate(final double[] values,final int begin, final int length)
163        throws MathIllegalArgumentException {
164            // Initialize the kurtosis
165            double kurt = Double.NaN;
166    
167            if (test(values, begin, length) && length > 3) {
168    
169                // Compute the mean and standard deviation
170                Variance variance = new Variance();
171                variance.incrementAll(values, begin, length);
172                double mean = variance.moment.m1;
173                double stdDev = FastMath.sqrt(variance.getResult());
174    
175                // Sum the ^4 of the distance from the mean divided by the
176                // standard deviation
177                double accum3 = 0.0;
178                for (int i = begin; i < begin + length; i++) {
179                    accum3 += FastMath.pow(values[i] - mean, 4.0);
180                }
181                accum3 /= FastMath.pow(stdDev, 4.0d);
182    
183                // Get N
184                double n0 = length;
185    
186                double coefficientOne =
187                    (n0 * (n0 + 1)) / ((n0 - 1) * (n0 - 2) * (n0 - 3));
188                double termTwo =
189                    (3 * FastMath.pow(n0 - 1, 2.0)) / ((n0 - 2) * (n0 - 3));
190    
191                // Calculate kurtosis
192                kurt = (coefficientOne * accum3) - termTwo;
193            }
194            return kurt;
195        }
196    
197        /**
198         * {@inheritDoc}
199         */
200        @Override
201        public Kurtosis copy() {
202            Kurtosis result = new Kurtosis();
203            // No try-catch because args are guaranteed non-null
204            copy(this, result);
205            return result;
206        }
207    
208        /**
209         * Copies source to dest.
210         * <p>Neither source nor dest can be null.</p>
211         *
212         * @param source Kurtosis to copy
213         * @param dest Kurtosis to copy to
214         * @throws NullArgumentException if either source or dest is null
215         */
216        public static void copy(Kurtosis source, Kurtosis dest)
217            throws NullArgumentException {
218            MathUtils.checkNotNull(source);
219            MathUtils.checkNotNull(dest);
220            dest.setData(source.getDataRef());
221            dest.moment = source.moment.copy();
222            dest.incMoment = source.incMoment;
223        }
224    
225    }