/*
 * TSPFitness.java
 *
 * Created on March 25, 2006, 9:54 PM
 *
 * 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.TSPIntegerIndividual;
import cz.pcland.tsp.*;
import java.util.*;

/**
 *
 * @author petr
 */
public class TSPFitness implements Evaluator{
    TSPInstance instance = null;
    LengthMatrix lmatrix;
    
    public void setDataObject(Object instance){
        if(instance instanceof TSPInstance) {
            this.instance = (TSPInstance)instance;
        }
    }
 
    /**
     * Creates a new instance of TSPFitness
     */
    public TSPFitness() {
        
    }
    
    public void init(BaseIndividual[] population) {
        
    }
    public void onStart(BaseIndividual[] population){
        instance.computeMatrix();
        this.lmatrix = instance.lmatrix;
    }
    
    
    public void postEvaluate(BaseIndividual[] population, double min, double max) {
        for(int ii=0;ii<population.length;++ii){
            population[ii].setFitness( max -  population[ii].getFitness() );
        }
    }
    
    public double getEvaluation(BaseIndividual bi){
        //return 15.0d;
        
        TSPIntegerIndividual integerString = (TSPIntegerIndividual)bi;
        int[] str = integerString.getString();
        double sum = 0.0d;
        for(int ii=1;ii<integerString.getString().length;ii++){
            sum += this.lmatrix.data[str[ii]][str[ii-1]];
        }
        
        sum += this.lmatrix.data[str[0]][str[str.length-1]];

        return sum;
        
    }
    
    public boolean isEnd(BaseIndividual bi){
        return false;
    }
    
    public String toString(){
        return "TSP (integer) fitness";
    }
}
