import 'dart:collection'; import 'dart:math' as math; import '../domain/graph_definition.dart'; /// Deterministic 0-based ranks for a graph definition's nodes. /// /// Ranks come from the condensation DAG: every strongly connected component /// shares one rank, and a component sits one past its deepest predecessor /// (longest path). Self loops and cycles therefore stay finite, a cycle's /// members do not drift apart, and disconnected nodes stay at rank 0. Edges /// whose endpoints are not definition nodes are ignored: an unknown target /// never invents a node. class GraphRanks { GraphRanks({ required Map rankOf, required this.rankCount, required List> components, }) : rankOf = Map.unmodifiable(rankOf), components = List.unmodifiable(>[ for (final component in components) List.unmodifiable(component), ]); /// Every definition key's rank, in definition order. final Map rankOf; /// Number of distinct ranks, 0 for an empty node set. final int rankCount; /// Strongly connected components as keys, each sorted by definition order and /// the list sorted by its first member. final List> components; } /// One DFS frame for the iterative Tarjan walk. class _Frame { _Frame(this.node); final int node; int nextChild = 0; } /// Assigns ranks to exactly the supplied [nodes]. /// /// [edges] is read for ordering only; it never adds nodes. Duplicate edges are /// harmless. The walk is iterative, so a deep chain cannot overflow the call /// stack, and the work is linear in nodes plus edges. GraphRanks assignGraphRanks(List nodes, List edges) { final indexOf = {}; for (var index = 0; index < nodes.length; index += 1) { indexOf[nodes[index].key] = index; } final adjacency = List>.generate(nodes.length, (_) => []); final seenPairs = {}; for (final edge in edges) { final source = indexOf[edge.source]; final target = indexOf[edge.target]; if (source == null || target == null) continue; if (!seenPairs.add(source * nodes.length + target)) continue; adjacency[source].add(target); } final components = _components(adjacency); final componentOf = List.filled(nodes.length, -1); for (var component = 0; component < components.length; component += 1) { for (final node in components[component]) { componentOf[node] = component; } } // Condensation edges and their indegrees. final successors = List>.generate(components.length, (_) => {}); final indegree = List.filled(components.length, 0); for (var source = 0; source < adjacency.length; source += 1) { final from = componentOf[source]; for (final target in adjacency[source]) { final to = componentOf[target]; if (from == to) continue; if (successors[from].add(to)) indegree[to] += 1; } } // Longest-path ranks over the condensation. Queue order only has to be a // topological order; the resulting rank per component is unique. final ranks = List.filled(components.length, 0); final ready = ListQueue(); for (var component = 0; component < components.length; component += 1) { if (indegree[component] == 0) ready.add(component); } var settled = 0; while (ready.isNotEmpty) { final component = ready.removeFirst(); settled += 1; for (final next in successors[component]) { ranks[next] = math.max(ranks[next], ranks[component] + 1); indegree[next] -= 1; if (indegree[next] == 0) ready.add(next); } } if (settled != components.length) { // The condensation cannot contain a cycle by construction; stop rather than // return a silently truncated layout. throw StateError('graph condensation was not acyclic'); } final componentKeys = >[ for (final component in components) [for (final node in component) nodes[node].key], ]; final componentOrder = [ for (var component = 0; component < components.length; component += 1) component, ]..sort((a, b) => components[a].first.compareTo(components[b].first)); final rankOf = {}; var rankCount = 0; for (var index = 0; index < nodes.length; index += 1) { final rank = ranks[componentOf[index]]; rankOf[nodes[index].key] = rank; if (rank + 1 > rankCount) rankCount = rank + 1; } return GraphRanks( rankOf: rankOf, rankCount: rankCount, components: >[ for (final component in componentOrder) componentKeys[component], ], ); } /// Tarjan's strongly connected components, emitted sinks first. /// /// Iterative rather than recursive so a long chain cannot exhaust the stack. /// Members are sorted by definition index, which keeps every output stable. List> _components(List> adjacency) { final discovery = List.filled(adjacency.length, -1); final low = List.filled(adjacency.length, 0); final onStack = List.filled(adjacency.length, false); final stack = []; final components = >[]; var nextDiscovery = 0; for (var root = 0; root < adjacency.length; root += 1) { if (discovery[root] != -1) continue; discovery[root] = low[root] = nextDiscovery; nextDiscovery += 1; stack.add(root); onStack[root] = true; final callStack = <_Frame>[_Frame(root)]; while (callStack.isNotEmpty) { final frame = callStack.last; final node = frame.node; if (frame.nextChild < adjacency[node].length) { final child = adjacency[node][frame.nextChild]; frame.nextChild += 1; if (discovery[child] == -1) { discovery[child] = low[child] = nextDiscovery; nextDiscovery += 1; stack.add(child); onStack[child] = true; callStack.add(_Frame(child)); } else if (onStack[child]) { low[node] = math.min(low[node], discovery[child]); } continue; } callStack.removeLast(); if (callStack.isNotEmpty) { final parent = callStack.last.node; low[parent] = math.min(low[parent], low[node]); } if (low[node] == discovery[node]) { final component = []; while (stack.isNotEmpty) { final member = stack.removeLast(); onStack[member] = false; component.add(member); if (member == node) break; } component.sort(); components.add(component); } } } return components; }