package com.approximatrix.draco.fit;

import static org.junit.Assert.*;
import org.junit.Test;

public class RunNLLSTest extends RegressionTestSkeleton  {

	/** A weaker delta is used since this is an imperfect calculation */
	private static final double DELTA_NLLS = 1.0E-5;
	
	@Test
	public void testRunNLLSNoInt1() {
		String equation = "alpha*x";
		String[] parameters = new String[1]; parameters[0] = "alpha";
		double[] estimates = new double[1];  estimates[0] = 1.75;
		
		RunNLLS analysis = new RunNLLS(super.noint1,"y",equation,parameters,estimates,1.0);
		analysis = runIterations(analysis,10,false);
		assertNotNull(analysis);
		
		double[] coef = analysis.getCoef();
		assertCloseTo(2.07438016528926,coef[0],DELTA_NLLS);
		
		double[] var = analysis.getCoefVariances();
		assertCloseTo(0.165289256198347E-01*0.165289256198347E-01,var[0],DELTA_NLLS);
	}
	
	//@Test
	public void testRunNLLSMisra1a() {
		String equation = "a*(1.0-exp(-1.0*b*x))";
		String[] parameters = new String[2]; parameters[0] = "a"; parameters[1] = "b";
		double[] estimates = new double[2];  estimates[0] = 250.0; estimates[1] = 0.0005;
		
		RunNLLS analysis = new RunNLLS(super.misra1a,"y",equation,parameters,estimates,1.0);
		analysis = runIterations(analysis,10,false);
		assertNotNull(analysis);
		
		double[] coef = analysis.getCoef();
		assertCloseTo(2.3894212918E+02,coef[0],DELTA_NLLS);
		assertCloseTo(5.5015643181E-04,coef[1],DELTA_NLLS);
		
		double[] var = analysis.getCoefVariances();
		assertCloseTo(2.7070075241E+00*2.7070075241E+00,var[0],DELTA_NLLS);
		assertCloseTo(7.2668688436E-06*7.2668688436E-06,var[1],DELTA_NLLS);
	}
	
	private RunNLLS runIterations(RunNLLS analysis, int iterations, boolean ignore_conditioning) {
		for(int i=0;i<iterations-1;i++) {
			analysis.setIgnoreConditioning(ignore_conditioning);
			analysis.perform();
			if(!analysis.success)
				return null;
			analysis = new RunNLLS(analysis);
		}
		analysis.setIgnoreConditioning(ignore_conditioning);
		analysis.perform();
		if(!analysis.success)
			return null;
		
		return analysis; 
	}
	
}
