private void checkIsDAGAndCollectVariablesInTopologicalOrder()
{
// Topological sort based on logic described at:
// http://en.wikipedia.org/wiki/Topoligical_sorting
Set<Node> seenAlready = new Set<Node>();
Map<Node, List<Node>> incomingEdges = new Map<Node, List<Node>>();
Set<Node> s = new Set<Node>();
foreach (Node n in this.rootNodes)
{
walkNode(n, seenAlready, incomingEdges, s);
}
while (!(s.Count == 0))
{
HashSet<Node>.Enumerator enumerator = s.GetEnumerator();
enumerator.MoveNext();
Node n = enumerator.Current;
s.remove(n);
variables.Add(n.getRandomVariable());
varToNodeMap.put(n.getRandomVariable(), n);
foreach (Node m in n.getChildren())
{
List<Node> edges = incomingEdges.get(m);
edges.Remove(n);
if (edges.Count == 0)
{
s.add(m);
}
}
}
foreach (List<Node> edges in incomingEdges.values())
{
if (!(edges.Count == 0))
{
throw new IllegalArgumentException(
"Network contains at least one cycle in it, must be a DAG.");
}
}
}