/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.approximatrix.draco.fit.statistics;

import com.approximatrix.draco.fit.LSFit;

public class DurbinWatsonStatistic extends ExtendedStatistic {

	private static final String NAME = "Durbin-Watson Statistic";
	
	public DurbinWatsonStatistic() {
		super();
	}
	
	public DurbinWatsonStatistic(LSFit analysis) {
		super(analysis);
		//this.value = compute();
	}
	
	public String getName() {
		return NAME;
	}

	public Number getValue() {
		if(value == null) {
			compute();
		}
		return value;
	}

	public void compute() {
		double numerator = 0.0;
		double denom = 0.0;
		
		if(this.analysis == null) return;
		
		double[] residuals = this.analysis.getResiduals();
		
		denom = residuals[0]*residuals[0];
		for(int i=1;i<residuals.length;i++) {
			numerator = numerator +
				(residuals[i]-residuals[i-1])*
				(residuals[i]-residuals[i-1]);
			
			denom = denom + residuals[i]*residuals[i];
		}
		
		if(denom != 0.0) {
			this.value = new Double(numerator/denom);
		} else {
			this.value = new Double(-1.0);
		}
	}
}
