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.MathIllegalStateException;
023import org.apache.commons.math3.exception.NullArgumentException;
024import org.apache.commons.math3.exception.util.LocalizedFormats;
025import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
026import org.apache.commons.math3.stat.descriptive.StorelessUnivariateStatistic;
027import org.apache.commons.math3.stat.descriptive.summary.SumOfLogs;
028import org.apache.commons.math3.util.FastMath;
029import org.apache.commons.math3.util.MathUtils;
030
031/**
032 * Returns the <a href="http://www.xycoon.com/geometric_mean.htm">
033 * geometric mean </a> of the available values.
034 * <p>
035 * Uses a {@link SumOfLogs} instance to compute sum of logs and returns
036 * <code> exp( 1/n  (sum of logs) ).</code>  Therefore, </p>
037 * <ul>
038 * <li>If any of values are < 0, the result is <code>NaN.</code></li>
039 * <li>If all values are non-negative and less than
040 * <code>Double.POSITIVE_INFINITY</code>,  but at least one value is 0, the
041 * result is <code>0.</code></li>
042 * <li>If both <code>Double.POSITIVE_INFINITY</code> and
043 * <code>Double.NEGATIVE_INFINITY</code> are among the values, the result is
044 * <code>NaN.</code></li>
045 * </ul> </p>
046 * <p>
047 * <strong>Note that this implementation is not synchronized.</strong> If
048 * multiple threads access an instance of this class concurrently, and at least
049 * one of the threads invokes the <code>increment()</code> or
050 * <code>clear()</code> method, it must be synchronized externally.</p>
051 *
052 *
053 */
054public class GeometricMean extends AbstractStorelessUnivariateStatistic implements Serializable {
055
056    /** Serializable version identifier */
057    private static final long serialVersionUID = -8178734905303459453L;
058
059    /** Wrapped SumOfLogs instance */
060    private StorelessUnivariateStatistic sumOfLogs;
061
062    /**
063     * Create a GeometricMean instance
064     */
065    public GeometricMean() {
066        sumOfLogs = new SumOfLogs();
067    }
068
069    /**
070     * Copy constructor, creates a new {@code GeometricMean} identical
071     * to the {@code original}
072     *
073     * @param original the {@code GeometricMean} instance to copy
074     * @throws NullArgumentException if original is null
075     */
076    public GeometricMean(GeometricMean original) throws NullArgumentException {
077        super();
078        copy(original, this);
079    }
080
081    /**
082     * Create a GeometricMean instance using the given SumOfLogs instance
083     * @param sumOfLogs sum of logs instance to use for computation
084     */
085    public GeometricMean(SumOfLogs sumOfLogs) {
086        this.sumOfLogs = sumOfLogs;
087    }
088
089    /**
090     * {@inheritDoc}
091     */
092    @Override
093    public GeometricMean copy() {
094        GeometricMean result = new GeometricMean();
095        // no try-catch or advertised exception because args guaranteed non-null
096        copy(this, result);
097        return result;
098    }
099
100    /**
101     * {@inheritDoc}
102     */
103    @Override
104    public void increment(final double d) {
105        sumOfLogs.increment(d);
106    }
107
108    /**
109     * {@inheritDoc}
110     */
111    @Override
112    public double getResult() {
113        if (sumOfLogs.getN() > 0) {
114            return FastMath.exp(sumOfLogs.getResult() / sumOfLogs.getN());
115        } else {
116            return Double.NaN;
117        }
118    }
119
120    /**
121     * {@inheritDoc}
122     */
123    @Override
124    public void clear() {
125        sumOfLogs.clear();
126    }
127
128    /**
129     * Returns the geometric mean of the entries in the specified portion
130     * of the input array.
131     * <p>
132     * See {@link GeometricMean} for details on the computing algorithm.</p>
133     * <p>
134     * Throws <code>IllegalArgumentException</code> if the array is null.</p>
135     *
136     * @param values input array containing the values
137     * @param begin first array element to include
138     * @param length the number of elements to include
139     * @return the geometric mean or Double.NaN if length = 0 or
140     * any of the values are &lt;= 0.
141     * @throws MathIllegalArgumentException if the input array is null or the array
142     * index parameters are not valid
143     */
144    @Override
145    public double evaluate(
146        final double[] values, final int begin, final int length)
147    throws MathIllegalArgumentException {
148        return FastMath.exp(
149            sumOfLogs.evaluate(values, begin, length) / length);
150    }
151
152    /**
153     * {@inheritDoc}
154     */
155    public long getN() {
156        return sumOfLogs.getN();
157    }
158
159    /**
160     * <p>Sets the implementation for the sum of logs.</p>
161     * <p>This method must be activated before any data has been added - i.e.,
162     * before {@link #increment(double) increment} has been used to add data;
163     * otherwise an IllegalStateException will be thrown.</p>
164     *
165     * @param sumLogImpl the StorelessUnivariateStatistic instance to use
166     * for computing the log sum
167     * @throws MathIllegalStateException if data has already been added
168     *  (i.e if n > 0)
169     */
170    public void setSumLogImpl(StorelessUnivariateStatistic sumLogImpl)
171    throws MathIllegalStateException {
172        checkEmpty();
173        this.sumOfLogs = sumLogImpl;
174    }
175
176    /**
177     * Returns the currently configured sum of logs implementation
178     *
179     * @return the StorelessUnivariateStatistic implementing the log sum
180     */
181    public StorelessUnivariateStatistic getSumLogImpl() {
182        return sumOfLogs;
183    }
184
185    /**
186     * Copies source to dest.
187     * <p>Neither source nor dest can be null.</p>
188     *
189     * @param source GeometricMean to copy
190     * @param dest GeometricMean to copy to
191     * @throws NullArgumentException if either source or dest is null
192     */
193    public static void copy(GeometricMean source, GeometricMean dest)
194        throws NullArgumentException {
195        MathUtils.checkNotNull(source);
196        MathUtils.checkNotNull(dest);
197        dest.setData(source.getDataRef());
198        dest.sumOfLogs = source.sumOfLogs.copy();
199    }
200
201
202    /**
203     * Throws MathIllegalStateException if n > 0.
204     * @throws MathIllegalStateException if data has been added to this statistic
205     */
206    private void checkEmpty() throws MathIllegalStateException {
207        if (getN() > 0) {
208            throw new MathIllegalStateException(
209                    LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC,
210                    getN());
211        }
212    }
213
214}