Index: branches/HeuristicLab.VariableInteractionNetworks/HeuristicLab.VariableInteractionNetworks/3.3/VariableInteractionNetwork.cs
===================================================================
--- branches/HeuristicLab.VariableInteractionNetworks/HeuristicLab.VariableInteractionNetworks/3.3/VariableInteractionNetwork.cs	(revision 14283)
+++ branches/HeuristicLab.VariableInteractionNetworks/HeuristicLab.VariableInteractionNetworks/3.3/VariableInteractionNetwork.cs	(revision 14622)
@@ -21,6 +21,11 @@
 
 using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
 using HeuristicLab.Common;
 using HeuristicLab.Core;
+using HeuristicLab.Data;
 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
 
@@ -29,4 +34,82 @@
   [StorableClass]
   public class VariableInteractionNetwork : DirectedGraph {
+    /// <summary>
+    /// Creates a network from a matrix of variable impacts (each row represents a target variable, each column represents an input variable)
+    /// The network is acyclic. Values in the diagonal are ignored.
+    /// The algorithm starts with an empty network and incrementally adds next most relevant input variable for each target variable up to a given threshold
+    /// In each iteration cycles are broken by removing the weakest link.
+    /// </summary>
+    /// <param name="nmse">vector of NMSE values for each target variable</param>
+    /// <param name="variableImpacts">Variable impacts (smaller is lower impact). Row names and columns names should be set</param>
+    /// <param name="nmseThreshold">Threshold for NMSE values. Variables with a NMSE value larger than the threshold are considered as independent variables</param>
+    /// <param name="varImpactThreshold">Threshold for variable impact values. Impacts with a value smaller than the threshold are considered as independent</param>
+    /// <returns></returns>
+    public static VariableInteractionNetwork FromNmseAndVariableImpacts(double[] nmse, DoubleMatrix variableImpacts, double nmseThreshold = 0.2, double varImpactThreshold = 0.0) {
+      if(variableImpacts.Rows != variableImpacts.Columns) throw new ArgumentException();
+      var network = new VariableInteractionNetwork();
+
+      Dictionary<string, IVertex> name2funVertex = new Dictionary<string, IVertex>(); // store vertexes representing the function for each target so we can easily add incoming arcs later on
+      string[] varNames = variableImpacts.RowNames.ToArray();
+      if(nmse.Length != varNames.Length) throw new ArgumentException();
+
+      for(int i = 0; i < varNames.Length; i++) {
+        var name = varNames[i];
+        var varVertex = new VariableNetworkNode() { Label = name };
+        network.AddVertex(varVertex);
+        if(nmse[i] < nmseThreshold) {
+          var functionVertex = new JunctionNetworkNode() { Label = "f_" + name };
+          name2funVertex.Add(name, functionVertex);
+          network.AddVertex(functionVertex);
+          var predArc = network.AddArc(functionVertex, varVertex);
+          predArc.Weight = double.PositiveInfinity; // never delete arcs from f_x -> x (representing output of a function)
+        }
+      }
+
+      // rel is updated (impacts which are represented in the network are set to zero)
+      var rel = variableImpacts.CloneAsMatrix();
+      // make sure the diagonal is not considered
+      for(int i = 0; i < rel.GetLength(0); i++) rel[i, i] = double.NegativeInfinity;
+
+      var addedArcs = AddArcs(network, rel, varNames, name2funVertex, varImpactThreshold);
+      while(addedArcs.Any()) {
+        var cycles = network.FindShortestCycles().ToList();
+        while(cycles.Any()) {
+          // delete weakest link
+          var weakestArc = cycles.SelectMany(cycle => network.ArcsForCycle(cycle)).OrderBy(a => a.Weight).First();
+          network.RemoveArc(weakestArc);
+
+          cycles = network.FindShortestCycles().ToList();
+        }
+
+        addedArcs = AddArcs(network, rel, varNames, name2funVertex, varImpactThreshold);
+      }
+
+      return network;
+    }
+
+    private static List<IArc> AddArcs(VariableInteractionNetwork network, double[,] impacts, string[] varNames, Dictionary<string, IVertex> name2funVertex, double threshold = 0.0) {
+      var newArcs = new List<IArc>();
+      for(int row = 0; row < impacts.GetLength(0); row++) {
+        if(!name2funVertex.ContainsKey(varNames[row])) continue; // this variable does not have an associated function (considered as independent)
+
+        var rowVector = Enumerable.Range(0, impacts.GetLength(0)).Select(col => impacts[row, col]).ToArray();
+        var max = rowVector.Max();
+        if(max > threshold) {
+          var idxOfMax = Array.IndexOf<double>(rowVector, max);
+          impacts[row, idxOfMax] = double.NegativeInfinity; // edge is not considered anymore
+          var srcName = varNames[idxOfMax];
+          var dstName = varNames[row];
+          var vertex = network.Vertices.Single(v => v.Label == srcName);
+          var arc = network.AddArc(vertex, name2funVertex[dstName]);
+          arc.Weight = max;
+          newArcs.Add(arc);
+        }
+      }
+      return newArcs;
+    }
+
+    [StorableConstructor]
+    public VariableInteractionNetwork(bool deserializing) : base(deserializing) { }
+
     public VariableInteractionNetwork() { }
 
@@ -35,4 +118,99 @@
     public override IDeepCloneable Clone(Cloner cloner) {
       return new VariableInteractionNetwork(this, cloner);
+    }
+    private IList<IArc> ArcsForCycle(IList<IVertex> cycle) {
+      var res = new List<IArc>();
+      foreach(var t in cycle.Zip(cycle.Skip(1), Tuple.Create)) {
+        var src = t.Item1;
+        var dst = t.Item2;
+        var arc = Arcs.Single(a => a.Source == src && a.Target == dst);
+        res.Add(arc);
+      }
+      return res;
+    }
+
+
+    // finds the shortest cycles in the graph and returns all sub-graphs containing only the nodes / edges within the cycle
+    public IEnumerable<IList<IVertex>> FindShortestCycles() {
+      foreach(var startVariable in base.Vertices.OfType<VariableNetworkNode>()) {
+        foreach(var cycle in FindShortestCycles(startVariable))
+          yield return cycle;
+      }
+    }
+
+    private IEnumerable<IList<IVertex>> FindShortestCycles(VariableNetworkNode startVariable) {
+      var q = new Queue<List<IVertex>>(); // queue of paths
+      var path = new List<IVertex>();
+      var cycles = new List<List<IVertex>>();
+      var maxPathLength = base.Vertices.Count();
+
+      path.Add(startVariable);
+      q.Enqueue(new List<IVertex>(path));
+
+      FindShortestCycles(q, maxPathLength, cycles);
+      return cycles;
+    }
+
+    // TODO efficiency
+    private void FindShortestCycles(Queue<List<IVertex>> queue, int maxPathLength, List<List<IVertex>> cycles) {
+      while(queue.Any()) {
+        var path = queue.Dequeue();
+        if(path.Count > 1 && path.First() == path.Last()) {
+          cycles.Add(new List<IVertex>(path)); // found a cycle
+        } else if(path.Count >= maxPathLength) {
+          continue;
+        } else {
+          var lastVert = path.Last();
+          var neighbours = base.Arcs.Where(a => a.Source == lastVert).Select(a => a.Target);
+          foreach(var neighbour in neighbours) {
+            queue.Enqueue(new List<IVertex>(path.Concat(new IVertex[] { neighbour })));
+          }
+        }
+      }
+    }
+
+    public DoubleMatrix GetWeightsMatrix() {
+      var names = Vertices.OfType<VariableNetworkNode>()
+        .Select(v => v.Label)
+        .OrderBy(s => s, new NaturalStringComparer()).ToArray();
+      var w = new double[names.Length, names.Length];
+
+      var name2idx = new Dictionary<string, int>();
+      for(int i = 0; i < names.Length; i++) {
+        name2idx.Add(names[i], i);
+      }
+
+      foreach(var arc in Arcs) {
+        // only consider arcs going into a junction node
+        var target = arc.Target as JunctionNetworkNode;
+        if(target != null)
+        {
+          var srcVarName = arc.Source.Label;
+          // each function node must have exactly one outgoing arc
+          var dstVarName = arc.Target.OutArcs.Single().Target.Label;
+
+          w[name2idx[dstVarName], name2idx[srcVarName]] = arc.Weight;
+        }
+      }
+
+
+      return new DoubleMatrix(w, names, names);
+    }
+
+    public string ToGraphVizString() {
+      var sb = new StringBuilder();
+      sb.AppendLine("digraph {");
+      sb.AppendLine("rankdir=LR");
+      foreach(var v in Vertices.OfType<VariableNetworkNode>()) {
+        sb.AppendFormat("\"{0}\" [shape=oval]", v.Label).AppendLine();
+      }
+      foreach(var v in Vertices.OfType<JunctionNetworkNode>()) {
+        sb.AppendFormat("\"{0}\" [shape=box]", v.Label).AppendLine();
+      }
+      foreach(var arc in Arcs) {
+        sb.AppendFormat("\"{0}\"->\"{1}\"", arc.Source.Label, arc.Target.Label).AppendLine();
+      }
+      sb.AppendLine("}");
+      return sb.ToString();
     }
   }
