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.math3.stat.descriptive.moment;
018
019import java.io.Serializable;
020
021import org.apache.commons.math3.exception.MathIllegalArgumentException;
022import org.apache.commons.math3.exception.NullArgumentException;
023import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
024import org.apache.commons.math3.stat.descriptive.WeightedEvaluation;
025import org.apache.commons.math3.stat.descriptive.summary.Sum;
026import org.apache.commons.math3.util.MathUtils;
027
028/**
029 * <p>Computes the arithmetic mean of a set of values. Uses the definitional
030 * formula:</p>
031 * <p>
032 * mean = sum(x_i) / n
033 * </p>
034 * <p>where <code>n</code> is the number of observations.
035 * </p>
036 * <p>When {@link #increment(double)} is used to add data incrementally from a
037 * stream of (unstored) values, the value of the statistic that
038 * {@link #getResult()} returns is computed using the following recursive
039 * updating algorithm: </p>
040 * <ol>
041 * <li>Initialize <code>m = </code> the first value</li>
042 * <li>For each additional value, update using <br>
043 *   <code>m = m + (new value - m) / (number of observations)</code></li>
044 * </ol>
045 * <p> If {@link #evaluate(double[])} is used to compute the mean of an array
046 * of stored values, a two-pass, corrected algorithm is used, starting with
047 * the definitional formula computed using the array of stored values and then
048 * correcting this by adding the mean deviation of the data values from the
049 * arithmetic mean. See, e.g. "Comparison of Several Algorithms for Computing
050 * Sample Means and Variances," Robert F. Ling, Journal of the American
051 * Statistical Association, Vol. 69, No. 348 (Dec., 1974), pp. 859-866. </p>
052 * <p>
053 *  Returns <code>Double.NaN</code> if the dataset is empty. Note that
054 *  Double.NaN may also be returned if the input includes NaN and / or infinite
055 *  values.
056 * </p>
057 * <strong>Note that this implementation is not synchronized.</strong> If
058 * multiple threads access an instance of this class concurrently, and at least
059 * one of the threads invokes the <code>increment()</code> or
060 * <code>clear()</code> method, it must be synchronized externally.
061 *
062 */
063public class Mean extends AbstractStorelessUnivariateStatistic
064    implements Serializable, WeightedEvaluation {
065
066    /** Serializable version identifier */
067    private static final long serialVersionUID = -1296043746617791564L;
068
069    /** First moment on which this statistic is based. */
070    protected FirstMoment moment;
071
072    /**
073     * Determines whether or not this statistic can be incremented or cleared.
074     * <p>
075     * Statistics based on (constructed from) external moments cannot
076     * be incremented or cleared.</p>
077     */
078    protected boolean incMoment;
079
080    /** Constructs a Mean. */
081    public Mean() {
082        incMoment = true;
083        moment = new FirstMoment();
084    }
085
086    /**
087     * Constructs a Mean with an External Moment.
088     *
089     * @param m1 the moment
090     */
091    public Mean(final FirstMoment m1) {
092        this.moment = m1;
093        incMoment = false;
094    }
095
096    /**
097     * Copy constructor, creates a new {@code Mean} identical
098     * to the {@code original}
099     *
100     * @param original the {@code Mean} instance to copy
101     * @throws NullArgumentException if original is null
102     */
103    public Mean(Mean original) throws NullArgumentException {
104        copy(original, this);
105    }
106
107    /**
108     * {@inheritDoc}
109     * <p>Note that when {@link #Mean(FirstMoment)} is used to
110     * create a Mean, this method does nothing. In that case, the
111     * FirstMoment should be incremented directly.</p>
112     */
113    @Override
114    public void increment(final double d) {
115        if (incMoment) {
116            moment.increment(d);
117        }
118    }
119
120    /**
121     * {@inheritDoc}
122     */
123    @Override
124    public void clear() {
125        if (incMoment) {
126            moment.clear();
127        }
128    }
129
130    /**
131     * {@inheritDoc}
132     */
133    @Override
134    public double getResult() {
135        return moment.m1;
136    }
137
138    /**
139     * {@inheritDoc}
140     */
141    public long getN() {
142        return moment.getN();
143    }
144
145    /**
146     * Returns the arithmetic mean of the entries in the specified portion of
147     * the input array, or <code>Double.NaN</code> if the designated subarray
148     * is empty.
149     * <p>
150     * Throws <code>IllegalArgumentException</code> if the array is null.</p>
151     * <p>
152     * See {@link Mean} for details on the computing algorithm.</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 mean of the values or Double.NaN if length = 0
158     * @throws MathIllegalArgumentException if the array is null or the array index
159     *  parameters are not valid
160     */
161    @Override
162    public double evaluate(final double[] values,final int begin, final int length)
163    throws MathIllegalArgumentException {
164        if (test(values, begin, length)) {
165            Sum sum = new Sum();
166            double sampleSize = length;
167
168            // Compute initial estimate using definitional formula
169            double xbar = sum.evaluate(values, begin, length) / sampleSize;
170
171            // Compute correction factor in second pass
172            double correction = 0;
173            for (int i = begin; i < begin + length; i++) {
174                correction += values[i] - xbar;
175            }
176            return xbar + (correction/sampleSize);
177        }
178        return Double.NaN;
179    }
180
181    /**
182     * Returns the weighted arithmetic mean of the entries in the specified portion of
183     * the input array, or <code>Double.NaN</code> if the designated subarray
184     * is empty.
185     * <p>
186     * Throws <code>IllegalArgumentException</code> if either array is null.</p>
187     * <p>
188     * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
189     * described above is used here, with weights applied in computing both the original
190     * estimate and the correction factor.</p>
191     * <p>
192     * Throws <code>IllegalArgumentException</code> if any of the following are true:
193     * <ul><li>the values array is null</li>
194     *     <li>the weights array is null</li>
195     *     <li>the weights array does not have the same length as the values array</li>
196     *     <li>the weights array contains one or more infinite values</li>
197     *     <li>the weights array contains one or more NaN values</li>
198     *     <li>the weights array contains negative values</li>
199     *     <li>the start and length arguments do not determine a valid array</li>
200     * </ul></p>
201     *
202     * @param values the input array
203     * @param weights the weights array
204     * @param begin index of the first array element to include
205     * @param length the number of elements to include
206     * @return the mean of the values or Double.NaN if length = 0
207     * @throws MathIllegalArgumentException if the parameters are not valid
208     * @since 2.1
209     */
210    public double evaluate(final double[] values, final double[] weights,
211                           final int begin, final int length) throws MathIllegalArgumentException {
212        if (test(values, weights, begin, length)) {
213            Sum sum = new Sum();
214
215            // Compute initial estimate using definitional formula
216            double sumw = sum.evaluate(weights,begin,length);
217            double xbarw = sum.evaluate(values, weights, begin, length) / sumw;
218
219            // Compute correction factor in second pass
220            double correction = 0;
221            for (int i = begin; i < begin + length; i++) {
222                correction += weights[i] * (values[i] - xbarw);
223            }
224            return xbarw + (correction/sumw);
225        }
226        return Double.NaN;
227    }
228
229    /**
230     * Returns the weighted arithmetic mean of the entries in the input array.
231     * <p>
232     * Throws <code>MathIllegalArgumentException</code> if either array is null.</p>
233     * <p>
234     * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
235     * described above is used here, with weights applied in computing both the original
236     * estimate and the correction factor.</p>
237     * <p>
238     * Throws <code>MathIllegalArgumentException</code> if any of the following are true:
239     * <ul><li>the values array is null</li>
240     *     <li>the weights array is null</li>
241     *     <li>the weights array does not have the same length as the values array</li>
242     *     <li>the weights array contains one or more infinite values</li>
243     *     <li>the weights array contains one or more NaN values</li>
244     *     <li>the weights array contains negative values</li>
245     * </ul></p>
246     *
247     * @param values the input array
248     * @param weights the weights array
249     * @return the mean of the values or Double.NaN if length = 0
250     * @throws MathIllegalArgumentException if the parameters are not valid
251     * @since 2.1
252     */
253    public double evaluate(final double[] values, final double[] weights)
254    throws MathIllegalArgumentException {
255        return evaluate(values, weights, 0, values.length);
256    }
257
258    /**
259     * {@inheritDoc}
260     */
261    @Override
262    public Mean copy() {
263        Mean result = new Mean();
264        // No try-catch or advertised exception because args are guaranteed non-null
265        copy(this, result);
266        return result;
267    }
268
269
270    /**
271     * Copies source to dest.
272     * <p>Neither source nor dest can be null.</p>
273     *
274     * @param source Mean to copy
275     * @param dest Mean to copy to
276     * @throws NullArgumentException if either source or dest is null
277     */
278    public static void copy(Mean source, Mean dest)
279        throws NullArgumentException {
280        MathUtils.checkNotNull(source);
281        MathUtils.checkNotNull(dest);
282        dest.setData(source.getDataRef());
283        dest.incMoment = source.incMoment;
284        dest.moment = source.moment.copy();
285    }
286}