View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math3.stat.descriptive.moment;
18  
19  import java.io.Serializable;
20  
21  import org.apache.commons.math3.exception.MathIllegalArgumentException;
22  import org.apache.commons.math3.exception.MathIllegalStateException;
23  import org.apache.commons.math3.exception.NullArgumentException;
24  import org.apache.commons.math3.exception.util.LocalizedFormats;
25  import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
26  import org.apache.commons.math3.stat.descriptive.StorelessUnivariateStatistic;
27  import org.apache.commons.math3.stat.descriptive.summary.SumOfLogs;
28  import org.apache.commons.math3.util.FastMath;
29  import org.apache.commons.math3.util.MathUtils;
30  
31  /**
32   * Returns the <a href="http://www.xycoon.com/geometric_mean.htm">
33   * geometric mean </a> of the available values.
34   * <p>
35   * Uses a {@link SumOfLogs} instance to compute sum of logs and returns
36   * <code> exp( 1/n  (sum of logs) ).</code>  Therefore, </p>
37   * <ul>
38   * <li>If any of values are < 0, the result is <code>NaN.</code></li>
39   * <li>If all values are non-negative and less than
40   * <code>Double.POSITIVE_INFINITY</code>,  but at least one value is 0, the
41   * result is <code>0.</code></li>
42   * <li>If both <code>Double.POSITIVE_INFINITY</code> and
43   * <code>Double.NEGATIVE_INFINITY</code> are among the values, the result is
44   * <code>NaN.</code></li>
45   * </ul> </p>
46   * <p>
47   * <strong>Note that this implementation is not synchronized.</strong> If
48   * multiple threads access an instance of this class concurrently, and at least
49   * one of the threads invokes the <code>increment()</code> or
50   * <code>clear()</code> method, it must be synchronized externally.</p>
51   *
52   *
53   */
54  public class GeometricMean extends AbstractStorelessUnivariateStatistic implements Serializable {
55  
56      /** Serializable version identifier */
57      private static final long serialVersionUID = -8178734905303459453L;
58  
59      /** Wrapped SumOfLogs instance */
60      private StorelessUnivariateStatistic sumOfLogs;
61  
62      /**
63       * Create a GeometricMean instance
64       */
65      public GeometricMean() {
66          sumOfLogs = new SumOfLogs();
67      }
68  
69      /**
70       * Copy constructor, creates a new {@code GeometricMean} identical
71       * to the {@code original}
72       *
73       * @param original the {@code GeometricMean} instance to copy
74       * @throws NullArgumentException if original is null
75       */
76      public GeometricMean(GeometricMean original) throws NullArgumentException {
77          super();
78          copy(original, this);
79      }
80  
81      /**
82       * Create a GeometricMean instance using the given SumOfLogs instance
83       * @param sumOfLogs sum of logs instance to use for computation
84       */
85      public GeometricMean(SumOfLogs sumOfLogs) {
86          this.sumOfLogs = sumOfLogs;
87      }
88  
89      /**
90       * {@inheritDoc}
91       */
92      @Override
93      public GeometricMean copy() {
94          GeometricMean result = new GeometricMean();
95          // no try-catch or advertised exception because args guaranteed non-null
96          copy(this, result);
97          return result;
98      }
99  
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 }