/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.statistics;
import java.io.*;

public class AnoVaTest extends java.lang.Object
	{
	double f, p;
	int[] N;
	double[] sum, sumsq;
	int columns;

	public void reset( int cols )
		{
		columns=cols;
		N=new int[cols];
		sum=new double[cols];
		sumsq=new double[cols];
		}

	public void datum( double X, int i )
		{
		sum[i]+=X;
		sumsq[i]+=X*X;
		N[i]++;
		}

	public void compute()
		throws ArithmeticException
		{
		double totalss, columnss, errorms, columnms;
		double grandtotal=0.0, grandsq=0.0, errorss=0.0;
		int grandcount=0;

		for ( int i=0; i<columns; i++ )
			{
			if ( N[i]<2 )
				throw new ArithmeticException( "Not enough data points for an AnoVa." );
			grandtotal+=sum[i];
			grandsq+=sumsq[i];
			grandcount+=N[i];

			errorss+=sumsq[i] - sum[i]*sum[i]/N[i];
			}

		totalss=grandsq - grandtotal*grandtotal/grandcount;
		columnss=totalss-errorss;

		columnms=columnss/(columns-1);
		errorms=errorss/(grandcount-columns);
		
		f=columnms/errorms;
		p=FDistribution.p( f, columns-1, grandcount-columns );
		}

	public double getMean( int i ) {return sum[i]/N[i];}
	public double getN( int i ) {return N[i];}
	public double getSum( int i ) {return sum[i];}
	public double getF() {return f;}
	public double getP() {return p;}
	}




