​fly-in /
src / flow / flow_network.py
63 commits
09-08-2026
302 lines 9.8 kB
  1"""A hand-written maximum-flow solver over integer capacities.
  2
  3The class here knows nothing about zones, drones or turns: it moves
  4units through numbered nodes. Everything specific to the simulation is
  5built on top of it by src.flow.time_expanded.
  6"""
  7
  8from collections import deque
  9
 10
 11class FlowNetwork:
 12    """A directed graph of capacitated arcs, solved with Dinic.
 13
 14    Arcs are kept in one flat list. Adding an arc appends two entries,
 15    the arc itself and a reverse arc of capacity zero, so the reverse
 16    of arc e is always e ^ 1. Pushing units forward subtracts
 17    from one and adds to the other, which is what lets the algorithm
 18    take back an earlier decision instead of committing to it.
 19
 20    The solver is incremental. Nodes and arcs may be added between
 21    calls to max_flow, and the next call resumes from the
 22    residual capacities the previous one left behind. Adding arcs only
 23    ever grants capacity, so flow already pushed stays valid and the
 24    new call merely looks for the paths that opened up.
 25    """
 26
 27    def __init__(self, size: int = 0) -> None:
 28        """Create a network of isolated nodes.
 29
 30        Args:
 31            size: How many nodes to start with, numbered from zero.
 32
 33        Raises:
 34            ValueError: If the size is negative.
 35        """
 36        if size < 0:
 37            raise ValueError(f"a network cannot hold {size} nodes")
 38        self._to: list[int] = []
 39        self._cap: list[int] = []
 40        self._head: list[list[int]] = [[] for _ in range(size)]
 41        self._level: list[int] = []
 42        self._next: list[int] = []
 43
 44    @property
 45    def size(self) -> int:
 46        """How many nodes the network holds.
 47
 48        Returns:
 49            The node count.
 50        """
 51        return len(self._head)
 52
 53    @property
 54    def arcs(self) -> int:
 55        """How many arcs were added, reverse arcs excluded.
 56
 57        Returns:
 58            The arc count.
 59        """
 60        return len(self._to) // 2
 61
 62    def add_node(self) -> int:
 63        """Append one isolated node.
 64
 65        Returns:
 66            The identifier of the new node.
 67        """
 68        self._head.append([])
 69        return len(self._head) - 1
 70
 71    def add_edge(self, src: int, dst: int, capacity: int) -> int:
 72        """Append an arc and its reverse.
 73
 74        Args:
 75            src: Node the arc leaves.
 76            dst: Node the arc enters.
 77            capacity: Units the arc may carry, zero or more.
 78
 79        Returns:
 80            The identifier of the arc, used later by flow_on.
 81
 82        Raises:
 83            ValueError: If a node is unknown, if both ends are the same
 84                node, or if the capacity is negative.
 85        """
 86        self._check_node(src)
 87        self._check_node(dst)
 88        if src == dst:
 89            raise ValueError(f"arc from node {src} to itself")
 90        if capacity < 0:
 91            raise ValueError(f"negative capacity {capacity}")
 92        arc = len(self._to)
 93        self._to.append(dst)
 94        self._cap.append(capacity)
 95        self._to.append(src)
 96        self._cap.append(0)
 97        self._head[src].append(arc)
 98        self._head[dst].append(arc + 1)
 99        return arc
100
101    def flow_on(self, arc: int) -> int:
102        """Report how many units an arc currently carries.
103
104        The reverse arc's capacity counts exactly the units pushed
105        along the forward one, so no separate bookkeeping is needed.
106
107        Args:
108            arc: An identifier returned by add_edge.
109
110        Returns:
111            The units carried.
112
113        Raises:
114            ValueError: If the identifier names no forward arc.
115        """
116        if arc < 0 or arc >= len(self._to) or arc % 2 == 1:
117            raise ValueError(f"{arc} is not a forward arc")
118        return self._cap[arc ^ 1]
119
120    def residual(self, arc: int) -> int:
121        """Report how many more units an arc could carry.
122
123        Args:
124            arc: An identifier returned by add_edge.
125
126        Returns:
127            The capacity left.
128
129        Raises:
130            ValueError: If the identifier names no forward arc.
131        """
132        if arc < 0 or arc >= len(self._to) or arc % 2 == 1:
133            raise ValueError(f"{arc} is not a forward arc")
134        return self._cap[arc]
135
136    def max_flow(self, source: int, sink: int) -> int:
137        """Push as many units as possible from source to sink.
138
139        Args:
140            source: Node the units leave.
141            sink: Node the units must reach.
142
143        Returns:
144            The units pushed by this call. Repeated calls on a
145            growing network return the extra flow each one found, so
146            the caller adds them up to get the running total.
147
148        Raises:
149            ValueError: If a node is unknown or the two are the same.
150        """
151        self._check_node(source)
152        self._check_node(sink)
153        if source == sink:
154            raise ValueError("source and sink must differ")
155        pushed = 0
156        while self._build_levels(source, sink):
157            self._next = [0] * len(self._head)
158            while True:
159                found = self._augment(source, sink)
160                if found == 0:
161                    break
162                pushed += found
163        return pushed
164
165    def forward_arcs_from(self, node: int) -> list[int]:
166        """List the arcs leaving a node, reverse arcs excluded.
167
168        Args:
169            node: The node to look around.
170
171        Returns:
172            The identifiers of the arcs that were added at this node.
173
174        Raises:
175            ValueError: If no such node exists.
176        """
177        self._check_node(node)
178        return [arc for arc in self._head[node] if arc % 2 == 0]
179
180    def target(self, arc: int) -> int:
181        """Name the node an arc points at.
182
183        Args:
184            arc: An identifier returned by add_edge.
185
186        Returns:
187            The node the arc enters.
188
189        Raises:
190            ValueError: If the identifier names no forward arc.
191        """
192        if arc < 0 or arc >= len(self._to) or arc % 2 == 1:
193            raise ValueError(f"{arc} is not a forward arc")
194        return self._to[arc]
195
196    def _check_node(self, node: int) -> None:
197        """Reject a node identifier the network does not hold.
198
199        Args:
200            node: The identifier to check.
201
202        Raises:
203            ValueError: If no such node exists.
204        """
205        if node < 0 or node >= len(self._head):
206            raise ValueError(f"unknown node {node}")
207
208    def _build_levels(self, source: int, sink: int) -> bool:
209        """Label every node with its hop distance from the source.
210
211        Only arcs with capacity left are followed, so the labelling
212        describes the residual network. The next phase pushes flow
213        strictly from one level to the next, which is what makes the
214        paths it finds the shortest ones available.
215
216        Args:
217            source: Node to measure distances from.
218            sink: Node the search is trying to reach.
219
220        Returns:
221            True while the sink is still reachable.
222        """
223        self._level = [-1] * len(self._head)
224        self._level[source] = 0
225        queue: deque[int] = deque([source])
226        while queue:
227            node = queue.popleft()
228            for arc in self._head[node]:
229                target = self._to[arc]
230                if self._cap[arc] > 0 and self._level[target] < 0:
231                    self._level[target] = self._level[node] + 1
232                    queue.append(target)
233        return self._level[sink] >= 0
234
235    def _augment(self, source: int, sink: int) -> int:
236        """Walk one path down the levels and saturate it.
237
238        The walk is iterative rather than recursive: a time-expanded
239        network is deep, and a recursive descent would risk exhausting
240        the interpreter's stack on the larger maps.
241
242        Each node keeps a cursor into its arc list. An arc that leads
243        nowhere is stepped over once and never revisited during this
244        phase, which is what keeps the phase linear in the arc count.
245
246        Args:
247            source: Node to start the walk at.
248            sink: Node the walk is trying to reach.
249
250        Returns:
251            The units pushed, or zero when no path is left.
252        """
253        path: list[int] = []
254        node = source
255        while True:
256            if node == sink:
257                return self._push(path)
258            arc = self._advance(node)
259            if arc is not None:
260                path.append(arc)
261                node = self._to[arc]
262                continue
263            self._level[node] = -1
264            if not path:
265                return 0
266            arc = path.pop()
267            node = self._to[arc ^ 1]
268            self._next[node] += 1
269
270    def _advance(self, node: int) -> int | None:
271        """Find the next usable arc leaving a node.
272
273        Args:
274            node: Node whose cursor to move.
275
276        Returns:
277            An arc going one level deeper with capacity to spare, or
278            None once the node's arcs are exhausted.
279        """
280        while self._next[node] < len(self._head[node]):
281            arc = self._head[node][self._next[node]]
282            target = self._to[arc]
283            deeper = self._level[target] == self._level[node] + 1
284            if self._cap[arc] > 0 and deeper:
285                return arc
286            self._next[node] += 1
287        return None
288
289    def _push(self, path: list[int]) -> int:
290        """Send as much as the tightest arc of a path allows.
291
292        Args:
293            path: The arcs of a source-to-sink walk, in order.
294
295        Returns:
296            The units pushed.
297        """
298        units = min(self._cap[arc] for arc in path)
299        for arc in path:
300            self._cap[arc] -= units
301            self._cap[arc ^ 1] += units
302        return units