package ac.essex.ooechs.ecj.ecj2java.example.functions;

import ec.EvolutionState;
import ec.Problem;
import ec.gp.GPData;
import ec.gp.ADFStack;
import ec.gp.GPIndividual;
import ac.essex.ooechs.ecj.ecj2java.example.data.DoubleData;
import ac.essex.ooechs.ecj.ecj2java.nodes.ParseableGPNode;

/**
 * <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: 08-Dec-2006
 * @version 1.0
 */
public class Sqrt extends ParseableGPNode {

    public Sqrt() {
        // I have 1 child - this must match the type in the params file. It is ECJ's checking mechanism.
        super("sqrt", 1);
    }

    /**
     * Called as the function is evaluated.
     */
    public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) {

        DoubleData dd = ((DoubleData) (input));

        // evaluate the left child
        children[0].eval(state, thread, input, stack, individual, problem);

        // do a square root
        dd.x = dd.x > 0? Math.sqrt(dd.x) : 1;

    }

    public int getObjectType() {
        return ParseableGPNode.DOUBLE;
    }

    /**
     * Convert this code to pure Java
     */
    public String getJavaCode() {
        return getChild(0).getVariableName() + " > 0? Math.sqrt(" + getChild(0).getVariableName() + ") : 0";
    }

}
