// (c) MIT 2003.  All rights reserved.

////////////////////////////////////////////////////////////////////////////////
//
// FILE:	Analyzer.java
//
// AUTHOR:	Manoj D. Muzumdar
//		archon@ai.mit.edu
//
// DATE:	July, 1998
//
// COPYRIGHT:	Massachusetts Institute of Technology
//		All rights reserved.
//
// PURPOSE:     Library for numeric data analysis
//
////////////////////////////////////////////////////////////////////////////////

package rec.util;

import java.util.Comparator;

/**
 * Analyzer is a library of routines for numeric data analysis.
 *
 * It operates on data sets of doubles.
 */
public final class Analyzer
{
  public static double mean( double[] data )
  {
    Assert.check( data != null, "data set cannot be empty" );

    double total = 0.0;

    for( int i = 0; i < data.length; ++i ) {
      total += data[i];
    }

    return( total / (double)data.length );
  }

  public static double median( double[] data )
  {
    Assert.check( data != null, "data set cannot be empty" );

    if( data.length == 1 )
      return( data[0] );

    double[] sortedData = sort( data );

    // Even case.
    if( data.length % 2 == 0 ) {
      return( (data[data.length / 2 - 1]
	       + data[data.length / 2]) / 2.0 );
    }

    // Odd case.
    return( data[(data.length - 1) / 2] );
  }

  public static double variance( double[] data )
  {
    Assert.check( data != null, "data set cannot be empty" );

    double avg = mean( data );

    double total = 0.0;

    for( int i = 0; i < data.length; ++i ) {
      total += Math.pow( data[i] - avg, 2.0 );
    }

    return( total / (double)data.length );
  }

  public static double standardDeviation( double[] data )
  {
    Assert.check( data != null, "data set cannot be empty" );

    return( Math.sqrt( variance( data ) ) );
  }

  //////////////////////////////////////////////////////////////////////////////

  private static double[] sort( double[] data )
  {

    double[] ret = new double[data.length];

    for( int i = 0; i < data.length; ++i ) {
      ret[i] = data[i];
    }

    QuickSort.sort( ret, new DoubleComparator() );

    return( ret );
  }
      
  //////////////////////////////////////////////////////////////////////////////
}

class DoubleComparator implements Comparator
{
      public DoubleComparator()
      {
      }

      public int compare( Object o1, Object o2 )
      {
	double d1 = ((Double)o1).doubleValue();
	double d2 = ((Double)o2).doubleValue();

	if( d1 == d2 )
	  return( 0 );

	return( d1 < d2 ? -1 : 1 );
      }
    }

////////////////////////////////////////////////////////////////////////////////
