package jimena.binaryrn;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
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.calculationparameters.SSSearchParameters;
import jimena.calculationparameters.SSSSimulationParameters;
import jimena.calculationparameters.SimulationParameters;
import jimena.libs.BDDLib;
import jimena.libs.DoubleValue;
import jimena.libs.MathLib;
import jimena.libs.StandardNumberFormat;
import jimena.libs.StringLib;
import jimena.perturbation.OnOffPerturbation;
import jimena.simulation.CalculationController;
import jimena.simulation.SSSFromStartVector;
import jimena.simulation.SimulatedAnnealingSSS;
import jimena.simulation.Simulator;
import jimena.simulation.StableSteadyState;
import jimena.simulationmethods.SimulationMethod;
import jimena.sssearcher.SSSearchResult;
import jimena.sssearcher.SSSearcher;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;

/**
 * Implements a binary regulatory network.
 * 
 * Please note that this class is NOT THREADSAFE. For multithreaded computation just copy the network with the clone[...]() function.
 * 
 * @author Stefan Karl, Department of Bioinformatics, University of Würzburg, stefan[dot]karl[at]uni-wuerzburg[dot]de
 * 
 */
public class RegulatoryNetwork implements Serializable {
    private static final long serialVersionUID = -3637940236128103506L;

    /**
     * Sets the names of all nodes in the network.
     * 
     * @param names
     *            The names to set.
     */
    public void setNames(ArrayList<String> names) {
        setNames(names.toArray(new String[names.size()]));
    }

    /**
     * Sets the names of all nodes in the network.
     * 
     * @param names
     *            The names to set.
     */
    public void setNames(String[] names) {
        if (names.length != networkNodes.length) {
            throw new IllegalArgumentException("The arrays must be of equal size.");
        }
        for (int i = 0; i < names.length; i++) {
            if (names[i] == null) {
                throw new IllegalArgumentException("A node name may not be null.");
            }
            for (int j = i + 1; j < names.length; j++) {
                if (names[i].equals(names[j])) {
                    throw new IllegalArgumentException("All node names must be different.");
                }
            }
            networkNodes[i].setName(names[i]);
        }
    }

    /**
     * Sorts the network nodes by their label.
     */
    public void sortNetworkNodes() {
        // Bubble sort
        boolean change = true;
        while (change) {
            change = false;
            for (int i = 0; i < this.nodeCount() - 1; i++) {
                if (getNetworkNodes()[i + 1].getName().compareTo(getNetworkNodes()[i].getName()) < 0) {
                    change = true;

                    NetworkNode tempNode = getNetworkNodes()[i + 1];
                    getNetworkNodes()[i + 1] = getNetworkNodes()[i];
                    getNetworkNodes()[i] = tempNode;

                    for (int j = 0; j < nodeCount(); j++) {
                        for (int k = 0; k < getNetworkNodes()[j].getInputs().length; k++) {
                            if (getNetworkNodes()[j].getInputs()[k].getSource() == i) {
                                getNetworkNodes()[j].getInputs()[k].setSource(i + 1);
                                continue;
                            }
                            if (getNetworkNodes()[j].getInputs()[k].getSource() == i + 1) {
                                getNetworkNodes()[j].getInputs()[k].setSource(i);
                                continue;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * A private function that checks the plausibility of some often used parameters.
     * 
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param simulationsPerInput
     *            Number of simulations per input
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxt
     *            The maximum simulated time
     */
    private static void checkParameters(double stabilityMaxDiff, double stabilityMinTime, int simulationsPerInput, SimulationMethod method,
            double dt, double maxt) {
        if (stabilityMaxDiff < 0 || stabilityMinTime <= 0 || simulationsPerInput <= 0 || dt <= 0 || maxt <= 0) {
            throw new IllegalArgumentException();
        }

        if (method == null) {
            throw new NullPointerException();
        }
    }

    private NetworkNode[] networkNodes = new NetworkNode[0];
    private transient HashSet<RegulatoryNetworkObserver> observers = new HashSet<RegulatoryNetworkObserver>();
    private DoubleValue timeIndex = new DoubleValue(0); // The same time index is held by the nodes.

    /**
     * Creates a new empty regulatory network.
     */
    public RegulatoryNetwork() {
    }

    /**
     * Creates a regulatory network from an array of network nodes. The observers are empty and the time index is set to 0. The
     * 
     * @param networkNodes
     *            The network nodes to use
     * @param timeIndex
     */
    public RegulatoryNetwork(NetworkNode[] networkNodes, DoubleValue timeIndex) {
        if (networkNodes == null || timeIndex == null) {
            throw new NullPointerException();
        }

        this.networkNodes = networkNodes;
        this.observers = new HashSet<RegulatoryNetworkObserver>();
        this.timeIndex = timeIndex;
    }

    /**
     * Adds an observer to this binary regulatory network. If the observer already exists it will be ignored.
     * 
     * @param observer
     *            The observer to add
     */
    public void addObserver(RegulatoryNetworkObserver observer) {
        if (observer == null) {
            throw new NullPointerException();
        }

        observers.add(observer);
    }

    /**
     * Calculates the stable state that is assumed starting from a set of given values. Please note that annealing does not seem to be
     * converging faster then mere simulation.
     * 
     * @param startValues
     *            The values to start from.
     * @param method
     *            The method to apply for the simulation
     * @param maxt
     *            The maximum annealing steps
     * @return An array with the results or null of the simulation did not converge in time.
     */
    public SSSFromStartVector annealingStableSteadyStateSearcher(double[] startValues, SimulationMethod method, long maxt) {
        // Check whether startValues == null is included here
        for (double value : startValues) {
            MathLib.checkNotNaNAndWithinRange(value, 0, 1);
        }
        if (method == null) {
            throw new NullPointerException();
        }
        if (maxt <= 0) {
            throw new IllegalArgumentException();
        }

        RegulatoryNetwork searchingNetwork = cloneClean();
        searchingNetwork.setValues(startValues);
        SimulatedAnnealingSSS stableSteadyState = new SimulatedAnnealingSSS(searchingNetwork, method, maxt);
        return stableSteadyState;
    }

    /**
     * Creates a deep copy of this regulatory network with a new time index, a new log and no observers.
     * 
     * @return The copied network.
     */
    public RegulatoryNetwork cloneClean() {
        DoubleValue timeIndex = new DoubleValue(0);
        NetworkNode[] copiedNetworkNodes = new NetworkNode[nodeCount()];

        for (int i = 0; i < copiedNetworkNodes.length; i++) {
            copiedNetworkNodes[i] = networkNodes[i].clone(timeIndex, false);
        }

        return new RegulatoryNetwork(copiedNetworkNodes, timeIndex);
    }

    /**
     * Returns a index which increases with the number of cycles the given network node is a member of.
     * 
     * If favorSmallCycles is set, small cycles increase the index more than large cycles (the increase is 1/(2^n) where n is the length of
     * the cycle). If it is not set, large and small cycles increase the index by 1.
     * 
     * @param node
     *            The node whose cycle membership is to be determined.
     * @param favorSmallCycles
     *            Whether small cycles increase the index more than large cycles (see above).
     * @return An index which increases with the number of cycles the given network node is a member of.
     */
    public double cycleIndex(int node, boolean favorSmallCycles) {
        if (node < 0 || node > networkNodes.length) {
            throw new IllegalArgumentException("The specified node does not exist in the network.");
        }
        LinkedList<Integer> visitedNodes = new LinkedList<Integer>();
        visitedNodes.add(node);
        return cycleIndex(visitedNodes, node, favorSmallCycles);
    }

    private double cycleIndex(LinkedList<Integer> visitedNodes, int node, boolean favorSmallCycles) {
        double result = 0;

        for (Integer source : networkNodes[node].getInputSources()) {
            if (visitedNodes.peekFirst() == source) {
                if (favorSmallCycles) {
                    result += 1.0 / Math.pow(2, visitedNodes.size());
                } else {
                    result += 1.0;
                }
                continue;
            }
            if (visitedNodes.contains(source)) {
                continue;
            }
            visitedNodes.add(source);
            result += cycleIndex(visitedNodes, source, favorSmallCycles);
            visitedNodes.removeLast();
        }

        return result;
    }

    //
    // /**
    // * Calculates an index for the stability of the network against the deletion of input connections. The index equals the mean deletion
    // * stability index of all inputs in the network
    // *
    // * @param stabilityMaxDiff
    // * The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
    // * stabilityMaxDiff*2
    // * @param stabilityMinTime
    // * Time the node has to spend in an epsilon neighborhood around a former value to assume stability
    // * @param simulationsPerInput
    // * Number of simulations per input
    // * @param method
    // * The method to apply for the simulation
    // * @param dt
    // * The time step in the simulation
    // * @param maxt
    // * The maximum simulated time
    // * @param minSuccesfulSimulations
    // * If less than minSuccesfulSimulations converge for the stability index calculation of ANY input, NaN will be returned
    // * @param calculationController
    // * A calculation controller or null for an uncontrolled calculation
    // * @param threads
    // * Threads used for the search
    // * @return The calculated index or NaN
    // */
    // public double deletionStabilityIndex(double stabilityMaxDiff, double stabilityMinTime, int simulationsPerInput,
    // SimulationMethod method, double dt, double maxt, int minSuccesfulSimulations, CalculationController calculationController,
    // int threads) {
    // // Calculate the mean deletion stability index of all inputs in the network
    // checkParameters(stabilityMaxDiff, stabilityMinTime, simulationsPerInput, method, dt, maxt);
    // if (minSuccesfulSimulations > simulationsPerInput) {
    // throw new IllegalArgumentException(
    // "MinSuccesfulSimulations is greater than simulationsPerInput. The calculation cannot succeed.");
    // }
    //
    // int totalInputs = 0;
    // for (int changedNode = 0; changedNode < nodeCount(); changedNode++) {
    // for (int changedInput = 0; changedInput < networkNodes[changedNode].getInputs().length; changedInput++) {
    // totalInputs++;
    // }
    // }
    //
    // double differenceSum = 0;
    // int simulatedInputs = 0;
    // for (int changedNode = 0; changedNode < nodeCount(); changedNode++) {
    // for (int changedInput = 0; changedInput < networkNodes[changedNode].getInputs().length; changedInput++) {
    // double inputDeletionStabilityIndex = deletionStabilityIndex(stabilityMaxDiff, stabilityMinTime, simulationsPerInput,
    // method, dt, maxt, changedNode, changedInput, minSuccesfulSimulations, threads);
    //
    // if (MathLib.isNaN(inputDeletionStabilityIndex)) {
    // return Double.NaN;
    // }
    //
    // simulatedInputs++;
    // differenceSum += inputDeletionStabilityIndex;
    //
    // if (calculationController != null) {
    // if (!calculationController.isOn()) {
    // return Double.NaN;
    // }
    // calculationController.setProgress(((double) simulatedInputs) / totalInputs, simulatedInputs * simulationsPerInput);
    // }
    // }
    // }
    //
    // if (calculationController != null) {
    // calculationController.notifyCalculationFinished();
    // }
    //
    // return differenceSum / totalInputs;
    // }
    //
    // /**
    // * Calculates the deletion stability index of a node by combining that of its outgoing connections.
    // *
    // * @param stabilityMaxDiff
    // * The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
    // * stabilityMaxDiff*2
    // * @param stabilityMinTime
    // * Time the node has to spend in an epsilon neighborhood around a former value to assume stability
    // * @param simulationsPerInput
    // * Number of simulations per input
    // * @param method
    // * The method to apply for the simulation
    // * @param dt
    // * The time step in the simulation
    // * @param maxt
    // * The maximum simulated time
    // * @param nodeIndex
    // * The node to analyze
    // * @param minSuccesfulSimulations
    // * If less than minSuccesfulSimulations converge for the stability index calculation of ANY input line originating from the
    // * given node, NaN will be returned
    // * @param average
    // * Whether the the sum or the average of the sss stabilities of the outgoing connections will be taken
    // * @param threads
    // * Threads used for the search
    // * @return The calculated index
    // */
    // public double deletionStabilityIndex(double stabilityMaxDiff, double stabilityMinTime, int simulationsPerInput,
    // SimulationMethod method, double dt, double maxt, int nodeIndex, int minSuccesfulSimulations, boolean average, int threads) {
    // // Calculate the mean deletion stability index of all inputs originating from the given node
    // checkParameters(stabilityMaxDiff, stabilityMinTime, simulationsPerInput, method, dt, maxt);
    // if (minSuccesfulSimulations > simulationsPerInput) {
    // throw new IllegalArgumentException(
    // "MinSuccesfulSimulations is greater than simulationsPerInput. The calculation cannot succeed.");
    // }
    //
    // int totalOutgoingConnections = 0;
    // double differenceSum = 0;
    //
    // for (int changedNode = 0; changedNode < nodeCount(); changedNode++) {
    // for (int changedInput = 0; changedInput < networkNodes[changedNode].getInputs().length; changedInput++) {
    // if (networkNodes[changedNode].getInputs()[changedInput].getSource() == nodeIndex) {
    // double inputDeletionStabilityIndex = deletionStabilityIndex(stabilityMaxDiff, stabilityMinTime, simulationsPerInput,
    // method, dt, maxt, changedNode, changedInput, minSuccesfulSimulations, threads);
    //
    // if (MathLib.isNaN(inputDeletionStabilityIndex)) {
    // return Double.NaN;
    // }
    //
    // differenceSum += inputDeletionStabilityIndex;
    // totalOutgoingConnections++;
    // }
    // }
    // }
    //
    // if (totalOutgoingConnections == 0) {
    // // The node has no outgoing connections
    // return 0;
    // }
    //
    // if (average) {
    // return differenceSum / totalOutgoingConnections;
    // } else {
    // return differenceSum;
    // }
    // }
    //

    /**
     * Simulates the network for number of times and returns the mean simulation time it took for the network to converge. Useful to choose
     * reasonable maxTime values for simulations.
     * 
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxt
     *            The maximum simulated time
     * @param simulations
     *            The number of initial configurations to simulate
     * @param threads
     *            Threads used for the search.
     * @param max
     *            Whether the maximum or the mean converging time is returned.
     * @return The mean converging time for all calculations.
     */
    public double convergingTime(double stabilityMaxDiff, double stabilityMinTime, SimulationMethod method, double dt, double maxt,
            int simulations, int threads, boolean max) {
        checkParameters(stabilityMaxDiff, stabilityMinTime, simulations, method, dt, maxt);

        ExecutorService threadPool = Executors.newFixedThreadPool(threads);
        StableSteadyState[] runs = new StableSteadyState[simulations];

        for (int i = 0; i < simulations; i++) {
            // Choose random values to start the simulation
            double[] startValues = MathLib.randomVector(nodeCount());

            // Run the simulation with the random start values
            RegulatoryNetwork network = cloneClean();

            network.setValues(startValues);

            runs[i] = new StableSteadyState(network, method, dt, maxt, stabilityMaxDiff, stabilityMinTime, null);
            threadPool.submit(runs[i]);
        }

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

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

        if (max) {
            // Return the maximum converging time
            double maximum = 0;
            for (int i = 0; i < simulations; i++) {
                maximum = Math.max(maximum, runs[i].getConvergingTime());
            }
            return maximum;
        } else {
            // Return the mean converging time
            double mean = 0;
            for (int i = 0; i < simulations; i++) {
                mean += runs[i].getConvergingTime();
            }

            return mean / simulations;
        }
    }

    /**
     * Disables the given input line.
     * 
     * @param node
     *            The node whose line is to be removed.
     * @param input
     *            The number of the input which is to be removed.
     */
    public void addNullMutation(int node, int input) {
        try {
            networkNodes[node].getInputs()[input].toString();
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException("The specified input does not exist in the network.");
        }
        networkNodes[node].getFunction().disableInput(input);
    }

    /**
     * Disables the given input line.
     * 
     * @param input
     *            The input which is to be removed.
     */
    public void addNullMutation(NetworkInput input) {
        addNullMutation(input.getNode(), input.getInput());
    }

    /**
     * Deletes several inputs from the network.
     * 
     * @param inputs
     *            The inputs to remove.
     */
    public void addNullMutation(List<NetworkInput> inputs) {
        for (NetworkInput input : inputs) {
            addNullMutation(input);
        }
    }

    /**
     * Calculates a deletion stability index between 0 and 1 for the given input line. If too few of the simulations converge Double.NaN is
     * returned.
     * 
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param simulationsPerInput
     *            Number of simulations per input
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxt
     *            The maximum simulated time
     * @param changedNode
     *            The node whose input is to be analyzed
     * @param changedInput
     *            The input of the node that is to be analyzed
     * @param minSuccesfulSimulations
     *            If less than minSuccesfulSimulations converge, NaN will be returned
     * @param threads
     *            Threads used for the search.
     * @param perturbateInputNodes
     *            Whether all input nodes to the network should be assigned fixed random values for the calculations
     * @return The deletion stability index of the node or Double.NaN if the analysis was unsuccessful.
     */
    public double deletionStabilityIndex(double stabilityMaxDiff, double stabilityMinTime, int simulationsPerInput,
            SimulationMethod method, double dt, double maxt, int changedNode, int changedInput, int minSuccesfulSimulations, int threads,
            boolean perturbateInputNodes) {
        // Simulate the original network and a network where the given input line is missing from the same random start values
        // The mean difference between SSS the simulation reaches is seen as an index for the deletion stability of the input

        try {
            networkNodes[changedNode].getInputs()[changedInput].toString();
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException("The specified input does not exist in the network.");
        }
        checkParameters(stabilityMaxDiff, stabilityMinTime, simulationsPerInput, method, dt, maxt);
        if (minSuccesfulSimulations > simulationsPerInput) {
            throw new IllegalArgumentException(
                    "MinSuccesfulSimulations is greater than simulationsPerInput. The calculation cannot succeed.");
        }

        int countedResults = 0;
        double result = 0;

        ExecutorService threadPool = Executors.newFixedThreadPool(threads);
        StableSteadyState[] originalNetworkSSSS = new StableSteadyState[simulationsPerInput];
        StableSteadyState[] crippledNetworkSSSS = new StableSteadyState[simulationsPerInput];

        // Create the crippled network by wiring the deactivated input to a dummy node.
        // The crippled network will be copied and filled with start values later
        RegulatoryNetwork crippledNetworkTemplate = cloneClean();
        crippledNetworkTemplate.addNullMutation(changedNode, changedInput);

        // Original network
        for (int i = 0; i < simulationsPerInput; i++) {
            // Choose random start values for both simulations
            double[] startValues = MathLib.randomVector(nodeCount());

            // Prepare the simulation of the original network
            RegulatoryNetwork originalNetwork = cloneClean();

            // Set fixed values for all nodes without inputs, so their output connections can have any long term influence
            // (besides outputing 0) and remove all other perturbations
            for (int j = 0; j < originalNetwork.nodeCount(); j++) {
                originalNetwork.getNetworkNodes()[j].getPerturbations().clear();
                if (perturbateInputNodes) {
                    if (originalNetwork.getNetworkNodes()[j].getInputs().length == 0) {
                        originalNetwork.getNetworkNodes()[j].getPerturbations().add(new OnOffPerturbation(startValues[j]));
                    }
                }
            }

            originalNetwork.setValues(startValues);

            originalNetworkSSSS[i] = new StableSteadyState(originalNetwork, method, dt, maxt, stabilityMaxDiff, stabilityMinTime, null);
            threadPool.submit(originalNetworkSSSS[i]);

            // Prepare the simulation of the crippled network
            RegulatoryNetwork crippledNetwork = crippledNetworkTemplate.cloneClean();

            for (int j = 0; j < crippledNetwork.nodeCount() - 1; j++) {
                crippledNetwork.getNetworkNodes()[j].getPerturbations().clear();
                if (perturbateInputNodes) {
                    if (crippledNetwork.getNetworkNodes()[j].getInputs().length == 0) {
                        crippledNetwork.getNetworkNodes()[j].getPerturbations().add(new OnOffPerturbation(startValues[j]));
                    }
                }
            }

            crippledNetwork.setValues(startValues);

            crippledNetworkSSSS[i] = new StableSteadyState(crippledNetwork, method, dt, maxt, stabilityMaxDiff, stabilityMinTime, null);
            threadPool.submit(crippledNetworkSSSS[i]);
        }

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

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

        // Compare the SSS of the original and the crippled network
        for (int i = 0; i < simulationsPerInput; i++) {
            double[] originalResult = originalNetworkSSSS[i].getResult(); // This array is shorter! (*)
            double[] crippledResult = crippledNetworkSSSS[i].getResult();

            if (originalResult != null && crippledResult != null) {
                countedResults++;
                result += MathLib.meanSquaredDifferenceUnchecked(originalResult, crippledResult); // The order is important because of (*)
            }
        }

        if (countedResults == 0) {
            return Double.NaN;
        }

        if (countedResults < minSuccesfulSimulations) {
            return Double.NaN;
        }

        return result / countedResults;
    }

    /**
     * Returns the stable steady states of the network if a discrete model is assumed.
     * 
     * @return An ArrayList of byte arrays with the stable steady states.
     */
    @SuppressWarnings("unchecked")
    public synchronized ArrayList<byte[]> discreteStableSteadyStates() {
        /*
         * We construct a BDD for the boolean expression that is true iff the results of all transition functions match the values of the
         * nodes they affect: (x1 <-> f1(x1, x2, ...) ^ x2 <-> f2(...)^ ...) where xi are the nodes and fi the transition functions.
         */
        BDDFactory bddFactory = BDDLib.getBDDFactory(); // A shortcut to the BDD factory

        // Create one BDD for each node
        bddFactory.setVarNum(nodeCount());
        BDD[] nodes = new BDD[nodeCount()];
        for (int i = 0; i < nodeCount(); i++) {
            nodes[i] = bddFactory.ithVar(i);
        }

        // Construct the expression by ANDing the subexpressions (xi <-> fi(x1, x2, ...) to the "true" literal
        BDD network = bddFactory.one();

        for (int i = 0; i < nodeCount(); i++) {
            // Create an array of input BDDs for the function fi
            BDD[] inputs = new BDD[networkNodes[i].getInputs().length];
            for (int j = 0; j < networkNodes[i].getInputs().length; j++) {
                inputs[j] = nodes[networkNodes[i].getInputs()[j].getSource()];
            }

            // Create a BDD for the function fi
            BDD functionBDD = networkNodes[i].getFunction().createBDD(inputs, bddFactory);

            // Create a BDD for the subexpression (xi <-> fi(x1, x2, ...)
            functionBDD = nodes[i].biimp(functionBDD);

            // Concatenate the function BDDs
            network.andWith(functionBDD);
        }

        // The arrays contain -1 (= arbitrary value) components, we expand those to full arrays.
        // E.g. (-1,1,0) => (1,1,0),(0,1,0)
        return MathLib.bddAllsatResultToArray((List<byte[]>) network.allsat());
    }

    /**
     * Returns a string representation of the function of a node.
     * 
     * @param node
     *            The node to consider.
     * @return String representation of the function.
     */
    public String getFunctionString(int node) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified node is not valid.");
        }

        String[] nodeNames = getNodeNames();

        String[] inputNodeNames = new String[networkNodes[node].getInputs().length];
        for (int j = 0; j < networkNodes[node].getInputs().length; j++) {
            inputNodeNames[j] = nodeNames[networkNodes[node].getInputs()[j].getSource()];
        }

        return networkNodes[node].getName() + " = " + networkNodes[node].getFunction().getFunctionString(inputNodeNames, false);
    }

    /**
     * Returns a Odefy compatible string representation of the function of a node.
     * 
     * @param node
     *            The node to consider.
     * @return String representation of the function.
     */
    public String getFunctionStringOdefyCompatible(int node) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified node is not valid.");
        }

        String[] nodeNames = getNodeNames();

        // Create an array of input BDDs for the function fi
        String[] inputNodeNames = new String[networkNodes[node].getInputs().length];
        for (int j = 0; j < networkNodes[node].getInputs().length; j++) {
            inputNodeNames[j] = nodeNames[networkNodes[node].getInputs()[j].getSource()];
        }

        return "'" + networkNodes[node].getName() + " = " + networkNodes[node].getFunction().getFunctionString(inputNodeNames, true) + "'";
    }

    /**
     * Returns a Odefy compatible string representation of network.
     * 
     * @return A string representation of network.
     */
    public String getNetworkStringOdefyCompatible() {
        String result = "expr = {";

        for (int i = 0; i < networkNodes.length; i++) {
            result = result + "\n" + getFunctionStringOdefyCompatible(i);
            if (i != networkNodes.length - 1) {
                result = result + ", ";
            }
        }
        result = result + "}";

        return result;
    }

    /**
     * Returns a string representation of network.
     * 
     * @return A string representation of network.
     */
    public String getNetworkString() {
        String result = new String();

        for (int i = 0; i < networkNodes.length; i++) {
            result = result + "\n" + getFunctionString(i);
        }

        return result;
    }

    /**
     * Prints a string representation of the network.
     */
    public void printNetwork() {
        System.out.println(getNetworkStringOdefyCompatible());
    }

    /**
     * Returns the set of input indexes to a node whose source nodes have a given name
     * 
     * @param node
     *            The node whose inputs are to be searched
     * @param name
     *            The input name to search for
     * @return A set of the matching inputs' indices
     */
    public TreeSet<Integer> getInputIndicesByName(int node, String name) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified network node was not found in the network.");
        }

        if (name == null) {
            throw new NullPointerException();
        }

        TreeSet<Integer> result = new TreeSet<Integer>();

        for (int i = 0; i < networkNodes[node].getInputs().length; i++) {
            if (StringLib.equalsTrimmed(getInputSourceName(node, i), name)) {
                result.add(i);
            }
        }

        return result;
    }

    /**
     * Returns the set of input indexes to a node whose source nodes have a given name
     * 
     * @param node
     *            The node whose inputs are to be searched
     * @param input
     *            The input name to search for
     * @return A set of the matching inputs' indices
     */
    public TreeSet<Integer> getInputIndicesByName(String node, String input) {
        return getInputIndicesByName(getNodeIndexByName(node), input);
    }

    /**
     * Return the index of the node who is the index-th input to the specified node.
     * 
     * @param node
     *            The node whose inputs are considered
     * @param index
     *            Index of the input
     * @return Index of the input node
     */
    public int getInputSourceIndex(int node, int index) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified network node was not found in the network.");
        }

        if (node < 0 || index >= networkNodes[node].getInputs().length) {
            throw new IllegalArgumentException("The specified input was not found in the node.");
        }

        return networkNodes[node].getInputs()[index].getSource();
    }

    /**
     * Return the index of the source to the specified input.
     * 
     * @param input
     *            The input to consider
     * @return Index of the input node
     */
    public int getInputSourceIndex(NetworkInput input) {
        return getInputSourceIndex(input.getNode(), input.getInput());
    }

    /**
     * Return the name of the source to the specified input.
     * 
     * @param input
     *            The input to consider
     * @return Name of the input node
     */
    public String getInputSourceName(NetworkInput input) {
        return getInputSourceName(input.getNode(), input.getInput());
    }

    /**
     * Return the name of the node who is the index-th input to the specified node.
     * 
     * @param node
     *            The node whose inputs are considered
     * @param index
     *            Index of the input
     * @return Name of the input node
     */
    public String getInputSourceName(int node, int index) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified network node was not found in the network.");
        }

        if (node < 0 || index >= networkNodes[node].getInputs().length) {
            throw new IllegalArgumentException("The specified input was not found in the node.");
        }

        return networkNodes[getInputSourceIndex(node, index)].getName();
    }

    /**
     * Return the network nodes of this networks.
     * 
     * @return Network nodes
     */
    public NetworkNode[] getNetworkNodes() {
        return networkNodes;
    }

    /**
     * Sets the network nodes of this networks.
     * 
     * @param networkNodes
     *            The network nodes to set.
     */
    public void setNetworkNodes(NetworkNode[] networkNodes) {
        this.networkNodes = networkNodes;
    }

    /**
     * Returns the network node with a given name.
     * 
     * @param name
     *            The name to search for
     * @return The network node with that name or an exception if no node was found
     */
    public NetworkNode getNodeByName(String name) {
        return networkNodes[getNodeIndexByName(name)];
    }

    /**
     * Returns the index of the network node with a given name.
     * 
     * @param name
     *            The name to search for
     * @return The index of the network node with that name or an exception if no node was found
     */
    public int getNodeIndexByName(String name) {
        for (int i = 0; i < networkNodes.length; i++) {
            if (StringLib.equalsTrimmed(networkNodes[i].getName(), name)) {
                return i;
            }
        }
        throw new IllegalArgumentException("Node not found.");
    }

    /**
     * Gets the names of the nodes.
     * 
     * @return An array of the names of the nodes.
     */
    public String[] getNodeNames() {
        String[] names = new String[nodeCount()];
        for (int i = 0; i < nodeCount(); i++) {
            names[i] = networkNodes[i].getName();
        }
        return names;
    }

    /**
     * Returns the observers of the network.
     * 
     * @return The observers of the network in a HashSet.
     */
    public HashSet<RegulatoryNetworkObserver> getObservers() {
        return observers;
    }

    /**
     * Returns the time index of this network.
     * 
     * @return The time index
     */
    public DoubleValue getTimeIndex() {
        return timeIndex;
    }

    /**
     * Returns the values of the nodes. You should not use this method to get a single value, but query the node instead.
     * 
     * @return An arrays of the values of the nodes.
     */
    public double[] getValues() {
        double[] result = new double[nodeCount()];
        for (int i = 0; i < nodeCount(); i++) {
            result[i] = networkNodes[i].getValue();
        }
        return result;
    }

    /**
     * Returns the values of the nodes. You should not use this method to get a single value, but query the node instead.
     * 
     * @return An arrays of the values of the nodes.
     */
    public double[] getValues(double[] target) {
        for (int i = 0; i < nodeCount(); i++) {
            target[i] = networkNodes[i].getValue();
        }
        return target;
    }

    /**
     * Returns whether the network is empty, i.e. it has no nodes.
     * 
     * @return True is the network is empty
     */
    public boolean isEmpty() {
        return nodeCount() == 0;
    }

    /**
     * Takes the nodes and the time index from a loaded network, keeping the current observers.
     * 
     * @param storedNetwork
     *            A network loaded from a file.
     */
    public void loadNetwork(RegulatoryNetwork storedNetwork) {
        // This automatically checks for storedNetwork = null
        networkNodes = storedNetwork.getNetworkNodes();
        timeIndex = storedNetwork.getTimeIndex();
        notifyObserversOfChangedNetwork();
    }

    /**
     * Parses a yED file into this network. The current content will be replaced. The time index is set to 0 and the observer are preserved.
     * 
     * @param file
     *            yED file
     */
    public void loadYEdFile(File file) {
        // Checks done by the parseYEdFile function
        timeIndex = new DoubleValue(0);
        try {
            networkNodes = RegulatoryNetworkLib.parseYEdFile(file, timeIndex);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

        notifyObserversOfChangedNetwork();
    }

    /**
     * Creates a log entries with the current values in all the nodes.
     */
    public void log() {
        for (NetworkNode node : networkNodes) {
            node.log();
        }
    }

    /**
     * The value of all nodes is set to 0 if it is < 0.5 and to 1 otherwise.
     */
    public void makeDiscrete() {
        for (NetworkNode node : networkNodes) {
            node.makeDiscrete();
        }
    }

    /**
     * Returns the number of node in the network.
     * 
     * @return Number of nodes
     */
    public int nodeCount() {
        return networkNodes.length;
    }

    /**
     * Notifies all observers that a change of the network structure has taken place.
     */
    public void notifyObserversOfChangedNetwork() {
        for (RegulatoryNetworkObserver observer : observers) {
            observer.notifyNetworkChanged();
        }
    }

    /**
     * Notifies all observers that a change of the network values has taken place.
     */
    public void notifyObserversOfChangedValues() {
        for (RegulatoryNetworkObserver observer : observers) {
            observer.notifyValuesChanged();
        }
    }

    /**
     * Removes all perturbation from the network.
     * 
     */
    public void removeAllPerturbations() {
        for (NetworkNode node : networkNodes) {
            node.getPerturbations().clear();
        }
    }

    /**
     * Removes an observer to this binary regulatory network. If the observer is not registered the command will be ignored.
     * 
     * @param observer
     *            The observer to remove
     */
    public void removeObserver(RegulatoryNetworkObserver observer) {
        if (observer == null) {
            throw new NullPointerException();
        }

        observers.remove(observer);
    }

    /**
     * Resets all values to the initial values, resets the logs and sets the time index to 0.
     */
    public void reset() {
        for (NetworkNode node : networkNodes) {
            node.reset();
            node.resetLog();
        }
        timeIndex.setValue(0D);
        notifyObserversOfChangedValues();
    }

    /**
     * Sets the observers of the network.
     * 
     * @param observers
     *            The observers of the network in a HashSet.
     */
    public void setObservers(HashSet<RegulatoryNetworkObserver> observers) {
        if (observers == null) {
            throw new NullPointerException();
        }

        this.observers = observers;
    }

    /**
     * Sets the values of the nodes.
     * 
     * @param values
     *            An arrays of the values of the nodes to set.
     */
    public void setValues(double[] values) {
        // This automatically checks for values = null, the values themselves are checked by the setValue function
        for (int i = 0; i < values.length; i++) {
            networkNodes[i].setValue(values[i]);
        }
    }

    /**
     * Simulate the the network for a given amount of time.
     * 
     * @param method
     *            The method to use
     * @param dt
     *            The time step
     * @param maxT
     *            The duration of the simulation (If the simulation uses discrete steps (maxt/dt) steps are done)
     * @param maxSpeed
     *            Maximum speed of the simulation
     * @param minSimulationTimeBetweenLogs
     *            Minimum (simulation) time between two log entries during the simulation.
     * @param calculationController
     *            A calculation controller or null for an uncontrolled calculation
     */
    public void simulate(SimulationMethod method, double dt, double maxT, double maxSpeed, double minSimulationTimeBetweenLogs,
            CalculationController calculationController) {
        simulate(new SimulationParameters(method, dt, maxT, calculationController), maxSpeed, minSimulationTimeBetweenLogs);
    }

    /**
     * Simulate the the network for a given amount of time.
     * 
     * @param parameters
     *            Parameters of the simulation
     * @param maxSpeed
     *            Maximum speed of the simulation
     * @param minSimulationTimeBetweenLogs
     *            Minimum (simulation) time between two log entries during the simulation.
     */
    public void simulate(SimulationParameters parameters, double maxSpeed, double minSimulationTimeBetweenLogs) {
        Simulator simulator = new Simulator(parameters, this, maxSpeed, minSimulationTimeBetweenLogs);
        simulator.start();
        try {
            simulator.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Calculates the stable state that is assumed starting from a set of given values.
     * 
     * @param startValues
     *            The values to start from
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxt
     *            The maximum simulated time
     * @param calculationController
     *            A calculation controller or null for an uncontrolled calculation
     * @return An array with the results or null of the simulation did not converge in time.
     */
    public double[] stableSteadyState(double[] startValues, double stabilityMaxDiff, double stabilityMinTime, SimulationMethod method,
            double dt, double maxt, CalculationController calculationController) {
        checkParameters(stabilityMaxDiff, stabilityMinTime, 1, method, dt, maxt);
        // Check whether startValues == null is included here
        for (double value : startValues) {
            MathLib.checkNotNaNAndWithinRange(value, 0, 1);
        }

        StableSteadyState stableSteadyState;
        stableSteadyState = stableSteadyStateSearcher(startValues, stabilityMaxDiff, stabilityMinTime, method, dt, maxt,
                calculationController);

        Thread stableSteadyStateThread = new Thread(stableSteadyState);
        stableSteadyStateThread.start();
        try {
            stableSteadyStateThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return stableSteadyState.getResult();
    }

    /**
     * Calculates the stable state that is assumed starting from a set of given values.
     * 
     * @param startValues
     *            The values to start from
     * @param p
     *            Parameters of the search
     * @return An array with the results or null of the simulation did not converge in time.
     */
    public double[] stableSteadyState(double[] startValues, SSSSimulationParameters p) {
        return stableSteadyState(startValues, p.getStabilityMaxDiff(), p.getStabilityMinTime(), p.getMethod(), p.getDt(), p.getMaxT(),
                p.getCalculationController());
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there.
     * 
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxT
     *            The maximum simulated time
     * @param duplicateMaxDiff
     *            Maximum difference for two components to be considered equal
     * @param maxTime
     *            The maximum time to search in ms
     * @param calculationController
     *            A calculation controller or null for an uncontrolled calculation
     * @param threads
     *            The number of threads used for the simulation
     * @param sssSearcher
     *            The stable steady state searcher to use
     * @return An ArrayList with the SSS found by the calculation.
     */
    public ArrayList<double[]> stableSteadyStates(double stabilityMaxDiff, double stabilityMinTime, SimulationMethod method, double dt,
            double maxT, double duplicateMaxDiff, long maxTime, CalculationController calculationController, int threads,
            SSSearcher sssSearcher) {
        return stableSteadyStatesWithBasins(stabilityMaxDiff, stabilityMinTime, method, dt, maxT, duplicateMaxDiff, maxTime,
                calculationController, threads, sssSearcher).getResults();
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there. Returns a the basins of attraction as well.
     * 
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxT
     *            The maximum simulated time
     * @param duplicateMaxDiff
     *            Maximum difference for two components to be considered equal
     * @param maxTime
     *            The maximum time to search in ms
     * @param calculationController
     *            A calculation controller or null for an uncontrolled calculation
     * @param threads
     *            The number of threads used for the simulation
     * @param sssSearcher
     *            The stable steady state searcher to use
     * @return An ArrayList with the SSS found by the calculation.
     */
    public SSSearchResult stableSteadyStatesWithBasins(double stabilityMaxDiff, double stabilityMinTime, SimulationMethod method,
            double dt, double maxT, double duplicateMaxDiff, long maxTime, CalculationController calculationController, int threads,
            SSSearcher sssSearcher) {
        checkParameters(stabilityMaxDiff, stabilityMinTime, 1, method, dt, maxT);
        if (duplicateMaxDiff < 0 || maxTime <= 0) {
            throw new IllegalArgumentException("Invalid SSS Search paremters.");
        }

        return stableSteadyStatesWithBasins(new SSSearchParameters(method, dt, maxT, calculationController, stabilityMaxDiff,
                stabilityMinTime, threads, duplicateMaxDiff), maxTime, sssSearcher);
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there.
     * 
     * @param parameters
     *            The search parameters.
     * @param maxTime
     *            The maximum time to search in ms
     * @param sssSearcher
     *            The stable steady state searcher to use
     * 
     * @return An ArrayList with the SSS found by the calculation.
     */
    public ArrayList<double[]> stableSteadyStates(SSSearchParameters parameters, long maxTime, SSSearcher sssSearcher) {
        return stableSteadyStatesWithBasins(parameters, maxTime, sssSearcher).getResults();
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there. Also returns the basins of attraction.
     * 
     * @param parameters
     *            The search parameters.
     * @param maxTime
     *            The maximum time to search in ms
     * @param sssSearcher
     *            The stable steady state searcher to use
     * 
     * @return An ArrayList with the SSS found by the calculation.
     */
    public SSSearchResult stableSteadyStatesWithBasins(SSSearchParameters parameters, long maxTime, SSSearcher sssSearcher) {
        return sssSearcher.searchSSStates(this, parameters, maxTime);
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there.
     * 
     * @param numberOfStarts
     *            The number of start vectors to simulate
     * @param parameters
     *            The search parameters.
     * @param sssSearcher
     *            The stable steady state searcher to use
     * 
     * @return An ArrayList with the SSS found by the calculation.
     */
    public ArrayList<double[]> stableSteadyStates(long numberOfStarts, SSSearchParameters parameters, SSSearcher sssSearcher) {
        return sssSearcher.searchSSStates(this, numberOfStarts, parameters).getResults();
    }

    /**
     * Calculates a subset of the stable steady states of this node by randomly choosing a set a set of start values and simulation from
     * there.
     * 
     * @param numberOfStarts
     *            The number of start vectors to simulate
     * @param parameters
     *            The search parameters.
     * @param sssSearcher
     *            The stable steady state searcher to use
     * 
     * @return An ArrayList with the SSS found by the calculation.
     */
    public SSSearchResult stableSteadyStatesWithCounter(long numberOfStarts, SSSearchParameters parameters, SSSearcher sssSearcher) {
        return sssSearcher.searchSSStates(this, numberOfStarts, parameters);
    }

    /**
     * Returns a SSS searcher with a copy of the network and the given start values.
     * 
     * @param startValues
     *            The values to start from.
     * @param stabilityMaxDiff
     *            The epsilon neighborhood around a former value which must not be left to assume stability has the diameter
     *            stabilityMaxDiff*2
     * @param stabilityMinTime
     *            Time the node has to spend in an epsilon neighborhood around a former value to assume stability
     * @param method
     *            The method to apply for the simulation
     * @param dt
     *            The time step in the simulation
     * @param maxt
     *            The maximum simulated time
     * @param calculationController
     *            A calculation controller or null for an uncontrolled calculation
     * @return An array with the results or null of the simulation did not converge in time.
     */
    public StableSteadyState stableSteadyStateSearcher(double[] startValues, double stabilityMaxDiff, double stabilityMinTime,
            SimulationMethod method, double dt, double maxt, CalculationController calculationController) {
        checkParameters(stabilityMaxDiff, stabilityMinTime, 1, method, dt, maxt);
        // Check whether startValues == null is included here
        for (double value : startValues) {
            MathLib.checkNotNaNAndWithinRange(value, 0, 1);
        }

        RegulatoryNetwork searchingNetwork = cloneClean();
        searchingNetwork.setValues(startValues);
        StableSteadyState stableSteadyState;

        stableSteadyState = new StableSteadyState(searchingNetwork, method, dt, maxt, stabilityMaxDiff, stabilityMinTime,
                calculationController);

        return stableSteadyState;
    }

    /**
     * Returns the sum of the number of all inputs to all network nodes.
     * 
     * @return Sum of all inputs
     */
    public int sumOfInputs() {
        int numberOfInputs = 0;
        for (NetworkNode node : networkNodes) {
            numberOfInputs += node.getInputs().length;
        }
        return numberOfInputs;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (double o : getValues()) {
            result.append(StandardNumberFormat.SHORTFIXEDNUMBERFORMAT.format(o) + " | ");
        }
        return result.toString();
    }

    /**
     * Returns the next input in a list of all inputs in the network.
     * 
     * @param node
     *            The node of the preceding input
     * @param input
     *            The position of the preceding input
     * 
     * @return The next input or null if the end if the list was reached.
     * */
    public NetworkInput getNextInput(int node, int input) {
        if (!isValidInput(node, input)) {
            throw new IllegalArgumentException("The specified input does not exist." + "(" + node + ", " + input + ")");
        }
        if ((input + 1) >= networkNodes[node].getInputs().length) {
            for (int i = node + 1; i < networkNodes.length; i++) {
                if (networkNodes[i].getInputs().length != 0) {
                    return new NetworkInput(i, 0);
                }
            }
            return null;
        } else {
            return new NetworkInput(node, input + 1);
        }
    }

    /**
     * Returns the next input in a list of all inputs in the network.
     * 
     * @param node
     *            The node of the preceding input
     * @param input
     *            The position of the preceding input
     * 
     * @return The next input or the first one if the end if the list was reached.
     * */
    public NetworkInput getNextInputWrap(int node, int input) {
        if (!isValidInput(node, input)) {
            throw new IllegalArgumentException("The specified input does not exist." + "(" + node + ", " + input + ")");
        }
        if ((input + 1) >= networkNodes[node].getInputs().length) {
            for (int i = node + 1; i < networkNodes.length; i++) {
                if (networkNodes[i].getInputs().length != 0) {
                    return new NetworkInput(i, 0);
                }
            }
            return getFirstInput();
        } else {
            return new NetworkInput(node, input + 1);
        }
    }

    /**
     * Returns the first element in a list of all inputs in the network.
     * 
     * @return The first input in the network or null if none exist.
     */
    public NetworkInput getFirstInput() {
        for (int i = 0; i < networkNodes.length; i++) {
            if (networkNodes[i].getInputs().length != 0) {
                return new NetworkInput(i, 0);
            }
        }
        return null;
    }

    /**
     * Returns the next input in a list of all inputs in the network.
     * 
     * @param input
     *            The preceding input
     * 
     * @return The next input or null if the end if the list was reached.
     * */
    public NetworkInput getNextInput(NetworkInput input) {
        return (getNextInput(input.getNode(), input.getInput()));
    }

    /**
     * Returns the next input in a list of all inputs in the network.
     * 
     * @param input
     *            The preceding input
     * 
     * @return The next input or the first one if the end if the list was reached.
     * */
    public NetworkInput getNextInputWrap(NetworkInput input) {
        return (getNextInputWrap(input.getNode(), input.getInput()));
    }

    /**
     * Returns a String representation of a given input.
     * 
     * @param input
     *            The input.
     * @param sep
     *            The seperator between the inputs.
     * @return Its string representation
     */
    public String getInputString(NetworkInput input, String sep) {
        return "\"" + networkNodes[networkNodes[input.getNode()].getInputs()[input.getInput()].getSource()].getName() + "\"" + sep + "\""
                + networkNodes[input.getNode()].getName() + "\"";
    }

    /**
     * Returns a String representation of a given input.
     * 
     * @param input
     *            The input.
     * @return Its string representation
     */
    public String getInputString(NetworkInput input) {
        return getInputString(input, "->");
    }

    /**
     * Returns a String representation of a list of given inputs.
     * 
     * @param inputs
     *            The inputs.
     * @return Their string representation
     */
    public String getInputString(ArrayList<NetworkInput> inputs) {
        String result = "{ ";
        for (int i = 0; i < inputs.size() - 1; i++) {
            result = result + getInputString(inputs.get(i)) + ", ";
        }
        if (inputs.size() != 0) {
            result = result + getInputString(inputs.get(inputs.size() - 1));
        }
        return result + " }";
    }

    /**
     * Checks whether the given input exists in the network.
     * 
     * @param input
     *            The input to check for.
     * @return True, if the input exists.
     */
    public boolean isValidInput(NetworkInput input) {
        return isValidInput(input.getNode(), input.getInput());
    }

    public boolean isLoop(NetworkInput input) {
        return input.getNode() == getInputSourceIndex(input);
    }

    /**
     * Checks whether the given input exists in the network.
     * 
     * @param node
     *            The node of the input to check for.
     * @param input
     *            The position of the input to check for.
     * @return True, if the input exists.
     */
    public boolean isValidInput(int node, int input) {
        if (node < 0 || node >= networkNodes.length || input < 0 || input >= networkNodes[node].getInputs().length) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Returns all inputs in the network.
     * 
     * @return All inputs of the network.
     */
    public ArrayList<NetworkInput> getInputs() {
        ArrayList<NetworkInput> result = new ArrayList<NetworkInput>();
        if (getFirstInput() == null) {
            return result;
        }
        NetworkInput nextInput = getFirstInput();
        while (nextInput != null) {
            result.add(nextInput);
            nextInput = getNextInput(nextInput);
        }
        return result;
    }

    /**
     * Returns the inputs from a given node in the network.
     * 
     * @param fromNode
     *            Inputs originating in this node are returned.
     * 
     * @return All inputs from the given node.
     */
    public ArrayList<NetworkInput> getInputsBySource(int fromNode) {
        if (fromNode < 0 || fromNode >= networkNodes.length) {
            throw new IllegalArgumentException("The specified network node " + fromNode + " was not found in the network.");
        }
        ArrayList<NetworkInput> result = new ArrayList<NetworkInput>();
        if (getFirstInput() == null) {
            return result;
        }
        NetworkInput nextInput = getFirstInput();
        while (nextInput != null) {
            if (networkNodes[nextInput.getNode()].getInputs()[nextInput.getInput()].getSource() != fromNode) {
                nextInput = getNextInput(nextInput);
                continue;
            }
            result.add(nextInput);
            nextInput = getNextInput(nextInput);
        }
        return result;
    }

    /**
     * Returns all inputs starting from a given node and leading to a given node.
     * 
     * @param fromNode
     *            The node the inputs start from.
     * @param toNode
     *            The node the inputs lead to.
     * @return All inputs between the two nodes.
     */
    public ArrayList<NetworkInput> getInputsBySourceAndTarget(int fromNode, int toNode) {
        ArrayList<NetworkInput> result = new ArrayList<NetworkInput>();

        ArrayList<NetworkInput> from = getInputsBySource(fromNode);
        ArrayList<NetworkInput> to = getInputsByTarget(toNode);

        for (NetworkInput input : from) {
            for (NetworkInput input2 : to) {
                if (input.getNode() == input2.getNode() && input.getInput() == input2.getInput()) {
                    result.add(input);
                    break;
                }
            }
        }
        return result;
    }

    /**
     * Returns the inputs to a given node in the network.
     * 
     * @param toNode
     *            Inputs targeting this node are returned.
     * @return All inputs to the given node.
     */
    public ArrayList<NetworkInput> getInputsByTarget(int toNode) {
        if (toNode < 0 || toNode >= networkNodes.length) {
            throw new IllegalArgumentException("The specified network node was not found in the network.");
        }
        ArrayList<NetworkInput> result = new ArrayList<NetworkInput>();

        for (int i = 0; i < networkNodes[toNode].getInputs().length; i++) {
            result.add(new NetworkInput(toNode, i));
        }

        return result;
    }

    /**
     * Removes all mutations from the network.
     */
    public void restore() {
        for (NetworkNode node : networkNodes) {
            node.getFunction().restore();
        }
    }

    /**
     * Prints the current values of the network nodes.
     */
    public void printNetworkState() {
        int padding = StringLib.maxStringLength(getNodeNames());

        for (NetworkNode node : networkNodes) {
            System.out.println(StringLib.padLeft(node.getName(), padding) + ": " + node.getValue());
        }
    }

    /**
     * Creates a string representation of the network ready to import in SQUAD. Throws an exception if network is not compatible with SQUAD.
     * 
     * @return A SQUAD compatible representation of the node's input.
     */
    public String exportSQUAD() {
        String result = new String();
        for (int i = 0; i < networkNodes.length; i++) {
            result = result + exportSQUAD(i);
        }
        return result;
    }

    /**
     * Creates a string representation of the inputs to the specified node ready to import in SQUAD. Throws an exception if the node is not
     * compatible with SQUAD.
     * 
     * @param node
     *            The node to export.
     * @return A SQUAD compatible representation of the node's input.
     */
    public String exportSQUAD(int node) {
        if (node < 0 || node >= networkNodes.length) {
            throw new IllegalArgumentException("The specified node does not exist.");
        }

        String result = new String();
        if (networkNodes[node].getFunction() instanceof ActivatorInhibitorFunction) {
            boolean[] activators = ((ActivatorInhibitorFunction) networkNodes[node].getFunction()).getActivators();
            for (int i = 0; i < networkNodes[node].getInputs().length; i++) {
                result = result + networkNodes[networkNodes[node].getInputs()[i].getSource()].getName() + (activators[i] ? " -> " : " -| ")
                        + networkNodes[node].getName() + "\n";
            }
        } else {
            throw new IllegalArgumentException("The specified node is not an activator-inhibitor-node.");
        }
        return result;
    }

    /**
     * Switches the sources of two inputs.
     * 
     * @param input1
     *            First input of the pair.
     * @param input2
     *            Second input of the pair.
     */
    public void switchInputs(NetworkInput input1, NetworkInput input2) {
        int temp = networkNodes[input1.getNode()].getInputs()[input1.getInput()].getSource();
        networkNodes[input1.getNode()].getInputs()[input1.getInput()].setSource(networkNodes[input2.getNode()].getInputs()[input2
                .getInput()].getSource());
        networkNodes[input2.getNode()].getInputs()[input2.getInput()].setSource(temp);
    }

    /**
     * Switches two random inputs in the network.
     */
    public void switchRandomInputs(boolean preserveLoops) {
        ArrayList<NetworkInput> inputs = getInputs();
        int numberOfLoops = numberOfLoops();
        while (true) {
            int rnd1 = (int) (Math.random() * (inputs.size() - 1));

            int rnd2 = (int) (Math.random() * (inputs.size() - 1));

            switchInputs(inputs.get(rnd1), inputs.get(rnd2));
            if (numberOfLoops == numberOfLoops() || !preserveLoops) {
                break;
            }
            switchInputs(inputs.get(rnd1), inputs.get(rnd2));
        }
    }

    /**
     * Switches two random inputs in the network for given number of times.
     * 
     * @param repetitions
     *            Number of switches
     */
    public void switchRandomInputs(int repetitions, boolean preserveLoops) {
        for (int i = 0; i < repetitions; i++) {
            switchRandomInputs(preserveLoops);
        }
    }

    public boolean hasLoop(int node) {
        return getInputsBySourceAndTarget(node, node).size() != 0;
    }

    /**
     * Returns the number of input loops in the network.
     * 
     * @return Number of loops.
     */
    public int numberOfLoops() {
        int counter = 0;
        for (int i = 0; i < networkNodes.length; i++) {
            for (int j = 0; j < networkNodes[i].getInputs().length; j++) {
                if (networkNodes[i].getInputs()[j].getSource() == i) {
                    counter++;
                }
            }
        }
        return counter;
    }

    /**
     * Returns the number of inputs with or without loops in the network.
     * 
     * @return Number of inputs.
     */
    public int numberOfInputNodes() {
        int counter = 0;

        for (int i = 0; i < nodeCount(); i++) {
            if (getInputsByTarget(i).size() == 0) {
                counter++;
            }
        }
        return counter;
    }

    /**
     * Constructs a set of all the node indices.
     * 
     * @return A set of all the node indices.
     */
    public TreeSet<Integer> setOfAllNodeIndices() {
        TreeSet<Integer> allIndices = new TreeSet<Integer>();
        for (int i = 0; i < nodeCount(); i++) {
            allIndices.add(i);
        }
        return allIndices;
    }

    /**
     * Returns the given network input if it exists.
     * 
     * @param input
     *            The input to return.
     * @return The requested network input.
     */
    public Input getInput(NetworkInput input) {
        return networkNodes[input.getNode()].getInputs()[input.getInput()];
    }
}
