152 lines
5.6 kB
1"""Finding the shortest run, and reading it back as a schedule."""
2
3from collections import deque
4
5from ..errors import FlyInError
6from ..scenario import Scenario
7from ..schedule import Move, Placement, Schedule
8from ..zone import Zone
9from .time_expanded import TimeExpandedNetwork
10
11
12class Scheduler:
13 """Works out the fewest turns a map can be flown in.
14
15 The network is grown one turn at a time and solved again after
16 each layer. Because the solver keeps its residual capacities, the
17 first turn count that carries every drone is the smallest one that
18 can: a shorter run would have filled an earlier layer.
19 """
20
21 def __init__(self, scenario: Scenario) -> None:
22 """Prepare a scheduler for one map.
23
24 Args:
25 scenario: The map and drone count to solve.
26 """
27 self._scenario = scenario
28 self._expanded = TimeExpandedNetwork(scenario)
29
30 def solve(self) -> Schedule:
31 """Find a shortest run and describe it turn by turn.
32
33 Returns:
34 The schedule every drone follows.
35
36 Raises:
37 FlyInError: If no route reaches the end zone, or if the
38 run refuses to close within a generous turn limit.
39 """
40 self._require_a_route()
41 self._grow()
42 return self._build(self._itineraries())
43
44 def _require_a_route(self) -> None:
45 """Check the end zone can be reached at all.
46
47 Capacities are ignored here: this only rules out a map whose
48 end zone is walled off, which is worth reporting immediately
49 rather than after a hundred fruitless layers.
50
51 Raises:
52 FlyInError: If no chain of passable zones joins the ends.
53 """
54 network = self._scenario.network
55 start, end = network.start, network.end
56 if not start.is_passable or not end.is_passable:
57 raise FlyInError("the start or end zone is blocked")
58 seen = {start.name}
59 queue: deque[Zone] = deque([start])
60 while queue:
61 zone = queue.popleft()
62 if zone.name == end.name:
63 return
64 for neighbor, _ in network.neighbors(zone.name):
65 if neighbor.is_passable and neighbor.name not in seen:
66 seen.add(neighbor.name)
67 queue.append(neighbor)
68 raise FlyInError(
69 f"no route leads from {start.name} to {end.name}"
70 )
71
72 def _grow(self) -> None:
73 """Add turns until every drone reaches the end zone.
74
75 Raises:
76 FlyInError: If the limit is reached first, which means the
77 capacities of the map cannot pass this many drones.
78 """
79 graph = self._expanded.graph
80 wanted = self._scenario.nb_drones
81 limit = 2 * len(self._scenario.network) + 2 * wanted + 8
82 delivered = graph.max_flow(
83 self._expanded.source, self._expanded.sink
84 )
85 while delivered < wanted:
86 if self._expanded.horizon >= limit:
87 raise FlyInError(
88 f"only {delivered} of {wanted} drones can be "
89 f"delivered within {limit} turns"
90 )
91 self._expanded.extend()
92 delivered += graph.max_flow(
93 self._expanded.source, self._expanded.sink
94 )
95
96 def _itineraries(self) -> list[dict[int, Placement]]:
97 """Split the flow back into one route per drone.
98
99 The layered network only ever points forward in time, so a
100 walk that always takes an arc still carrying flow cannot loop
101 and cannot get stuck: whatever enters a node leaves it again.
102
103 Returns:
104 For each drone, where it stands on each of its turns.
105 """
106 graph = self._expanded.graph
107 unread = {
108 arc: graph.flow_on(arc)
109 for node in range(graph.size)
110 for arc in graph.forward_arcs_from(node)
111 }
112 routes: list[dict[int, Placement]] = []
113 for _ in range(self._scenario.nb_drones):
114 route: dict[int, Placement] = {}
115 node = self._expanded.source
116 while node != self._expanded.sink:
117 arc = next(
118 candidate
119 for candidate in graph.forward_arcs_from(node)
120 if unread[candidate] > 0
121 )
122 unread[arc] -= 1
123 node = graph.target(arc)
124 tag = self._expanded.tag_of(node)
125 if tag is not None:
126 route[tag.turn] = tag.placement
127 routes.append(route)
128 return routes
129
130 def _build(self, routes: list[dict[int, Placement]]) -> Schedule:
131 """Turn one route per drone into one line per turn.
132
133 A drone appears in a turn only when its placement changed,
134 which is what the output format asks for. A delivered drone
135 has no placement left to report, so it simply stops appearing.
136
137 Args:
138 routes: Where each drone stands on each of its turns.
139
140 Returns:
141 The finished schedule.
142 """
143 schedule = Schedule(self._scenario)
144 for turn in range(1, self._expanded.horizon + 1):
145 moves: list[Move] = []
146 for drone, route in enumerate(routes, start=1):
147 here = route.get(turn)
148 if here is None or here == route.get(turn - 1):
149 continue
150 moves.append(Move(drone, here))
151 schedule.add_turn(moves)
152 return schedule