package ac.essex.gp.genetics;

import ac.essex.gp.individuals.Individual;
import ac.essex.gp.params.GPParams;
import ac.essex.gp.tree.Node;
import ac.essex.gp.problems.Problem;
import ac.essex.gp.util.DataStack;

/**
 * <p/>
 * 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 2
 * of the License, or (at your option) any later version,
 * provided that any use properly credits the author.
 * 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 at http://www.gnu.org
 * </p>
 *
 * @author Olly Oechsle, University of Essex, Date: 15-Jan-2007
 * @version 1.0
 */
public class Crossover {

    //public static StatisticsSolver stats;

    public static boolean produceOffspring(Individual male, Individual female, GPParams params, Problem p) {

        // get random subtree from the male individual
        Node maleNode = male.getRandomSubtree(GPParams.ANY_RETURN_TYPE, 1.0);

        if (maleNode == null) return false;

        // get one from female, but ensure they match (in terms of return type AND size)
        //Node femaleNode = female.getRandomSubtree(maleNode.getReturnType(), 1.0, maleNode.getTreeSize());
        Node femaleNode = female.getRandomSubtree(maleNode.getReturnType(), 1.0);

        if (femaleNode == null) return false;

        // save parents (replacechild updates them)
        Node maleParent = maleNode.getParent();
        Node femaleParent = femaleNode.getParent();

        if (maleParent == null) System.out.println("MALE PARENT IS NULL");
        if (femaleParent == null) System.out.println("FEMALE PARENT IS NULL");

        // swap subtrees
        maleParent.replaceChild(maleNode, femaleNode);
        femaleParent.replaceChild(femaleNode, maleNode);

        double minFitness = Math.min(male.getHits(), female.getHits());

        p.evaluate(male, new DataStack());
        p.evaluate(female, new DataStack());       

        double maleFitnessChange = male.getHits() - minFitness;
        double femaleFitnessChange = female.getHits() - minFitness;

        //stats.addData(maleFitnessChange);
        //stats.addData(femaleFitnessChange);

        return true;

    }

    //public static void resetStatistics() {
    //    stats = new StatisticsSolver(200);
    //}



}
