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