280 lines
9.5 kB
1"""Turning a map into a layered flow network, one turn at a time.
2
3Each turn of the simulation becomes one copy of the map. A zone is a
4pair of nodes whose joining arc carries its occupancy limit; a
5connection is a pair of node whose joining arc carries its own. The
6layers are grown on demand so the scheduler can stop at the first turn
7count that fits every drone.
8"""
9
10from dataclasses import dataclass
11
12from ..connection import Connection
13from ..scenario import Scenario
14from ..schedule import AtZone, InFlight, Placement
15from ..zone import UNLIMITED, Zone, ZoneRole, ZoneType
16from .flow_network import FlowNetwork
17
18
19@dataclass(frozen=True)
20class NodeTag:
21 """What passing through a node means for a drone.
22
23 Only nodes that stand for a position carry a tag: the inbound node
24 of a zone, and the transit node of a flight. The decoder reads a
25 drone's itinerary straight off the tags of the path it walks.
26
27 Attributes:
28 turn: The turn this position belongs to.
29 placement: Where the drone is at that turn.
30 """
31
32 turn: int
33 placement: Placement
34
35
36class TimeExpandedNetwork:
37 """Build the network with its first turn in place.
38
39 Args:
40 scenario: The map and drone count to model.
41 """
42 def __init__(self, scenario: Scenario) -> None:
43 self._scenario = scenario
44 self._graph = FlowNetwork()
45 self._source = self._graph.add_node()
46 self._sink = self._graph.add_node()
47 self._tags: dict[int, NodeTag] = {}
48 self._in_nodes: list[dict[str, int]] = []
49 self._out_nodes: list[dict[str, int]] = []
50 self._in_flight: dict[int, list[tuple[int, str]]] = {}
51 self._horizon = -1
52 self.extend()
53
54 @property
55 def graph(self) -> FlowNetwork:
56 """The flow network being built.
57
58 Returns:
59 The solver holding every node and arc so far.
60 """
61 return self._graph
62
63 @property
64 def source(self) -> int:
65 """The node every drone starts from.
66
67 Returns:
68 The source node.
69 """
70 return self._source
71
72 @property
73 def sink(self) -> int:
74 """The node every delivered drone ends at.
75
76 Returns:
77 The sink node.
78 """
79 return self._sink
80
81 @property
82 def horizon(self) -> int:
83 """The last turn the network covers.
84
85 Returns:
86 The highest turn index built so far.
87 """
88 return self._horizon
89
90 def tag_of(self, node: int) -> NodeTag | None:
91 """Say what a node means, if it means anything.
92
93 Args:
94 node: A node of the flow network.
95
96 Returns:
97 Its tag, or None for the plumbing nodes that stand for a
98 capacity rather than a position.
99 """
100 return self._tags.get(node)
101
102 def extend(self) -> None:
103 """Add one more turn to the network."""
104 turn = self._horizon + 1
105 self._add_zones(turn)
106 if turn > 0:
107 self._add_links(turn)
108 self._add_waits(turn)
109 self._land_flights(turn)
110 self._horizon = turn
111
112 def _zones(self) -> list[Zone]:
113 """List the zones drones may occupy, in map order.
114
115 Returns:
116 Every zone except the blocked ones.
117 """
118 return [
119 zone
120 for zone in self._scenario.network.zones.values()
121 if zone.is_passable
122 ]
123
124 def _links_of(self, zone: Zone) -> list[tuple[Zone, Connection]]:
125 """List a zone's usable neighbors, best ones first.
126
127 Priority zones are placed ahead of the rest so the solver
128 explores them first. They cost the same turn as a normal zone,
129 so this cannot shorten a run; it only decides which of the
130 equally short runs comes out.
131
132 Args:
133 zone: The zone to look around.
134
135 Returns:
136 Neighboring zone and connecting link, priority first.
137
138 Raises:
139 KeyError: If the zone is not part of the map.
140 """
141 usable = [
142 pair
143 for pair in self._scenario.network.neighbors(zone.name)
144 if pair[0].is_passable
145 ]
146 usable.sort(
147 key=lambda pair: pair[0].zone_type is not ZoneType.PRIORITY
148 )
149 return usable
150
151 def _add_zones(self, turn: int) -> None:
152 """Lay out every zone of one turn.
153
154 The arc joining a zone's two nodes carries its occupancy
155 limit, so it counts exactly the drones standing there this
156 turn. The end zone gets no outbound node: a drone that reaches
157 it is delivered and leaves the network.
158
159 Args:
160 turn: The turn to build.
161 """
162 arriving: dict[str, int] = {}
163 leaving: dict[str, int] = {}
164 for zone in self._zones():
165 node = self._graph.add_node()
166 self._tags[node] = NodeTag(turn, AtZone(zone))
167 arriving[zone.name] = node
168 if zone.role is ZoneRole.END:
169 self._graph.add_edge(node, self._sink, UNLIMITED)
170 continue
171 departure = self._graph.add_node()
172 self._graph.add_edge(node, departure, zone.capacity)
173 leaving[zone.name] = departure
174 self._in_nodes.append(arriving)
175 self._out_nodes.append(leaving)
176 if turn == 0:
177 start = self._scenario.network.start.name
178 self._graph.add_edge(
179 self._source, arriving[start], self._scenario.nb_drones
180 )
181
182 def _add_links(self, turn: int) -> None:
183 """Lay out every connection of one transition.
184
185 One hub per connection carries its capacity and is shared by
186 both directions. Drones enter it from either and leave it
187 toward either end, so the model can pair an entry with the
188 wrong exit; that reads as a drone which waited while paying
189 for a link slot, which is a legal run, only a wasteful one.
190
191 Args:
192 turn: The turn drones arrive on, one past their departure.
193 """
194 hubs: dict[tuple[str, str], tuple[int, int]] = {}
195 for link in self._usable_links():
196 entrance = self._graph.add_node()
197 exit_node = self._graph.add_node()
198 self._graph.add_edge(entrance, exit_node, link.max_link_capacity)
199 hubs[link.key] = (entrance, exit_node)
200 for zone in self._zones():
201 departure = self._out_nodes[turn - 1].get(zone.name)
202 if departure is None:
203 continue
204 for _, link in self._links_of(zone):
205 self._graph.add_edge(departure, hubs[link.key][0], UNLIMITED)
206 for link in self._usable_links():
207 zones = self._scenario.network.zones
208 for name in (link.a, link.b):
209 self._add_arrival(hubs[link.key][1], zones[name], link, turn)
210
211 def _usable_links(self) -> list[Connection]:
212 """List the connections drones may cross, in map order.
213
214 Returns:
215 Every connection whose two ends are both passable.
216 """
217 zones = self._scenario.network.zones
218 return [
219 link
220 for link in self._scenario.network.connections.values()
221 if zones[link.a].is_passable and zones[link.b].is_passable
222 ]
223
224 def _add_arrival(
225 self, hub: int, zone: Zone, link: Connection, turn: int
226 ) -> None:
227 """Let drones leave a link hub into one of its two ends.
228
229 Reaching a restricted zone takes a turn longer, so the drone
230 lands on a transit node instead. That node is its position for
231 this turn and has a single way out, which is what forces it to
232 arrive next turn rather than hover until space appears.
233
234 Args:
235 hub: The outbound node of the link's hub.
236 zone: The end being entered.
237 link: The connection being crossed.
238 turn: The turn of the arrival, or of the flight.
239 """
240 if zone.zone_type is not ZoneType.RESTRICTED:
241 self._graph.add_edge(
242 hub, self._in_nodes[turn][zone.name], UNLIMITED
243 )
244 return
245 transit = self._graph.add_node()
246 self._tags[transit] = NodeTag(turn, InFlight(link, zone))
247 self._graph.add_edge(hub, transit, UNLIMITED)
248 self._in_flight.setdefault(turn, []).append((transit, zone.name))
249
250 def _add_waits(self, turn: int) -> None:
251 """Let drones hold their position for one turn.
252
253 These arcs come after the movement arcs of the same zone, so
254 the solver tries every way out before it tries standing still.
255
256 Args:
257 turn: The turn being waited into.
258 """
259 for zone in self._zones():
260 departure = self._out_nodes[turn - 1].get(zone.name)
261 if departure is None:
262 continue
263 self._graph.add_edge(
264 departure, self._in_nodes[turn][zone.name], UNLIMITED
265 )
266
267 def _land_flights(self, turn: int) -> None:
268 """Bring last turn's flights down into their destinations.
269
270 A flight left hanging at the final turn simply leads nowehre,
271 which is how the model refuses to end a run with a drone still
272 on a connection.
273
274 Args:
275 turn: The turn the flights arrive on.
276 """
277 for transit, name in self._in_flight.get(turn - 1, []):
278 self._graph.add_edge(
279 transit, self._in_nodes[turn][name], UNLIMITED
280 )