538f6a19f603a6cf3fd8806ed83720b29905fc5e
[jalview.git] / forester / java / src / org / forester / util / BasicDescriptiveStatistics.java
1 // $Id:
2 // $
3 //
4 // FORESTER -- software libraries and applications
5 // for evolutionary biology research and applications.
6 //
7 // Copyright (C) 2008-2009 Christian M. Zmasek
8 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: www.phylosoft.org/forester
27
28 package org.forester.util;
29
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.List;
33
34 public class BasicDescriptiveStatistics implements DescriptiveStatistics {
35
36     private List<Double> _data;
37     private double       _sum;
38     private double       _min;
39     private double       _max;
40     private double       _sigma;
41     private boolean      _recalc_sigma;
42     private String       _desc;
43
44     public BasicDescriptiveStatistics() {
45         init();
46     }
47
48     public BasicDescriptiveStatistics( final String desc ) {
49         init();
50         setDescription( desc );
51     }
52
53     /* (non-Javadoc)
54      * @see org.forester.util.DescriptiveStatisticsI#addValue(double)
55      */
56     @Override
57     public void addValue( final double d ) {
58         _recalc_sigma = true;
59         _sum += d;
60         _data.add( new Double( d ) );
61         if ( d < _min ) {
62             _min = d;
63         }
64         if ( d > _max ) {
65             _max = d;
66         }
67     }
68
69     /* (non-Javadoc)
70      * @see org.forester.util.DescriptiveStatisticsI#arithmeticMean()
71      */
72     @Override
73     public double arithmeticMean() {
74         validate();
75         return getSum() / getN();
76     }
77
78     /* (non-Javadoc)
79      * @see org.forester.util.DescriptiveStatisticsI#asSummary()
80      */
81     @Override
82     public String asSummary() {
83         if ( getN() > 1 ) {
84             return arithmeticMean() + DescriptiveStatistics.PLUS_MINUS + sampleStandardDeviation() + " [" + getMin()
85                     + "..." + getMax() + "]";
86         }
87         else {
88             return "" + arithmeticMean();
89         }
90     }
91
92     /* (non-Javadoc)
93      * @see org.forester.util.DescriptiveStatisticsI#coefficientOfVariation()
94      */
95     @Override
96     public double coefficientOfVariation() {
97         validate();
98         return ( sampleStandardDeviation() / arithmeticMean() );
99     }
100
101     /* (non-Javadoc)
102      * @see org.forester.util.DescriptiveStatisticsI#getDataAsDoubleArray()
103      */
104     @Override
105     public double[] getDataAsDoubleArray() {
106         validate();
107         final double[] data_array = new double[ getN() ];
108         for( int i = 0; i < getN(); ++i ) {
109             data_array[ i ] = getValue( i );
110         }
111         return data_array;
112     }
113
114     /* (non-Javadoc)
115      * @see org.forester.util.DescriptiveStatisticsI#getMax()
116      */
117     @Override
118     public double getMax() {
119         validate();
120         return _max;
121     }
122
123     /* (non-Javadoc)
124      * @see org.forester.util.DescriptiveStatisticsI#getMin()
125      */
126     @Override
127     public double getMin() {
128         validate();
129         return _min;
130     }
131
132     /* (non-Javadoc)
133      * @see org.forester.util.DescriptiveStatisticsI#getN()
134      */
135     @Override
136     public int getN() {
137         return _data.size();
138     }
139
140     /* (non-Javadoc)
141      * @see org.forester.util.DescriptiveStatisticsI#getSum()
142      */
143     @Override
144     public double getSum() {
145         validate();
146         return _sum;
147     }
148
149   
150     @Override
151     public String getSummaryAsString() {
152         validate();
153         final double mean = arithmeticMean();
154         final double sd = sampleStandardDeviation();
155         return "" + mean + ( ( char ) 177 ) + sd + " [" + getMin() + "..." + getMax() + "]";
156     }
157
158    
159     @Override
160     public double getValue( final int index ) {
161         validate();
162         return ( ( ( _data.get( index ) ) ).doubleValue() );
163     }
164
165     private void init() {
166         _data = new ArrayList<Double>();
167         _sum = 0.0;
168         _min = Double.MAX_VALUE;
169         _max = -Double.MAX_VALUE;
170         _sigma = 0.0;
171         _recalc_sigma = true;
172         _desc = "";
173     }
174
175     /* (non-Javadoc)
176      * @see org.forester.util.DescriptiveStatisticsI#median()
177      */
178     @Override
179     public double median() {
180         validate();
181         double median = 0.0;
182         if ( getN() == 1 ) {
183             median = getValue( 0 );
184         }
185         else {
186             final int index = ( getN() / 2 );
187             final double[] data_array = getDataAsDoubleArray();
188             Arrays.sort( data_array );
189             if ( ( ( data_array.length ) % 2 ) == 0 ) {
190                 // even number of data values
191                 median = ( data_array[ index - 1 ] + data_array[ index ] ) / 2.0;
192             }
193             else {
194                 median = data_array[ index ];
195             }
196         }
197         return median;
198     }
199
200     /* (non-Javadoc)
201      * @see org.forester.util.DescriptiveStatisticsI#midrange()
202      */
203     @Override
204     public double midrange() {
205         validate();
206         return ( _min + _max ) / 2.0;
207     }
208
209     /* (non-Javadoc)
210      * @see org.forester.util.DescriptiveStatisticsI#pearsonianSkewness()
211      */
212     @Override
213     public double pearsonianSkewness() {
214         validate();
215         final double mean = arithmeticMean();
216         final double median = median();
217         final double sd = sampleStandardDeviation();
218         return ( ( 3 * ( mean - median ) ) / sd );
219     }
220
221     /* (non-Javadoc)
222      * @see org.forester.util.DescriptiveStatisticsI#sampleStandardDeviation()
223      */
224     @Override
225     public double sampleStandardDeviation() {
226         return Math.sqrt( sampleVariance() );
227     }
228
229     /* (non-Javadoc)
230      * @see org.forester.util.DescriptiveStatisticsI#sampleStandardUnit(double)
231      */
232     @Override
233     public double sampleStandardUnit( final double value ) {
234         validate();
235         return BasicDescriptiveStatistics.sampleStandardUnit( value, arithmeticMean(), sampleStandardDeviation() );
236     }
237
238     /* (non-Javadoc)
239      * @see org.forester.util.DescriptiveStatisticsI#sampleVariance()
240      */
241     @Override
242     public double sampleVariance() {
243         validate();
244         if ( getN() < 2 ) {
245             throw new ArithmeticException( "attempt to calculate sample variance for less then two values" );
246         }
247         return ( sumDeviations() / ( getN() - 1 ) );
248     }
249
250     /* (non-Javadoc)
251      * @see org.forester.util.DescriptiveStatisticsI#standardErrorOfMean()
252      */
253     @Override
254     public double standardErrorOfMean() {
255         validate();
256         return ( sampleStandardDeviation() / Math.sqrt( getN() ) );
257     }
258
259     /* (non-Javadoc)
260      * @see org.forester.util.DescriptiveStatisticsI#sumDeviations()
261      */
262     @Override
263     public double sumDeviations() {
264         validate();
265         if ( _recalc_sigma ) {
266             _recalc_sigma = false;
267             _sigma = 0.0;
268             final double mean = arithmeticMean();
269             for( int i = 0; i < getN(); ++i ) {
270                 _sigma += Math.pow( ( getValue( i ) - mean ), 2 );
271             }
272         }
273         return _sigma;
274     }
275
276     /* (non-Javadoc)
277      * @see org.forester.util.DescriptiveStatisticsI#toString()
278      */
279     @Override
280     public String toString() {
281         if ( getN() < 1 ) {
282             return "empty data set statistics";
283         }
284         final StringBuffer sb = new StringBuffer();
285         sb.append( "Descriptive statistics:" );
286         sb.append( ForesterUtil.getLineSeparator() );
287         sb.append( "n                       : " + getN() );
288         if ( getN() > 1 ) {
289             sb.append( ForesterUtil.getLineSeparator() );
290             sb.append( "min                     : " + getMin() );
291             sb.append( ForesterUtil.getLineSeparator() );
292             sb.append( "max                     : " + getMax() );
293             sb.append( ForesterUtil.getLineSeparator() );
294             sb.append( "midrange                : " + midrange() );
295             sb.append( ForesterUtil.getLineSeparator() );
296             sb.append( "median                  : " + median() );
297             sb.append( ForesterUtil.getLineSeparator() );
298             sb.append( "mean                    : " + arithmeticMean() );
299             sb.append( ForesterUtil.getLineSeparator() );
300             sb.append( "sd                      : " + sampleStandardDeviation() );
301             sb.append( ForesterUtil.getLineSeparator() );
302             sb.append( "variance                : " + sampleVariance() );
303             sb.append( ForesterUtil.getLineSeparator() );
304             sb.append( "standard error of mean  : " + standardErrorOfMean() );
305             sb.append( ForesterUtil.getLineSeparator() );
306             sb.append( "coefficient of variation: " + coefficientOfVariation() );
307             sb.append( ForesterUtil.getLineSeparator() );
308             sb.append( "pearsonian skewness     : " + pearsonianSkewness() );
309         }
310         return sb.toString();
311     }
312
313     private void validate() throws ArithmeticException {
314         if ( getN() < 1 ) {
315             throw new ArithmeticException( "attempt to get a result from empty data set statistics" );
316         }
317     }
318
319     public static int[] performBinning( final double[] values,
320                                         final double min,
321                                         final double max,
322                                         final int number_of_bins ) {
323         if ( min >= max ) {
324             throw new IllegalArgumentException( "min [" + min + "] is larger than or equal to max [" + max + "]" );
325         }
326         if ( number_of_bins < 3 ) {
327             throw new IllegalArgumentException( "number of bins is smaller than 3" );
328         }
329         final int[] bins = new int[ number_of_bins ];
330         final double binning_factor = number_of_bins / ( max - min );
331         final int last_index = number_of_bins - 1;
332         for( final double d : values ) {
333             if ( !( ( d > max ) || ( d < min ) ) ) {
334                 final int bin = ( int ) ( ( d - min ) * binning_factor );
335                 if ( bin > last_index ) {
336                     ++bins[ last_index ];
337                 }
338                 else {
339                     ++bins[ bin ];
340                 }
341             }
342         }
343         return bins;
344     }
345
346     /**
347      * Computes the sample standard unit (z-score). Used to compute 'value' in
348      * terms of standard units. Note that 'value', 'mean' and 'sd' must be all
349      * from the same sample data.
350      * 
351      * @param value
352      *            a double in the sample for which
353      * @param mean
354      *            the mean of the sample.
355      * @param sd
356      *            The standard deviation of the sample.
357      * @return 'value' in terms of standard units
358      */
359     public static double sampleStandardUnit( final double value, final double mean, final double sd ) {
360         return ( value - mean ) / sd;
361     }
362
363     @Override
364     public List<Double> getData() {
365         return _data;
366     }
367
368     @Override
369     public void setDescription( final String desc ) {
370         _desc = desc;
371     }
372
373     @Override
374     public String getDescription() {
375         return _desc;
376     }
377 }