package jimena.analysis;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import jimena.binaryrn.RegulatoryNetwork;
import jimena.calculationparameters.SSSearchParameters;
import jimena.libs.MathLib;
import jimena.simulation.StableSteadyState;

/**
 * A method to compare two networks with respect to their convergence behavior.
 * 
 * @author Stefan Karl, Department of Bioinformatics, University of Würzburg, stefan[dot]karl[at]uni-wuerzburg[dot]de
 * 
 */
public class ConvergenceComparator extends NetworkComparator {

    private final int THREADS = Runtime.getRuntime().availableProcessors();
    private int simulations;
    private SSSearchParameters parameters;

    public SSSearchParameters getSSSSearchParameters() {
        return parameters;
    }

    public int getSimulations() {
        return simulations;
    }

    /**
     * Creates a new network comparator which compares two networks with respect to their convergence behavior.
     * 
     * @param simulations
     *            Number of start vectors to runs.
     * @param parameters
     *            Parameters for the simulations.
     */
    public ConvergenceComparator(int simulations, SSSearchParameters parameters) {
        if (simulations <= 0) {
            throw new IllegalArgumentException("The number of simulations must be greater than 0.");
        }
        this.simulations = simulations;
        this.parameters = parameters;
    }

    /**
     * Returns the difference between two networks. The aspect which is considered for the comparison is given by the subclass.
     * 
     * @param n1
     *            One of the classes to compare.
     * @param n2
     *            One of the classes to compare.
     * @return The difference between the two networks
     */
    @Override
    public double[] differenceV(RegulatoryNetwork n1, RegulatoryNetwork n2) {
        ExecutorService threadPool = Executors.newFixedThreadPool(THREADS);
        StableSteadyState[] runsN1 = new StableSteadyState[simulations];
        StableSteadyState[] runsN2 = new StableSteadyState[simulations];

        for (int i = 0; i < simulations; i++) {
            double[] startValues = MathLib.randomVector(n1.nodeCount());

            RegulatoryNetwork networkN1 = n1.cloneClean();
            RegulatoryNetwork networkN2 = n2.cloneClean();

            networkN1.setValues(startValues);
            networkN2.setValues(startValues);

            // Not using the steadyStableState method avoids copying the networks
            runsN1[i] = new StableSteadyState(networkN1, parameters);
            runsN2[i] = new StableSteadyState(networkN2, parameters);

            threadPool.submit(runsN1[i]);
            threadPool.submit(runsN2[i]);
        }

        // Wait for termination of all calculations
        threadPool.shutdown();

        try {
            threadPool.awaitTermination(240, TimeUnit.HOURS);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        double sumOfDifference[] = new double[n1.nodeCount()];
        int counted = 0;
        for (int i = 0; i < simulations; i++) {
            if (runsN1[i].getResult() != null && runsN2[i].getResult() != null) {
                MathLib.addDoubleArraysUnchecked(sumOfDifference,
                        MathLib.squaredDifferenceUnchecked(runsN1[i].getResult(), runsN2[i].getResult()));
                counted++;
            }
        }
        
        MathLib.scaleUnchecked(sumOfDifference, 1d / counted);

        // System.out.println(counted);
        return sumOfDifference;
    }

}
