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.math.stat.descriptive.moment;
018    
019    import java.io.Serializable;
020    
021    import org.apache.commons.math.exception.NullArgumentException;
022    import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic;
023    import org.apache.commons.math.util.FastMath;
024    import org.apache.commons.math.util.MathUtils;
025    
026    /**
027     * Computes the skewness of the available values.
028     * <p>
029     * We use the following (unbiased) formula to define skewness:</p>
030     * <p>
031     * skewness = [n / (n -1) (n - 2)] sum[(x_i - mean)^3] / std^3 </p>
032     * <p>
033     * where n is the number of values, mean is the {@link Mean} and std is the
034     * {@link StandardDeviation} </p>
035     * <p>
036     * <strong>Note that this implementation is not synchronized.</strong> If
037     * multiple threads access an instance of this class concurrently, and at least
038     * one of the threads invokes the <code>increment()</code> or
039     * <code>clear()</code> method, it must be synchronized externally. </p>
040     *
041     * @version $Id: Skewness.java 1132432 2011-06-05 14:59:29Z luc $
042     */
043    public class Skewness extends AbstractStorelessUnivariateStatistic implements Serializable {
044    
045        /** Serializable version identifier */
046        private static final long serialVersionUID = 7101857578996691352L;
047    
048        /** Third moment on which this statistic is based */
049        protected ThirdMoment moment = null;
050    
051         /**
052         * Determines whether or not this statistic can be incremented or cleared.
053         * <p>
054         * Statistics based on (constructed from) external moments cannot
055         * be incremented or cleared.</p>
056        */
057        protected boolean incMoment;
058    
059        /**
060         * Constructs a Skewness
061         */
062        public Skewness() {
063            incMoment = true;
064            moment = new ThirdMoment();
065        }
066    
067        /**
068         * Constructs a Skewness with an external moment
069         * @param m3 external moment
070         */
071        public Skewness(final ThirdMoment m3) {
072            incMoment = false;
073            this.moment = m3;
074        }
075    
076        /**
077         * Copy constructor, creates a new {@code Skewness} identical
078         * to the {@code original}
079         *
080         * @param original the {@code Skewness} instance to copy
081         */
082        public Skewness(Skewness original) {
083            copy(original, this);
084        }
085    
086        /**
087         * {@inheritDoc}
088         */
089        @Override
090        public void increment(final double d) {
091            if (incMoment) {
092                moment.increment(d);
093            }
094        }
095    
096        /**
097         * Returns the value of the statistic based on the values that have been added.
098         * <p>
099         * See {@link Skewness} for the definition used in the computation.</p>
100         *
101         * @return the skewness of the available values.
102         */
103        @Override
104        public double getResult() {
105    
106            if (moment.n < 3) {
107                return Double.NaN;
108            }
109            double variance = moment.m2 / (moment.n - 1);
110            if (variance < 10E-20) {
111                return 0.0d;
112            } else {
113                double n0 = moment.getN();
114                return  (n0 * moment.m3) /
115                ((n0 - 1) * (n0 -2) * FastMath.sqrt(variance) * variance);
116            }
117        }
118    
119        /**
120         * {@inheritDoc}
121         */
122        public long getN() {
123            return moment.getN();
124        }
125    
126        /**
127         * {@inheritDoc}
128         */
129        @Override
130        public void clear() {
131            if (incMoment) {
132                moment.clear();
133            }
134        }
135    
136        /**
137         * Returns the Skewness of the entries in the specifed portion of the
138         * input array.
139         * <p>
140         * See {@link Skewness} for the definition used in the computation.</p>
141         * <p>
142         * Throws <code>IllegalArgumentException</code> if the array is null.</p>
143         *
144         * @param values the input array
145         * @param begin the index of the first array element to include
146         * @param length the number of elements to include
147         * @return the skewness of the values or Double.NaN if length is less than
148         * 3
149         * @throws IllegalArgumentException if the array is null or the array index
150         *  parameters are not valid
151         */
152        @Override
153        public double evaluate(final double[] values,final int begin,
154                final int length) {
155    
156            // Initialize the skewness
157            double skew = Double.NaN;
158    
159            if (test(values, begin, length) && length > 2 ){
160                Mean mean = new Mean();
161                // Get the mean and the standard deviation
162                double m = mean.evaluate(values, begin, length);
163    
164                // Calc the std, this is implemented here instead
165                // of using the standardDeviation method eliminate
166                // a duplicate pass to get the mean
167                double accum = 0.0;
168                double accum2 = 0.0;
169                for (int i = begin; i < begin + length; i++) {
170                    final double d = values[i] - m;
171                    accum  += d * d;
172                    accum2 += d;
173                }
174                final double variance = (accum - (accum2 * accum2 / length)) / (length - 1);
175    
176                double accum3 = 0.0;
177                for (int i = begin; i < begin + length; i++) {
178                    final double d = values[i] - m;
179                    accum3 += d * d * d;
180                }
181                accum3 /= variance * FastMath.sqrt(variance);
182    
183                // Get N
184                double n0 = length;
185    
186                // Calculate skewness
187                skew = (n0 / ((n0 - 1) * (n0 - 2))) * accum3;
188            }
189            return skew;
190        }
191    
192        /**
193         * {@inheritDoc}
194         */
195        @Override
196        public Skewness copy() {
197            Skewness result = new Skewness();
198            copy(this, result);
199            return result;
200        }
201    
202        /**
203         * Copies source to dest.
204         * <p>Neither source nor dest can be null.</p>
205         *
206         * @param source Skewness to copy
207         * @param dest Skewness to copy to
208         * @throws NullArgumentException if either source or dest is null
209         */
210        public static void copy(Skewness source, Skewness dest)
211            throws NullArgumentException {
212            MathUtils.checkNotNull(source);
213            MathUtils.checkNotNull(dest);
214            dest.setData(source.getDataRef());
215            dest.moment = new ThirdMoment(source.moment.copy());
216            dest.incMoment = source.incMoment;
217        }
218    }