/*
 * FunctionFitness.java
 *
 * Created on March 7, 2006, 10:56 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cz.pcland.ga.fitness;
import cz.pcland.ga.BaseIndividual;
import cz.pcland.ga.BinaryIndividual;
import java.util.*;
import cz.pcland.functions.lexan.*;
import cz.pcland.functions.nodes.*;
import cz.pcland.functions.syntax.*;
import cz.pcland.functions.*;
/**
 *
 * @author petr
 */
public class FunctionFitnessNaive extends BaseFunctionFitness implements Evaluator{
    
    public void init(BaseIndividual[] population) {
        
    }
    public void onStart(BaseIndividual[] population){
        
    }
    
    public void postEvaluate(BaseIndividual[] population, double min, double max) {
        
        for(int ii=0;ii<population.length;++ii){
            if(population[ii].getEvaluation() == Double.NaN || population[ii].getEvaluation() == Double.NEGATIVE_INFINITY) {
                population[ii].setFitness(0);
                population[ii].setEvaluation(0);
            }
            
            population[ii].setFitness( population[ii].getFitness()+Math.abs(min) );
        }
        
        
    }
    
    public double decode(BaseIndividual str) {
        String res = "";
        boolean[] bits = ((BinaryIndividual)str).getString();
        //boolean negated = bits[0];
        
        for(int i=0;i<bits.length;i++){
            if(bits[i])res+="1"; else res+="0";
        }
        
        double value = 0;
        try{
            value = Double.parseDouble(Integer.valueOf(res,2).toString());
        }catch(NumberFormatException e){
            System.out.println("Error during binary string to double conversion in functionfitness");
        }
        //if(!negated)return value; else return -value;
        return value;
    }
    
    
    
    public double getFunctionValue(double xValue){
        
        // System.out.println("MAX: " + max);
        
        // System.out.println("computed: " + computed);
        //if(computed == 0)computed = 0.00000000001;
        
        double value = instance.node.evaluate(xValue, "x");
        return value;
    }
    
    public double getEvaluation(BaseIndividual str){
        double value = decode(str);
        value = convertValueToInterval(value);
        value = getFunctionValue(value);
        if(value != Double.NEGATIVE_INFINITY && value != Double.POSITIVE_INFINITY && value != Double.NaN){
            return value;
        }else {
            return Double.NaN;
        }
        //  if(value < minimum) minimum = value;
    }
    
    
    public String toString(){
        return "Function's fitness";
    }
    
    
    
    public boolean isEnd(BaseIndividual bi){
        return false;
    }
    
    /** Creates a new instance of FunctionFitness */
    public FunctionFitnessNaive() {
    }
    
}
