package jimena.analysis;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import jimena.binarybf.actinhibitf.ActivatorInhibitorFunction;
import jimena.binaryrn.Input;
import jimena.binaryrn.NetworkInput;
import jimena.binaryrn.NetworkNode;
import jimena.binaryrn.RegulatoryNetwork;
import jimena.calculationparameters.SSSSearchParameters;
import jimena.libs.ArrayLib;
import jimena.libs.MathLib;
import jimena.simulation.StableSteadyState;

public class FunctionsAnalysis {
    public class MinInfluence implements Runnable {
        private RegulatoryNetwork network;
        private NetworkInput input = null;
        private int node = -1;
        private Set<Integer> nodesToConsider;
        private Set<Integer> protectedNodes;
        private SSSSearchParameters parameters;
        private int simulations;
        private BooleanValue aborted = new BooleanValue(false);

        private double result = Double.NaN;

        public MinInfluence(RegulatoryNetwork network, int node, SSSSearchParameters parameters, Set<Integer> nodesToConsider,
                int simulations, Set<Integer> protectedNodes) {
            this.network = network;
            this.node = node;
            this.nodesToConsider = nodesToConsider;
            this.parameters = parameters;
            this.simulations = simulations;
            this.protectedNodes = protectedNodes;
        }

        public MinInfluence(RegulatoryNetwork network, NetworkInput input, SSSSearchParameters parameters, Set<Integer> nodesToConsider,
                int simulations, Set<Integer> protectedNodes) {
            this.network = network;
            this.input = input;
            this.nodesToConsider = nodesToConsider;
            this.parameters = parameters;
            this.simulations = simulations;
            this.protectedNodes = protectedNodes;
        }

        public void abort() {
            this.aborted.setValue(true);
        }

        public double getResult() {
            return result;
        }

        @Override
        public void run() {
            if (aborted.getValue()) {
                result = Double.NaN;
                return;
            }

            double[] initialVector = MathLib.randomVector(network.nodeCount());
            if (input != null) {
                result = minInfluence(network, input, initialVector, simulations, parameters, nodesToConsider, protectedNodes, aborted);
            } else {
                result = minInfluence(network, node, initialVector, simulations, parameters, nodesToConsider, protectedNodes, aborted);
            }
        }
    }

    private final static int THREADS = Runtime.getRuntime().availableProcessors();

    public static void abortAll(MinInfluence[] runs) {
        for (MinInfluence run : runs) {
            run.abort();
        }
    }

    public static double[] centralitiesFromMatrix(double[][] matrix) {
        return centralitiesFromMatrix(matrix, MathLib.numberSet(matrix.length - 1));
    }

    public static double[] centralitiesFromMatrix(double[][] matrix, Set<Integer> nodesToConsider) {
        if (matrix == null) {
            return null;
        }

        double[] result = new double[matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            result[i] = centralityFromMatrix(matrix, i, nodesToConsider);
        }
        return result;
    }

    public static double centralityFromMatrix(double[][] matrix, int node) {
        return centralityFromMatrix(matrix, node, MathLib.numberSet(matrix.length - 1));
    }

    public static double centralityFromMatrix(double[][] matrix, int node, Set<Integer> nodesToConsider) {
        if (matrix == null) {
            return Double.NaN;
        }

        double result = 0;
        int counter = 0;
        for (Integer i : nodesToConsider) {
            result += matrix[node][i];
            counter++;
        }
        return result / counter;
    }

    public static int countOpen(MinInfluence[] runs) {
        int counter = 0;
        for (MinInfluence run : runs) {
            if (Double.isNaN(run.getResult())) {
                counter++;
            }
        }
        return counter;
    }

    public static double[] totalCentralities(RegulatoryNetwork network, NetworkComparator comparator) {
        return centralitiesFromMatrix(totalCentralityMatrix(network, comparator));
    }

    public static double[] nonDynamicCentralities(RegulatoryNetwork network, int simulations, SSSSearchParameters parameters) {
        return centralitiesFromMatrix(nonDynamicCentralityMatrix(network, simulations, parameters));
    }

    public static double[] dynamicCentralities(RegulatoryNetwork network, int simulations, int innersimulations,
            SSSSearchParameters parameters) {
        return dynamicCentralities(network, simulations, innersimulations, parameters, network.setOfAllNodeIndices());
    }

    public static double[] dynamicCentralities(RegulatoryNetwork network, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider) {
        double[] influences = new double[network.nodeCount()];
        for (int i = 0; i < network.nodeCount(); i++) {
            influences[i] = dynamicCentrality(network, i, simulations, innersimulations, parameters, nodesToConsider);

        }
        return influences;
    }

    public static double dynamicCentrality(RegulatoryNetwork network, int node, int simulations, int innersimulations,
            SSSSearchParameters parameters) {
        return dynamicCentrality(network, node, simulations, innersimulations, parameters, network.setOfAllNodeIndices());
    }

    public static double dynamicCentrality(RegulatoryNetwork network, int node, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider) {
        return dynamicCentrality(network, node, simulations, innersimulations, parameters, nodesToConsider, new TreeSet<Integer>());
    }

    public static double dynamicCentrality(RegulatoryNetwork network, int node, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes) {
        return dynamicCentrality(network, node, simulations, innersimulations, parameters, nodesToConsider, protectedNodes,
                Double.MAX_VALUE);
    }

    public static double dynamicCentrality(RegulatoryNetwork network, int node, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes, double threshold) {
        ExecutorService threadPool = Executors.newFixedThreadPool(THREADS);
        MinInfluence[] runs = new MinInfluence[simulations];

        FunctionsAnalysis enclosing = new FunctionsAnalysis();

        for (int i = 0; i < simulations; i++) {
            runs[i] = enclosing.new MinInfluence(network, node, parameters, nodesToConsider, innersimulations, protectedNodes);
            threadPool.submit(runs[i]);
        }

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

        while (!threadPool.isTerminated()) {
            double minResult = minResult(runs);

            if (minResult > threshold && !Double.isInfinite(minResult)) {
                abortAll(runs);
                try {
                    threadPool.awaitTermination(240, TimeUnit.HOURS);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                return minResult;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

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

        double sumOfDifference = 0;
        int counted = 0;
        for (int i = 0; i < simulations; i++) {
            if (!Double.isNaN(runs[i].getResult())) {
                sumOfDifference += runs[i].getResult();
                counted++;
            }
        }
        return sumOfDifference / counted;
    }

    public static double dynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations, int innersimulations,
            SSSSearchParameters parameters) {
        return dynamicCentrality(network, input, simulations, innersimulations, parameters, network.setOfAllNodeIndices());
    }

    public static double dynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider) {
        return dynamicCentrality(network, input, simulations, innersimulations, parameters, nodesToConsider, new TreeSet<Integer>());
    }

    public static double dynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes) {
        return dynamicCentrality(network, input, simulations, innersimulations, parameters, nodesToConsider, protectedNodes,
                Double.MAX_VALUE);
    }

    public static double dynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations, int innersimulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes, double threshold) {
        ExecutorService threadPool = Executors.newFixedThreadPool(THREADS);
        MinInfluence[] runs = new MinInfluence[simulations];

        FunctionsAnalysis enclosing = new FunctionsAnalysis();

        for (int i = 0; i < simulations; i++) {
            runs[i] = enclosing.new MinInfluence(network, input, parameters, nodesToConsider, innersimulations, protectedNodes);
            threadPool.submit(runs[i]);
        }

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

        while (!threadPool.isTerminated()) {
            double minResult = minResult(runs);

            if (minResult > threshold && !Double.isInfinite(minResult)) {
                abortAll(runs);
                try {
                    threadPool.awaitTermination(240, TimeUnit.HOURS);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                System.out.print(" <" + countOpen(runs) + "> ");

                return minResult;
            }

            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

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

        double sumOfDifference = 0;
        int counted = 0;
        for (int i = 0; i < simulations; i++) {
            if (!Double.isNaN(runs[i].getResult()) && !Double.isInfinite(runs[i].getResult())) {
                sumOfDifference += runs[i].getResult();
                counted++;
            }
        }
        return sumOfDifference / counted;
    }

    public static boolean isValid(double[] values) {
        if (values == null) {
            return false;
        }

        for (double value : values) {
            if (Double.isInfinite(value) || Double.isNaN(value)) {
                return false;
            }
        }
        return true;
    }

    public static String mathNumberFormat(double input) {
        return (String.valueOf(input)).replaceAll("E", "\\*^");
    }

    public static double minInfluence(RegulatoryNetwork network, int node, double[] initialVector, int simulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes, BooleanValue aborted) {
        RegulatoryNetwork network1 = network.cloneClean();
        RegulatoryNetwork network2 = network.cloneClean();

        int numberOfInputs = 0;
        for (NetworkInput input : network.getInputsBySource(node)) {
            splitInput(network1, input);
            splitInput(network2, input);
            network1.addNullMutation(input);
            numberOfInputs++;
        }

        double minInfluence = Double.NaN;

        // simulations = (int) (((double) simulations) * Math.pow(10, ((double) numberOfInputs) / 5));

        for (int i = 0; i < simulations; i++) {
            double[] initVector = initialVector.clone();

            for (NetworkInput input : network.getInputsBySource(node)) {
                if (!protectedNodes.contains(node)) {
                    initVector = ArrayLib.add(initVector, Math.random());
                } else {
                    initVector = ArrayLib.add(initVector, initVector[node]);
                }
            }

            network1.setValues(initVector);
            network2.setValues(initVector);

            StableSteadyState n1 = new StableSteadyState(network1, parameters);
            StableSteadyState n2 = new StableSteadyState(network2, parameters);

            n1.run();
            if (n1.getResult() != null) {
                n2.run();
            }

            if (n1.getResult() != null && n2.getResult() != null) {
                double diff = MathLib.meanSquaredDifferenceUnchecked(n1.getResult(), n2.getResult(), nodesToConsider);
                minInfluence = MathLib.min(minInfluence, diff);
            }

            if ((protectedNodes.contains(node) && minInfluence != Double.MAX_VALUE) || minInfluence < 1e-15) {
                break;
            }

            if (aborted.getValue()) {
                return Double.NaN;
            }
        }

        return minInfluence;
    }

    public static double minInfluence(RegulatoryNetwork network, NetworkInput input, double[] initialVector, int simulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider, Set<Integer> protectedNodes, BooleanValue aborted) {
        int source = network.getInput(input).getSource();

        RegulatoryNetwork network1 = network.cloneClean();
        RegulatoryNetwork network2 = network.cloneClean();

        splitInput(network1, input);
        splitInput(network2, input);

        network1.addNullMutation(input);

        double minInfluence = Double.POSITIVE_INFINITY;

        // simulations = (int) (((double) simulations) * Math.pow(10, ((double) numberOfInputs) / 5));

        for (int i = 0; i < simulations; i++) {
            double[] initVector = initialVector.clone();
            if (!protectedNodes.contains(source)) {
                initVector = ArrayLib.add(initVector, Math.random());
            } else {
                initVector = ArrayLib.add(initVector, initVector[source]);
            }

            network1.setValues(initVector);
            network2.setValues(initVector);

            StableSteadyState n1 = new StableSteadyState(network1, parameters);
            StableSteadyState n2 = new StableSteadyState(network2, parameters);

            n1.run();
            if (n1.getResult() != null) {
                n2.run();
            }

            if (n1.getResult() != null && n2.getResult() != null) {
                double diff = MathLib.meanSquaredDifferenceUnchecked(n1.getResult(), n2.getResult(), nodesToConsider);
                minInfluence = MathLib.min(minInfluence, diff);
            }

            if ((protectedNodes.contains(source) && minInfluence != Double.MAX_VALUE) || minInfluence < 1e-15) {
                break;
            }

            if (aborted.getValue()) {
                return Double.NaN;
            }
        }

        return minInfluence;
    }

    public static double minResult(MinInfluence[] runs) {
        double sumOfDifference = 0;
        for (int i = 0; i < runs.length; i++) {
            if (!Double.isNaN(runs[i].getResult())) {
                sumOfDifference += runs[i].getResult();
            }
        }

        return sumOfDifference / runs.length;// counted kürzt sich weg
    }

    public static double nonDynamicCentrality(RegulatoryNetwork network, int node, int simulations, SSSSearchParameters parameters) {
        return nonDynamicCentrality(network, node, simulations, parameters, network.setOfAllNodeIndices());
    }

    public static double nonDynamicCentrality(RegulatoryNetwork network, int node, int simulations, SSSSearchParameters parameters,
            Set<Integer> nodesToConsider) {
        double[] temp = nonDynamicCentralityVector(network, node, simulations, parameters);
        double result = 0;
        int counter = 0;
        for (Integer i : nodesToConsider) {
            result += temp[i];
            counter++;
        }
        return result / counter;
    }

    public static double nonDynamicCentrality(RegulatoryNetwork network, int simulations, SSSSearchParameters parameters) {
        double sum = 0;
        for (int i = 0; i < network.nodeCount(); i++) {
            sum += nonDynamicCentrality(network, i, simulations, parameters);
        }
        return sum / network.nodeCount();
    }

    public static double nonDynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations, SSSSearchParameters parameters) {
        return MathLib.average(nonDynamicCentralityVector(network, input, simulations, parameters));
    }

    public static double nonDynamicCentrality(RegulatoryNetwork network, NetworkInput input, int simulations,
            SSSSearchParameters parameters, Set<Integer> nodesToConsider) {
        return MathLib.average(nonDynamicCentralityVector(network, input, simulations, parameters), nodesToConsider);
    }

    public static double[][] nonDynamicCentralityMatrix(RegulatoryNetwork network, int simulations, SSSSearchParameters parameters) {
        double[][] matrix = new double[network.nodeCount()][];
        for (int i = 0; i < network.nodeCount(); i++) {
            // System.out.print("#");
            matrix[i] = nonDynamicCentralityVector(network, i, simulations, parameters);
            while (!isValid(matrix[i])) {
                matrix[i] = nonDynamicCentralityVector(network, i, simulations, parameters);
            }
        }
        return matrix;
    }

    public static double[] nonDynamicCentralityVector(RegulatoryNetwork network, int node, int simulations, SSSSearchParameters parameters) {
        ExecutorService threadPool = Executors.newFixedThreadPool(THREADS);
        StableSteadyState[] runsN1 = new StableSteadyState[simulations];
        StableSteadyState[] runsN2 = new StableSteadyState[simulations];

        for (int i = 0; i < simulations; i++) {
            double[] startValues1 = MathLib.randomVector(network.nodeCount());
            double[] startValues2 = startValues1.clone();
            startValues2[node] = Math.random();

            RegulatoryNetwork networkN1 = network.cloneClean();
            RegulatoryNetwork networkN2 = network.cloneClean();

            networkN1.setValues(startValues1);
            networkN2.setValues(startValues2);

            // 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[network.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);

        return sumOfDifference;
    }

    public static double[] nonDynamicCentralityVector(RegulatoryNetwork network, NetworkInput input, int simulations,
            SSSSearchParameters parameters) {
        int source = network.getInput(input).getSource();
        ExecutorService threadPool = Executors.newFixedThreadPool(THREADS);
        StableSteadyState[] runsN1 = new StableSteadyState[simulations];
        StableSteadyState[] runsN2 = new StableSteadyState[simulations];

        for (int i = 0; i < simulations; i++) {
            double[] startValues1 = MathLib.randomVector(network.nodeCount());
            double[] startValues2 = startValues1.clone();

            startValues1 = ArrayLib.add(startValues1, startValues1[source]);
            startValues2 = ArrayLib.add(startValues2, Math.random());

            RegulatoryNetwork networkN1 = network.cloneClean();
            RegulatoryNetwork networkN2 = network.cloneClean();

            splitInput(networkN1, input);
            splitInput(networkN2, input);

            networkN1.setValues(startValues1);
            networkN2.setValues(startValues2);

            // 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[network.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);

        return sumOfDifference;
    }

    public static double[] sensitivitiesFromMatrix(double[][] matrix) {
        if (matrix == null) {
            return null;
        }

        double[] result = new double[matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            result[i] = sensitivityFromMatrix(matrix, i);
        }
        return result;
    }

    public static double sensitivityFromMatrix(double[][] matrix, int node) {
        if (matrix == null) {
            return Double.NaN;
        }

        double result = 0;
        for (int i = 0; i < matrix.length; i++) {
            result += matrix[i][node];
        }

        return result / matrix.length;
    }

    public static void splitInput(RegulatoryNetwork network, NetworkInput input) {
        int source = network.getInput(input).getSource();
        network.setNetworkNodes(ArrayLib.add(network.getNetworkNodes(), network.getNetworkNodes()[source].clone()));
        network.getInput(input).setSource(network.nodeCount() - 1);
        for (Input i : network.getNetworkNodes()[network.nodeCount() - 1].getInputs()) {
            if (i.getSource() == source) {
                i.setSource(network.nodeCount() - 1);
            }
        }
    }

    public static double totalCentrality(RegulatoryNetwork network, int node, int simulations, NetworkComparator comparator,
            Set<Integer> nodesToConsider) {
        double[] temp = totalCentralityVector(network, node, comparator);
        double result = 0;
        int counter = 0;
        for (Integer i : nodesToConsider) {
            result += temp[i];
            counter++;
        }
        return result / counter;
    }

    /**
     * The influence of a node on the network.
     * 
     * @param network
     *            The network to consider
     * @param node
     *            The node to consider
     * @param comparator
     *            The comparator to use
     * @return Influence of the node on the network.
     */
    public static double totalCentrality(RegulatoryNetwork network, int node, NetworkComparator comparator) {
        return totalCentrality(network, node, comparator, network.setOfAllNodeIndices());
    }

    /**
     * The influence of a node on the network.
     * 
     * @param network
     *            The network to consider
     * @param node
     *            The node to consider
     * @param comparator
     *            The comparator to use
     * @param nodesToConsider
     *            The nodes to consider in the comparison
     * @return Influence of the node on the network.
     */
    public static double totalCentrality(RegulatoryNetwork network, int node, NetworkComparator comparator, Set<Integer> nodesToConsider) {
        ArrayList<NetworkInput> inputs = network.getInputsBySource(node);

        RegulatoryNetwork mutated = network.cloneClean();
        mutated.addNullMutation(inputs);

        return comparator.difference(network, mutated, nodesToConsider);
    }

    public static double totalCentrality(RegulatoryNetwork network, NetworkComparator comparator) {
        double sum = 0;
        for (int i = 0; i < network.nodeCount(); i++) {
            sum += totalCentrality(network, i, comparator);
            if (Double.isNaN(sum)) {
                break;
            }
        }
        return sum / network.nodeCount();
    }

    /**
     * The total influence of an input on the network.
     * 
     * @param network
     *            The network to consider
     * @param input
     *            The input to consider
     * @param comparator
     *            The comparator to use
     * @return Influence of the input on the network.
     */
    public static double totalCentrality(RegulatoryNetwork network, NetworkInput input, NetworkComparator comparator) {
        return totalCentrality(network, input, comparator, network.setOfAllNodeIndices());
    }

    /**
     * The influence of an input on the network.
     * 
     * @param network
     *            The network to consider
     * @param input
     *            The input to consider
     * @param comparator
     *            The comparator to use
     * @param nodesToConsider
     *            The nodes to consider in the comparison
     * @return Influence of the input on the network.
     */
    public static double totalCentrality(RegulatoryNetwork network, NetworkInput input, NetworkComparator comparator,
            Set<Integer> nodesToConsider) {
        RegulatoryNetwork mutated = network.cloneClean();
        mutated.addNullMutation(input);
        return comparator.difference(network, mutated, nodesToConsider);
    }

    public static double[][] totalCentralityMatrix(RegulatoryNetwork network, NetworkComparator comparator) {
        double[][] matrix = new double[network.nodeCount()][];
        for (int i = 0; i < network.nodeCount(); i++) {
            // System.out.print("#");
            matrix[i] = totalCentralityVector(network, i, comparator);
            while (!isValid(matrix[i])) {
                matrix[i] = totalCentralityVector(network, i, comparator);
            }
        }
        return matrix;
    }

    /**
     * The influence of a node on the network.
     * 
     * @param network
     *            The network to consider
     * @param node
     *            The node to consider
     * @param comparator
     *            The comparator to use
     * @return Influence of the node on the network.
     */
    public static double[] totalCentralityVector(RegulatoryNetwork network, int node, NetworkComparator comparator) {
        ArrayList<NetworkInput> inputs = network.getInputsBySource(node);

        RegulatoryNetwork mutated = network.cloneClean();
        mutated.addNullMutation(inputs);

        return comparator.differenceV(network, mutated);
    }

    public static double[] pharmacologicalCentralityVector(RegulatoryNetwork network, int node, int simulations,
            SSSSearchParameters parameters) {
        network.printNetwork();

        RegulatoryNetwork pharmNetwork = network.cloneClean();

        ActivatorInhibitorFunction newNodeFunction = new ActivatorInhibitorFunction(new boolean[] { true });
        Input newNodeInput = new Input(network.nodeCount());
        Input[] newNodeInputs = new Input[] { newNodeInput };
        NetworkNode newN = new NetworkNode("drug", newNodeFunction, newNodeInputs, new Rectangle2D.Double(0, 0, 0, 0), 0,
                network.getTimeIndex());

        pharmNetwork.setNetworkNodes(ArrayLib.add(pharmNetwork.getNetworkNodes(), newN));

        if (!(pharmNetwork.getNetworkNodes()[node].getFunction() instanceof ActivatorInhibitorFunction)) {
            throw new IllegalArgumentException("The network must be an activator-inhibitor-network.");
        }

        ActivatorInhibitorFunction f = ((ActivatorInhibitorFunction) pharmNetwork.getNetworkNodes()[node].getFunction());
        ActivatorInhibitorFunction newF = new ActivatorInhibitorFunction(ArrayLib.add(f.getActivators(), true));
        Input newInput = new Input(network.nodeCount());
        Input[] newInputs = ArrayLib.add(pharmNetwork.getNetworkNodes()[node].getInputs(), newInput);

        NetworkNode oldNode = pharmNetwork.getNetworkNodes()[node];
        NetworkNode newNode = new NetworkNode(oldNode.getName(), oldNode.getValue(), oldNode.getOdefyDecay(), oldNode.getSQUADDecay(),
                oldNode.getSQUADSteepness(), newF, newInputs, oldNode.getRectangle(), oldNode.getHillNormalize(), ArrayLib.add(
                        oldNode.getHillNs(), oldNode.STDHILLN), ArrayLib.add(oldNode.getHillKs(), oldNode.STDHILLK), ArrayLib.add(
                        oldNode.getSQUADWeights(), oldNode.STDSQUADWEIGHT*100), oldNode.getInitialValue(), oldNode.getPerturbations(),
                network.getTimeIndex(), oldNode.getLog());

        
        
        pharmNetwork.getNetworkNodes()[node] = newNode;

        pharmNetwork.printNetwork();
        
        double[] result = Arrays.copyOf( nonDynamicCentralityVector(pharmNetwork, network.nodeCount(), simulations, parameters), network.nodeCount());

        return result;
    }

    public static double[][] pharmacologicalCentralityMatrix(RegulatoryNetwork network, int simulations, SSSSearchParameters parameters) {
        double[][] matrix = new double[network.nodeCount()][];
        for (int i = 0; i < network.nodeCount(); i++) {
            matrix[i] = pharmacologicalCentralityVector(network, i, simulations, parameters);
            while (!isValid(matrix[i])) {
                matrix[i] = pharmacologicalCentralityVector(network, i, simulations, parameters);
            }
        }
        
        System.out.println(matrix.length+"|"+matrix[0].length);
        
        return matrix;
    }

}
