work on data buffer for aLeaves MAFFT suite + clean up
[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     @Override
150     public String getSummaryAsString() {
151         validate();
152         final double mean = arithmeticMean();
153         final double sd = sampleStandardDeviation();
154         return "" + mean + ( ( char ) 177 ) + sd + " [" + getMin() + "..." + getMax() + "]";
155     }
156
157     @Override
158     public double getValue( final int index ) {
159         validate();
160         return ( ( ( _data.get( index ) ) ).doubleValue() );
161     }
162
163     private void init() {
164         _data = new ArrayList<Double>();
165         _sum = 0.0;
166         _min = Double.MAX_VALUE;
167         _max = -Double.MAX_VALUE;
168         _sigma = 0.0;
169         _recalc_sigma = true;
170         _desc = "";
171     }
172
173     /* (non-Javadoc)
174      * @see org.forester.util.DescriptiveStatisticsI#median()
175      */
176     @Override
177     public double median() {
178         validate();
179         double median = 0.0;
180         if ( getN() == 1 ) {
181             median = getValue( 0 );
182         }
183         else {
184             final int index = ( getN() / 2 );
185             final double[] data_array = getDataAsDoubleArray();
186             Arrays.sort( data_array );
187             if ( ( ( data_array.length ) % 2 ) == 0 ) {
188                 // even number of data values
189                 median = ( data_array[ index - 1 ] + data_array[ index ] ) / 2.0;
190             }
191             else {
192                 median = data_array[ index ];
193             }
194         }
195         return median;
196     }
197
198     /* (non-Javadoc)
199      * @see org.forester.util.DescriptiveStatisticsI#midrange()
200      */
201     @Override
202     public double midrange() {
203         validate();
204         return ( _min + _max ) / 2.0;
205     }
206
207     /* (non-Javadoc)
208      * @see org.forester.util.DescriptiveStatisticsI#pearsonianSkewness()
209      */
210     @Override
211     public double pearsonianSkewness() {
212         validate();
213         final double mean = arithmeticMean();
214         final double median = median();
215         final double sd = sampleStandardDeviation();
216         return ( ( 3 * ( mean - median ) ) / sd );
217     }
218
219     /* (non-Javadoc)
220      * @see org.forester.util.DescriptiveStatisticsI#sampleStandardDeviation()
221      */
222     @Override
223     public double sampleStandardDeviation() {
224         return Math.sqrt( sampleVariance() );
225     }
226
227     /* (non-Javadoc)
228      * @see org.forester.util.DescriptiveStatisticsI#sampleStandardUnit(double)
229      */
230     @Override
231     public double sampleStandardUnit( final double value ) {
232         validate();
233         return BasicDescriptiveStatistics.sampleStandardUnit( value, arithmeticMean(), sampleStandardDeviation() );
234     }
235
236     /* (non-Javadoc)
237      * @see org.forester.util.DescriptiveStatisticsI#sampleVariance()
238      */
239     @Override
240     public double sampleVariance() {
241         validate();
242         if ( getN() < 2 ) {
243             throw new ArithmeticException( "attempt to calculate sample variance for less then two values" );
244         }
245         return ( sumDeviations() / ( getN() - 1 ) );
246     }
247
248     /* (non-Javadoc)
249      * @see org.forester.util.DescriptiveStatisticsI#standardErrorOfMean()
250      */
251     @Override
252     public double standardErrorOfMean() {
253         validate();
254         return ( sampleStandardDeviation() / Math.sqrt( getN() ) );
255     }
256
257     /* (non-Javadoc)
258      * @see org.forester.util.DescriptiveStatisticsI#sumDeviations()
259      */
260     @Override
261     public double sumDeviations() {
262         validate();
263         if ( _recalc_sigma ) {
264             _recalc_sigma = false;
265             _sigma = 0.0;
266             final double mean = arithmeticMean();
267             for( int i = 0; i < getN(); ++i ) {
268                 _sigma += Math.pow( ( getValue( i ) - mean ), 2 );
269             }
270         }
271         return _sigma;
272     }
273
274     /* (non-Javadoc)
275      * @see org.forester.util.DescriptiveStatisticsI#toString()
276      */
277     @Override
278     public String toString() {
279         if ( getN() < 1 ) {
280             return "empty data set statistics";
281         }
282         final StringBuffer sb = new StringBuffer();
283         sb.append( "Descriptive statistics:" );
284         sb.append( ForesterUtil.getLineSeparator() );
285         sb.append( "n                       : " + getN() );
286         if ( getN() > 1 ) {
287             sb.append( ForesterUtil.getLineSeparator() );
288             sb.append( "min                     : " + getMin() );
289             sb.append( ForesterUtil.getLineSeparator() );
290             sb.append( "max                     : " + getMax() );
291             sb.append( ForesterUtil.getLineSeparator() );
292             sb.append( "midrange                : " + midrange() );
293             sb.append( ForesterUtil.getLineSeparator() );
294             sb.append( "median                  : " + median() );
295             sb.append( ForesterUtil.getLineSeparator() );
296             sb.append( "mean                    : " + arithmeticMean() );
297             sb.append( ForesterUtil.getLineSeparator() );
298             sb.append( "sd                      : " + sampleStandardDeviation() );
299             sb.append( ForesterUtil.getLineSeparator() );
300             sb.append( "variance                : " + sampleVariance() );
301             sb.append( ForesterUtil.getLineSeparator() );
302             sb.append( "standard error of mean  : " + standardErrorOfMean() );
303             sb.append( ForesterUtil.getLineSeparator() );
304             sb.append( "coefficient of variation: " + coefficientOfVariation() );
305             sb.append( ForesterUtil.getLineSeparator() );
306             sb.append( "pearsonian skewness     : " + pearsonianSkewness() );
307         }
308         return sb.toString();
309     }
310
311     private void validate() throws ArithmeticException {
312         if ( getN() < 1 ) {
313             throw new ArithmeticException( "attempt to get a result from empty data set statistics" );
314         }
315     }
316
317     public static int[] performBinning( final double[] values,
318                                         final double min,
319                                         final double max,
320                                         final int number_of_bins ) {
321         if ( min >= max ) {
322             throw new IllegalArgumentException( "min [" + min + "] is larger than or equal to max [" + max + "]" );
323         }
324         if ( number_of_bins < 3 ) {
325             throw new IllegalArgumentException( "number of bins is smaller than 3" );
326         }
327         final int[] bins = new int[ number_of_bins ];
328         final double binning_factor = number_of_bins / ( max - min );
329         final int last_index = number_of_bins - 1;
330         for( final double d : values ) {
331             if ( !( ( d > max ) || ( d < min ) ) ) {
332                 final int bin = ( int ) ( ( d - min ) * binning_factor );
333                 if ( bin > last_index ) {
334                     ++bins[ last_index ];
335                 }
336                 else {
337                     ++bins[ bin ];
338                 }
339             }
340         }
341         return bins;
342     }
343
344     /**
345      * Computes the sample standard unit (z-score). Used to compute 'value' in
346      * terms of standard units. Note that 'value', 'mean' and 'sd' must be all
347      * from the same sample data.
348      * 
349      * @param value
350      *            a double in the sample for which
351      * @param mean
352      *            the mean of the sample.
353      * @param sd
354      *            The standard deviation of the sample.
355      * @return 'value' in terms of standard units
356      */
357     public static double sampleStandardUnit( final double value, final double mean, final double sd ) {
358         return ( value - mean ) / sd;
359     }
360
361     @Override
362     public List<Double> getData() {
363         return _data;
364     }
365
366     @Override
367     public void setDescription( final String desc ) {
368         _desc = desc;
369     }
370
371     @Override
372     public String getDescription() {
373         return _desc;
374     }
375 }