/*
 *  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.functions;

import umontreal.iro.lecuyer.util.Num;

import com.approximatrix.draco.fit.RunLS;

public class ProbitLikelihood extends SimpleLikelihood implements LikelihoodFunction {

	private static final String FUNCTION_NAME = "Probit";
	
	public ProbitLikelihood() {
		// Dummy
	}
	
	/** Returns the CDF value at the given variable position based on the specified
	 * parameters.
	 * 
	 * @see http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function
	 */
	public double evaluateFunction(double[] parameters, double[] variables) {
		return 0.5*(1.0+Num.erf(calculateLinearTerm(parameters,variables)/Math.sqrt(2.0)));
	}

	/** Never called ... */
	public double evaluateLikelihood(double[] parameters,
			double[][] independent, double[] dependent) {
		return 0;
	}

	public String getLikelihoodType() {
		return FUNCTION_NAME;
	}

	public double[] initializeParameters(double[] dependent,
			double[][] independent) {
		double[] results = RunLS.SimpleLS(independent, dependent);
		if(results == null) return null;
		return results;
	}

	@Override
	protected double evaluatePDF(double[] parameters, double[] variables) {
		double linterm = this.calculateLinearTerm(parameters, variables);
		double exponential = Math.exp(linterm*linterm/(-2.0));
		return exponential/Math.sqrt(2.0*Math.PI);
	}

}
