package jp.ac.kyutech.mns.ist.filter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;

public class AvgVarCalc2<E> {
	ArrayList<E> data;
	ArrayList<String> keys;
	String[] mlist;// = {"ppd","ramer","dist"};
	double[] avg;// = new double[mlist.length];
	double[] var;// = new double[mlist.length];
	double[] cnt;// = new double[mlist.length];
//	double[][] kavg;
//	double[][] kvar;
//	double[][] kcnt;

	public AvgVarCalc2(String[] _mlist, ArrayList<E> al){
		data = new ArrayList<E>(al);
		keys = new ArrayList<String>(Arrays.asList(_mlist));
		calc();
	}
	public void add(E d){
		data.add(d);
	}
	public double getavg(String k){
		return avg[keys.indexOf(k)];
	}
	public double getvar(String k){
		return var[keys.indexOf(k)];
	}
	public double getcnt(String k){
		return cnt[keys.indexOf(k)];
	}
	public void calc(){
		avg = new double[keys.size()];
		var = new double[keys.size()];
		cnt = new double[keys.size()];

		if (data.size()==0) return;
//		kavg = new double[5][keys.size()];
//		kvar = new double[5][keys.size()];
//		kcnt = new double[5][keys.size()];
//		for(int i=0;i<5;i++) for(int j=0;j<keys.size();j++) {
//		  kavg[i][j] = kvar[i][j] = kcnt[i][j] = 0;
//		}
		
		int m = 0;
		for(String s: keys){
			Field f = null;
			try {
				f = data.get(0).getClass().getField(s);
			} catch (NoSuchFieldException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();}

			double[] raw = new double[data.size()];
			double sum = 0;
			int i = 0;
			for(E d: data){
				try {
					raw[i] = f.getDouble(d);
					sum += raw[i];
				} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}
				i++;
			}
			//ここで，ようやくデータが揃った
			avg[m] = sum/data.size();
			cnt[m] = data.size();
			var[m] = 0;
			for(i=0;i<cnt[m];i++){
				var[m] += (avg[m]-raw[i])*(avg[m]-raw[i]);
			}
			var[m] /= cnt[m];
//			System.out.print(s+"  ");
//			System.out.println("Avg = "+avg[m]+"   Var = "+var[m]+"   Cnt = "+cnt[m]);
			
			m++;
		}

	}
	public void printAll(){
		for(String k : keys){
			System.out.println("["+k+"]  avg:"+getavg(k)+"   var:"+getvar(k)+"  cnt:"+(int)getcnt(k));
		}
	}
}
