graphwise 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
graphwise/dag.py ADDED
@@ -0,0 +1,160 @@
1
+ """Directed acyclic graphs: topological sorting and cycle detection.
2
+
3
+ A topological order lists the nodes so that every edge ``u -> v`` has ``u``
4
+ before ``v``. Such an order exists exactly when the graph has no directed
5
+ cycle. Build systems, package managers, spreadsheet recalculation, task
6
+ schedulers and data pipelines all depend on it.
7
+
8
+ Two classic algorithms:
9
+
10
+ * **Kahn (1962)**, BFS-based. Repeatedly remove a node with no incoming edges
11
+ ("peeling the onion"). It also returns the order level by level, which is
12
+ useful for running independent tasks in parallel.
13
+ * **Tarjan (1976)**, DFS-based. List nodes in reverse order of DFS finish
14
+ time. A back edge to a node still on the DFS stack means a cycle.
15
+
16
+ Both run in O(V + E) time.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+ from .exceptions import NotADAG
24
+ from .graph import DiGraph
25
+
26
+ __all__ = [
27
+ "topological_sort",
28
+ "topological_sort_kahn",
29
+ "topological_sort_dfs",
30
+ "topological_generations",
31
+ "is_dag",
32
+ "find_cycle",
33
+ ]
34
+
35
+
36
+ def _require_directed(graph: Any, name: str) -> None:
37
+ if not getattr(graph, "is_directed", False):
38
+ raise TypeError(f"{name} requires a DiGraph")
39
+
40
+
41
+ def topological_sort_kahn(graph: DiGraph[Any]) -> list[Any]:
42
+ """Topologically sort ``graph`` with Kahn's algorithm (BFS).
43
+
44
+ Ties go to the earliest-inserted node. Raises :class:`NotADAG` if the graph
45
+ has a cycle.
46
+
47
+ >>> from graphwise import DiGraph
48
+ >>> topological_sort_kahn(DiGraph([("shirt", "tie"), ("tie", "jacket"),
49
+ ... ("pants", "shoes"), ("pants", "jacket")]))
50
+ ['shirt', 'pants', 'tie', 'shoes', 'jacket']
51
+ """
52
+ return [n for gen in topological_generations(graph) for n in gen]
53
+
54
+
55
+ def topological_generations(graph: DiGraph[Any]) -> list[list[Any]]:
56
+ """Group the nodes into layers that can be processed in parallel.
57
+
58
+ Layer 0 holds the nodes with no prerequisites. Every node in layer ``k``
59
+ depends only on nodes in earlier layers. The number of layers is the
60
+ length of the longest path plus one: the critical path of a schedule.
61
+
62
+ >>> from graphwise import DiGraph
63
+ >>> topological_generations(DiGraph([(1, 3), (2, 3), (3, 4)]))
64
+ [[1, 2], [3], [4]]
65
+ """
66
+ _require_directed(graph, "topological sort")
67
+ in_degree = {v: len(preds) for v, preds in graph._pred.items()}
68
+ layer = [v for v, d in in_degree.items() if d == 0]
69
+ out = []
70
+ emitted = 0
71
+ while layer:
72
+ out.append(layer)
73
+ emitted += len(layer)
74
+ nxt = []
75
+ for u in layer:
76
+ for v in graph._adj[u]:
77
+ in_degree[v] -= 1
78
+ if in_degree[v] == 0:
79
+ nxt.append(v)
80
+ layer = nxt
81
+ if emitted != len(graph):
82
+ raise NotADAG("graph contains a cycle; no topological order exists")
83
+ return out
84
+
85
+
86
+ def topological_sort_dfs(graph: DiGraph[Any]) -> list[Any]:
87
+ """Topologically sort ``graph`` by reverse DFS post-order (Tarjan).
88
+
89
+ Uses three colours: white is unvisited, grey is on the current DFS path,
90
+ and black is finished. Reaching a grey node means a cycle. The DFS keeps
91
+ an explicit stack, so deep graphs cannot overflow the recursion limit.
92
+ Raises :class:`NotADAG` if the graph has a cycle.
93
+
94
+ >>> from graphwise import DiGraph
95
+ >>> topological_sort_dfs(DiGraph([(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]))
96
+ [4, 5, 0, 2, 3, 1]
97
+ """
98
+ order = _dfs_postorder_or_cycle(graph)
99
+ if isinstance(order, tuple):
100
+ raise NotADAG(f"graph contains a cycle: {list(order)}")
101
+ order.reverse()
102
+ return order
103
+
104
+
105
+ def _dfs_postorder_or_cycle(graph: DiGraph[Any]) -> list[Any] | tuple[Any, ...]:
106
+ """Return the DFS post-order as a list, or the first cycle found as a tuple."""
107
+ _require_directed(graph, "topological sort")
108
+ adj = graph._adj
109
+ GREY, BLACK = 1, 2
110
+ colour: dict[Any, int] = {}
111
+ post: list[Any] = []
112
+ for root in adj:
113
+ if root in colour:
114
+ continue
115
+ colour[root] = GREY
116
+ path = [root]
117
+ stack = [iter(adj[root])]
118
+ while stack:
119
+ for v in stack[-1]:
120
+ c = colour.get(v)
121
+ if c is None:
122
+ colour[v] = GREY
123
+ path.append(v)
124
+ stack.append(iter(adj[v]))
125
+ break
126
+ if c == GREY: # back edge: a cycle
127
+ return (*tuple(path[path.index(v) :]), v)
128
+ else:
129
+ u = path.pop()
130
+ stack.pop()
131
+ colour[u] = BLACK
132
+ post.append(u)
133
+ return post
134
+
135
+
136
+ def topological_sort(graph: DiGraph[Any], method: str = "kahn") -> list[Any]:
137
+ """Topologically sort ``graph`` using ``method``, either ``"kahn"`` or ``"dfs"``."""
138
+ if method == "kahn":
139
+ return topological_sort_kahn(graph)
140
+ if method == "dfs":
141
+ return topological_sort_dfs(graph)
142
+ raise ValueError(f"unknown method {method!r}; use 'kahn' or 'dfs'")
143
+
144
+
145
+ def is_dag(graph: DiGraph[Any]) -> bool:
146
+ """Return True if ``graph`` is directed and has no cycle."""
147
+ if not getattr(graph, "is_directed", False):
148
+ return False
149
+ return not isinstance(_dfs_postorder_or_cycle(graph), tuple)
150
+
151
+
152
+ def find_cycle(graph: DiGraph[Any]) -> list[Any] | None:
153
+ """Return one directed cycle as ``[v0, v1, ..., v0]``, or None if acyclic.
154
+
155
+ >>> from graphwise import DiGraph
156
+ >>> find_cycle(DiGraph([("a", "b"), ("b", "c"), ("c", "a")]))
157
+ ['a', 'b', 'c', 'a']
158
+ """
159
+ result = _dfs_postorder_or_cycle(graph)
160
+ return list(result) if isinstance(result, tuple) else None
graphwise/eulerian.py ADDED
@@ -0,0 +1,170 @@
1
+ """Eulerian circuits and paths with Hierholzer's algorithm.
2
+
3
+ An *Eulerian circuit* uses every edge exactly once and ends where it started.
4
+ An *Eulerian path* uses every edge exactly once but may end somewhere else.
5
+ Euler settled when they exist in 1736, with the Königsberg bridges problem,
6
+ which is often called the founding result of graph theory:
7
+
8
+ * **Undirected**: a circuit exists if every node has even degree, and a path
9
+ if exactly 0 or 2 nodes have odd degree. In both cases every edge must be in
10
+ one connected component.
11
+ * **Directed**: a circuit exists if every node has in-degree equal to
12
+ out-degree, and a path if one node has ``out - in = 1`` (the start) and one
13
+ has ``in - out = 1`` (the end). The edges must be connected when direction is
14
+ ignored.
15
+
16
+ Hierholzer's algorithm (1873) builds one in O(E) time. Walk unused edges
17
+ until you get stuck. Backtrack, splicing in sub-tours from any node on the
18
+ way that still has unused edges. The nodes, in the order they are popped,
19
+ form the circuit in reverse.
20
+
21
+ Uses: route inspection (snow ploughs, mail delivery), DNA fragment assembly
22
+ on de Bruijn graphs, and drawing a figure without lifting the pen.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Hashable
28
+ from typing import Any
29
+
30
+ from .exceptions import NotEulerian
31
+ from .graph import _BaseGraph, _undirected_adj
32
+
33
+ __all__ = ["eulerian_circuit", "eulerian_path", "has_eulerian_circuit", "has_eulerian_path"]
34
+
35
+
36
+ def _degree_imbalance(graph: _BaseGraph[Any]) -> dict[Any, int]:
37
+ """Directed: ``out - in``. Undirected: degree mod 2 (1 means odd)."""
38
+ if graph.is_directed:
39
+ return {v: len(graph._adj[v]) - len(graph._pred[v]) for v in graph._adj} # type: ignore[attr-defined]
40
+ return {v: graph.degree(v) % 2 for v in graph._adj} # type: ignore[attr-defined]
41
+
42
+
43
+ def _edges_connected(graph: _BaseGraph[Any]) -> bool:
44
+ """True if every node that has an edge is in one (weakly) connected piece."""
45
+ adj = _undirected_adj(graph)
46
+ with_edges = [v for v, nbrs in adj.items() if nbrs]
47
+ if not with_edges:
48
+ return True
49
+ seen = {with_edges[0]}
50
+ stack = [with_edges[0]]
51
+ while stack:
52
+ for v in adj[stack.pop()]:
53
+ if v not in seen:
54
+ seen.add(v)
55
+ stack.append(v)
56
+ return all(v in seen for v in with_edges)
57
+
58
+
59
+ def has_eulerian_circuit(graph: _BaseGraph[Any]) -> bool:
60
+ """Return True if ``graph`` has an Eulerian circuit."""
61
+ return _edges_connected(graph) and not any(_degree_imbalance(graph).values())
62
+
63
+
64
+ def _path_endpoints(graph: _BaseGraph[Any]) -> tuple[Any, Any] | None:
65
+ """Return the required ``(start, end)`` of an Eulerian path.
66
+
67
+ Returns ``(None, None)`` when any start works (a circuit exists), and None
68
+ when no Eulerian path exists.
69
+ """
70
+ if not _edges_connected(graph):
71
+ return None
72
+ imbalance = _degree_imbalance(graph)
73
+ if graph.is_directed:
74
+ starts = [v for v, d in imbalance.items() if d == 1]
75
+ ends = [v for v, d in imbalance.items() if d == -1]
76
+ if any(abs(d) > 1 for d in imbalance.values()):
77
+ return None
78
+ if not starts and not ends:
79
+ return (None, None)
80
+ if len(starts) == 1 and len(ends) == 1:
81
+ return (starts[0], ends[0])
82
+ return None
83
+ odd = [v for v, d in imbalance.items() if d]
84
+ if not odd:
85
+ return (None, None)
86
+ if len(odd) == 2:
87
+ return (odd[0], odd[1])
88
+ return None
89
+
90
+
91
+ def has_eulerian_path(graph: _BaseGraph[Any]) -> bool:
92
+ """Return True if ``graph`` has an Eulerian path (a circuit counts as one)."""
93
+ return _path_endpoints(graph) is not None
94
+
95
+
96
+ def _hierholzer(graph: _BaseGraph[Any], start: Any) -> list[Any]:
97
+ # Work on a copy of the adjacency, so the caller's graph is never changed.
98
+ remaining = {u: list(nbrs) for u, nbrs in graph._adj.items()}
99
+ directed = graph.is_directed
100
+ stack = [start]
101
+ circuit = []
102
+ while stack:
103
+ u = stack[-1]
104
+ if remaining[u]:
105
+ v = remaining[u].pop()
106
+ if not directed and v != u:
107
+ remaining[v].remove(u) # undirected: use up the edge from both ends
108
+ stack.append(v)
109
+ else:
110
+ circuit.append(stack.pop())
111
+ circuit.reverse()
112
+ return circuit
113
+
114
+
115
+ def _first_node_with_edges(graph: _BaseGraph[Any]) -> Any:
116
+ for v, nbrs in graph._adj.items():
117
+ if nbrs:
118
+ return v
119
+ return next(iter(graph._adj))
120
+
121
+
122
+ def eulerian_circuit(graph: _BaseGraph[Any], source: Hashable | None = None) -> list[Any]:
123
+ """Return an Eulerian circuit as a list of nodes, ``[source, ..., source]``.
124
+
125
+ The list has ``E + 1`` entries, and consecutive pairs are the edges in the
126
+ order they are walked. Raises :class:`NotEulerian` if no circuit exists.
127
+
128
+ >>> from graphwise import DiGraph
129
+ >>> eulerian_circuit(DiGraph([(0, 1), (1, 2), (2, 0)]), source=0)
130
+ [0, 1, 2, 0]
131
+ """
132
+ if len(graph) == 0:
133
+ raise NotEulerian("the empty graph has no Eulerian circuit")
134
+ if not has_eulerian_circuit(graph):
135
+ raise NotEulerian("graph has no Eulerian circuit")
136
+ if source is None:
137
+ source = _first_node_with_edges(graph)
138
+ else:
139
+ graph._check_node(source)
140
+ if graph.number_of_edges() and not graph._adj[source]:
141
+ raise NotEulerian(f"source {source!r} has no edges")
142
+ return _hierholzer(graph, source)
143
+
144
+
145
+ def eulerian_path(graph: _BaseGraph[Any], source: Hashable | None = None) -> list[Any]:
146
+ """Return an Eulerian path as a list of nodes (``E + 1`` entries).
147
+
148
+ If the graph has an Eulerian circuit, that circuit is returned (starting at
149
+ ``source`` if given). Otherwise the path must start at the one node whose
150
+ degree allows it. Raises :class:`NotEulerian` if no path exists, or if
151
+ ``source`` cannot be a start.
152
+
153
+ >>> from graphwise import Graph
154
+ >>> eulerian_path(Graph([("a", "b"), ("b", "c")]))
155
+ ['a', 'b', 'c']
156
+ """
157
+ if len(graph) == 0:
158
+ raise NotEulerian("the empty graph has no Eulerian path")
159
+ ends = _path_endpoints(graph)
160
+ if ends is None:
161
+ raise NotEulerian("graph has no Eulerian path")
162
+ start, end = ends
163
+ if start is None:
164
+ return eulerian_circuit(graph, source)
165
+ if source is not None:
166
+ if source == end and not graph.is_directed:
167
+ start = end # undirected paths can run in either direction
168
+ elif source != start:
169
+ raise NotEulerian(f"an Eulerian path cannot start at {source!r}")
170
+ return _hierholzer(graph, start)
@@ -0,0 +1,47 @@
1
+ """Exceptions raised by graphwise."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "GraphError",
7
+ "NodeNotFound",
8
+ "EdgeNotFound",
9
+ "NoPath",
10
+ "NotADAG",
11
+ "NegativeCycle",
12
+ "NotEulerian",
13
+ ]
14
+
15
+
16
+ class GraphError(Exception):
17
+ """Base class for every error raised by graphwise."""
18
+
19
+
20
+ class NodeNotFound(GraphError, KeyError):
21
+ """A node passed to a method or algorithm is not in the graph."""
22
+
23
+ def __str__(self) -> str: # KeyError would otherwise repr() the message
24
+ return str(self.args[0]) if self.args else ""
25
+
26
+
27
+ class EdgeNotFound(GraphError, KeyError):
28
+ """An edge passed to a method or algorithm is not in the graph."""
29
+
30
+ def __str__(self) -> str:
31
+ return str(self.args[0]) if self.args else ""
32
+
33
+
34
+ class NoPath(GraphError):
35
+ """No path exists between the requested nodes."""
36
+
37
+
38
+ class NotADAG(GraphError):
39
+ """The algorithm needs a directed acyclic graph, but the graph has a cycle."""
40
+
41
+
42
+ class NegativeCycle(GraphError):
43
+ """A negative-weight cycle makes shortest paths undefined."""
44
+
45
+
46
+ class NotEulerian(GraphError):
47
+ """The graph has no Eulerian circuit (or path) as requested."""
graphwise/flow.py ADDED
@@ -0,0 +1,155 @@
1
+ """Maximum flow and minimum cut with Dinic's algorithm.
2
+
3
+ Treat each edge weight as a *capacity*. The maximum flow is the most that can
4
+ be pushed from ``source`` to ``sink`` per unit time. The max-flow/min-cut
5
+ theorem says this equals the minimum total capacity of edges whose removal
6
+ separates the sink from the source. So one computation answers both "how much
7
+ can get through?" and "where is the bottleneck?".
8
+
9
+ Dinic's algorithm (1970) improves on Ford-Fulkerson in two ways:
10
+
11
+ 1. **Level graph.** A BFS on the *residual graph* labels every node with its
12
+ distance from the source. Only edges that go one level deeper are kept, so
13
+ every augmenting path found is a shortest one.
14
+ 2. **Blocking flow.** DFS pushes flow along level-graph paths until none is
15
+ left. A per-node edge pointer makes sure no dead edge is tried twice. Then
16
+ the level graph is rebuilt.
17
+
18
+ Shortest augmenting-path length strictly increases each phase, which bounds
19
+ the time at O(V² E) in general and O(E √V) on unit-capacity graphs, as in
20
+ bipartite matching.
21
+
22
+ Uses: bipartite matching and assignment, image segmentation (graph cuts),
23
+ project selection, network reliability, supply-chain and transport capacity,
24
+ and finding the cheapest set of links that would disconnect a network.
25
+
26
+ This version uses an explicit stack, so it does not depend on Python's
27
+ recursion limit. Nodes can be any hashable value.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import itertools
33
+ from collections import defaultdict, deque
34
+ from collections.abc import Hashable
35
+ from typing import Any
36
+
37
+ from .graph import _BaseGraph
38
+
39
+ __all__ = ["max_flow", "minimum_cut"]
40
+
41
+ Residual = dict[Any, dict[Any, float]]
42
+
43
+
44
+ def _dinic(graph: _BaseGraph[Any], source: Any, sink: Any) -> tuple[float, Residual]:
45
+ graph._check_node(source)
46
+ graph._check_node(sink)
47
+ if source == sink:
48
+ raise ValueError("source and sink must be different nodes")
49
+
50
+ # Residual capacities. Every edge also gets a reverse edge (capacity 0 at
51
+ # first, plus its own capacity if the graph already has that edge).
52
+ cap: Residual = defaultdict(dict)
53
+ for u, nbrs in graph._adj.items():
54
+ cap[u] # touch, so nodes without edges are present
55
+ for v, c in nbrs.items():
56
+ if c < 0:
57
+ raise ValueError(f"capacity of edge ({u!r}, {v!r}) is negative")
58
+ if u == v:
59
+ continue
60
+ cap[u][v] = cap[u].get(v, 0) + c
61
+ cap[v].setdefault(u, 0)
62
+ order = {u: list(nbrs) for u, nbrs in cap.items()} # fixed neighbour order
63
+
64
+ total: float = 0
65
+ while True:
66
+ # Phase 1: BFS on the residual graph to build the level graph.
67
+ level = {source: 0}
68
+ q = deque([source])
69
+ while q:
70
+ u = q.popleft()
71
+ for v in order[u]:
72
+ if v not in level and cap[u][v] > 0:
73
+ level[v] = level[u] + 1
74
+ q.append(v)
75
+ if sink not in level:
76
+ return total, cap
77
+
78
+ # Phase 2: push augmenting paths until the flow is blocking.
79
+ ptr = dict.fromkeys(order, 0)
80
+ while True:
81
+ path = [source]
82
+ while path and path[-1] != sink:
83
+ u = path[-1]
84
+ out = order[u]
85
+ while ptr[u] < len(out):
86
+ v = out[ptr[u]]
87
+ if cap[u][v] > 0 and level.get(v) == level[u] + 1:
88
+ path.append(v)
89
+ break
90
+ ptr[u] += 1
91
+ else: # dead end: back up and skip the edge that led here
92
+ path.pop()
93
+ if path:
94
+ ptr[path[-1]] += 1
95
+ if not path:
96
+ break # blocking flow reached
97
+ bottleneck = min(cap[a][b] for a, b in itertools.pairwise(path))
98
+ for a, b in itertools.pairwise(path):
99
+ cap[a][b] -= bottleneck
100
+ cap[b][a] += bottleneck
101
+ total += bottleneck
102
+
103
+
104
+ def max_flow(
105
+ graph: _BaseGraph[Any], source: Hashable, sink: Hashable
106
+ ) -> tuple[float, dict[Any, dict[Any, float]]]:
107
+ """Return ``(flow_value, flow)`` for the maximum ``source -> sink`` flow.
108
+
109
+ ``flow[u][v]`` is the flow on edge ``(u, v)``, given for every edge in the
110
+ graph. Edge weights are the capacities. In an undirected :class:`Graph`,
111
+ each edge can carry its capacity in either direction.
112
+
113
+ >>> from graphwise import DiGraph
114
+ >>> g = DiGraph([("s", "a", 10), ("s", "b", 5), ("a", "b", 15),
115
+ ... ("a", "t", 5), ("b", "t", 10)])
116
+ >>> max_flow(g, "s", "t")[0]
117
+ 15
118
+
119
+ References: Dinitz, Y. (1970). Algorithm for solution of a problem of
120
+ maximum flow in a network with power estimation. *Soviet Math. Doklady* 11.
121
+ """
122
+ value, cap = _dinic(graph, source, sink)
123
+ flow: dict[Any, dict[Any, float]] = {}
124
+ for u, nbrs in graph._adj.items():
125
+ flow[u] = {}
126
+ for v, c in nbrs.items():
127
+ flow[u][v] = 0 if u == v else max(0, c - cap[u][v])
128
+ return value, flow
129
+
130
+
131
+ def minimum_cut(
132
+ graph: _BaseGraph[Any], source: Hashable, sink: Hashable
133
+ ) -> tuple[float, tuple[set[Any], set[Any]]]:
134
+ """Return ``(cut_value, (S, T))``, a minimum ``source``/``sink`` cut.
135
+
136
+ ``S`` is the set of nodes still reachable from ``source`` in the residual
137
+ graph once the flow is maximal, and ``T`` is the rest. The edges from
138
+ ``S`` to ``T`` are saturated, and their total capacity equals the max flow.
139
+
140
+ >>> from graphwise import DiGraph
141
+ >>> g = DiGraph([("s", "a", 3), ("a", "t", 1), ("s", "t", 2)])
142
+ >>> value, (S, T) = minimum_cut(g, "s", "t")
143
+ >>> value, sorted(S), sorted(T)
144
+ (3, ['a', 's'], ['t'])
145
+ """
146
+ value, cap = _dinic(graph, source, sink)
147
+ reach = {source}
148
+ stack = [source]
149
+ while stack:
150
+ u = stack.pop()
151
+ for v, c in cap[u].items():
152
+ if c > 0 and v not in reach:
153
+ reach.add(v)
154
+ stack.append(v)
155
+ return value, (reach, set(graph) - reach)