2 files changed, +271, -0
347dc03Add flow package
author
mogi <git@paramogi.world> on 07-08-2026 13:22 UTC+1
committer
mogi <git@paramogi.world> on 07-08-2026 13:28 UTC+1
parentdb5d94d
      @@ -0,0 +1,271 @@
     1+"""A hand-written maximum-flow solver over integer capacities.
     2+
     3+The class here knows nothing about zones, drones or turns: it moves
     4+units through numbered nodes. Everything specific to the simulation is
     5+built on top of it by :mod:`src.flow.time_expanded`.
     6+"""
     7+
     8+from collections import deque
     9+
    10+
    11+class 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 :meth:`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 :meth:`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 :meth:`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 :meth:`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 _check_node(self, node: int) -> None:
   166+        """Reject a node identifier the network does not hold.
   167+
   168+        Args:
   169+            node: The identifier to check.
   170+
   171+        Raises:
   172+            ValueError: If no such node exists.
   173+        """
   174+        if node < 0 or node >= len(self._head):
   175+            raise ValueError(f"unknown node {node}")
   176+
   177+    def _build_levels(self, source: int, sink: int) -> bool:
   178+        """Label every node with its hop distance from the source.
   179+
   180+        Only arcs with capacity left are followed, so the labelling
   181+        describes the residual network. The next phase pushes flow
   182+        strictly from one level to the next, which is what makes the
   183+        paths it finds the shortest ones available.
   184+
   185+        Args:
   186+            source: Node to measure distances from.
   187+            sink: Node the search is trying to reach.
   188+
   189+        Returns:
   190+            True while the sink is still reachable.
   191+        """
   192+        self._level = [-1] * len(self._head)
   193+        self._level[source] = 0
   194+        queue: deque[int] = deque([source])
   195+        while queue:
   196+            node = queue.popleft()
   197+            for arc in self._head[node]:
   198+                target = self._to[arc]
   199+                if self._cap[arc] > 0 and self._level[target] < 0:
   200+                    self._level[target] = self._level[node] + 1
   201+                    queue.append(target)
   202+        return self._level[sink] >= 0
   203+
   204+    def _augment(self, source: int, sink: int) -> int:
   205+        """Walk one path down the levels and saturate it.
   206+
   207+        The walk is iterative rather than recursive: a time-expanded
   208+        network is deep, and a recursive descent would risk exhausting
   209+        the interpreter's stack on the larger maps.
   210+
   211+        Each node keeps a cursor into its arc list. An arc that leads
   212+        nowhere is stepped over once and never revisited during this
   213+        phase, which is what keeps the phase linear in the arc count.
   214+
   215+        Args:
   216+            source: Node to start the walk at.
   217+            sink: Node the walk is trying to reach.
   218+
   219+        Returns:
   220+            The units pushed, or zero when no path is left.
   221+        """
   222+        path: list[int] = []
   223+        node = source
   224+        while True:
   225+            if node == sink:
   226+                return self._push(path)
   227+            arc = self._advance(node)
   228+            if arc is not None:
   229+                path.append(arc)
   230+                node = self._to[arc]
   231+                continue
   232+            self._level[node] = -1
   233+            if not path:
   234+                return 0
   235+            arc = path.pop()
   236+            node = self._to[arc ^ 1]
   237+            self._next[node] += 1
   238+
   239+    def _advance(self, node: int) -> int | None:
   240+        """Find the next usable arc leaving a node.
   241+
   242+        Args:
   243+            node: Node whose cursor to move.
   244+
   245+        Returns:
   246+            An arc going one level deeper with capacity to spare, or
   247+            None once the node's arcs are exhausted.
   248+        """
   249+        while self._next[node] < len(self._head[node]):
   250+            arc = self._head[node][self._next[node]]
   251+            target = self._to[arc]
   252+            deeper = self._level[target] == self._level[node] + 1
   253+            if self._cap[arc] > 0 and deeper:
   254+                return arc
   255+            self._next[node] += 1
   256+        return None
   257+
   258+    def _push(self, path: list[int]) -> int:
   259+        """Send as much as the tightest arc of a path allows.
   260+
   261+        Args:
   262+            path: The arcs of a source-to-sink walk, in order.
   263+
   264+        Returns:
   265+            The units pushed.
   266+        """
   267+        units = min(self._cap[arc] for arc in path)
   268+        for arc in path:
   269+            self._cap[arc] -= units
   270+            self._cap[arc ^ 1] += units
   271+        return units