​fly-in /
src / simulation.py
63 commits
09-08-2026
344 lines 12 kB
  1"""Replaying a schedule while checking every rule of the flight.
  2
  3Nothing here comes from src.flow. The solver decides what the
  4drones do; this module works out, from the map alone, whether they
  5were allowed to do it.
  6"""
  7
  8from .connection import Connection
  9from .errors import SimulationError
 10from .render.base import Renderer
 11from .scenario import Scenario
 12from .schedule import AtZone, InFlight, Move, Placement, Schedule
 13from .zone import Zone, ZoneRole, ZoneType
 14
 15
 16class Simulation:
 17    """Walks a schedule turn by turn and enforces the rules.
 18
 19    A turn is checked in full before it is shown, so a schedule that
 20    breaks a rule never reaches the output. Placements are inspected
 21    by kind rather than asked what they allow: the rulebook belongs to
 22    the simulation, and spreading it over the placement classes would
 23    scatter it across two modules.
 24    """
 25
 26    def __init__(self, scenario: Scenario, schedule: Schedule) -> None:
 27        """Prepare to replay one schedule.
 28
 29        Args:
 30            scenario: The map the schedule was built for.
 31            schedule: The run to check.
 32
 33        Raises:
 34            ValueError: If the schedule belongs to another scenario.
 35        """
 36        if schedule._scenario is not scenario:
 37            raise ValueError("schedule and scenario do not match")
 38        self._scenario = scenario
 39        self._schedule = schedule
 40        self._network = scenario.network
 41        self._places: dict[int, Placement] = {}
 42
 43    def run(self, renderer: Renderer) -> int:
 44        """Replay the whole schedule through a view.
 45
 46        Args:
 47            renderer: The view to show each turn on.
 48
 49        Returns:
 50            The number of turns the tun takes.
 51
 52        Raises:
 53            SimulationError: If any turn breaks a rule, or if a drone
 54                is left undelivered at the end.
 55        """
 56        start = self._network.start
 57        self._places = {
 58            drone: AtZone(start)
 59            for drone in range(1, self._scenario.nb_drones + 1)
 60        }
 61        renderer.begin(self._scenario)
 62        turn = 0
 63        for turn, moves in enumerate(self._schedule, start=1):
 64            self._play(turn, moves)
 65            renderer.show_turn(turn, moves)
 66        self._require_delivery(turn)
 67        renderer.finish(turn)
 68        return turn
 69
 70    def _play(self, turn: int, moves: list[Move]) -> None:
 71        """Check one turn and apply it.
 72
 73        Args:
 74            turn: 1-based number of the turn.
 75            moves: The drones said to move this turn.
 76
 77        Raises:
 78            SimulationError: If the turn breaks a rule.
 79        """
 80        movers: dict[int, Placement] = {}
 81        for move in moves:
 82            if move.drone_id in movers:
 83                raise SimulationError(turn, f"D{move.drone_id} moves twice")
 84            if move.drone_id not in self._places:
 85                raise SimulationError(turn, f"D{move.drone_id} does not fly")
 86            movers[move.drone_id] = move.placement
 87        entered: dict[tuple[str, str], int] = {}
 88        for drone, place in self._places.items():
 89            target = movers.get(drone)
 90            if target is None:
 91                self._check_stay(turn, drone, place)
 92                continue
 93            link = self._check_move(turn, drone, place, target)
 94            if link is not None:
 95                entered[link.key] = entered.get(link.key, 0) + 1
 96        self._places.update(movers)
 97        self._check_occupancy(turn)
 98        self._check_links(turn, entered)
 99
100    def _check_stay(self, turn: int, drone: int, place: Placement) -> None:
101        """Check a drone is allowed to hold its position.
102
103        Args:
104            turn: 1-based number of the turn.
105            drone: Identifier of the drone.
106            place: Where it stood at the end of the previous turn.
107
108        Raises:
109            SimulationError: If it was in flight, since a crossing
110                must finish on the very next turn.
111        """
112        if isinstance(place, InFlight):
113            raise SimulationError(
114                turn,
115                f"D{drone} stayed on {place.connection} instead of "
116                f"reaching {place.target.name}"
117            )
118
119    def _check_move(
120        self, turn: int, drone: int, was: Placement, now: Placement
121    ) -> Connection | None:
122        """Check one drone's movement and report the link it took.
123
124        Args:
125            turn: 1-based number of the turn.
126            drone: Identifier of the droke.
127            was: Where it stood at the end of the previous turn.
128            now: Where the schedule puts it this turn.
129
130        Returns:
131            The connection it entered this turn, or None when it only
132            finished a crossing already under way.
133
134        Raises:
135            SimulationError: If the movement breaks a rule.
136        """
137        if isinstance(was, InFlight):
138            landed = isinstance(now, AtZone) and now.zone == was.target
139            if not landed:
140                raise SimulationError(
141                    turn,
142                    f"D{drone} was crossing to {was.target.name} and "
143                    f"went to {now.label()} instead"
144                )
145            return None
146        if not isinstance(was, AtZone):
147            raise SimulationError(turn, f"D{drone} was nowehere in particular")
148        if was.zone.role is ZoneRole.END:
149            raise SimulationError(
150                turn, f"D{drone} left the end zone after delivery"
151            )
152        if isinstance(now, InFlight):
153            return self._check_takeoff(turn, drone, was.zone, now)
154        if not isinstance(now, AtZone):
155            raise SimulationError(
156                turn, f"D{drone} moved nowhere in particular"
157            )
158        return self._check_hop(turn, drone, was.zone, now.zone)
159
160    def _check_takeoff(
161        self, turn: int, drone: int, was: Zone, now: InFlight
162    ) -> Connection:
163        """Check a drone starting a crossing toward a restricted zone.
164
165        Args:
166            turn: 1-based number of the turn.
167            drone: Identifier of the drone.
168            was: Zone it left.
169            now: The crossing it started.
170
171        Returns:
172            The connection it entered.
173
174        Raises:
175            SimulationError: If the destination is not restricted, or
176                the connection does not join the two zones.
177        """
178        target = self._known(turn, drone, now.target)
179        if target.zone_type is not ZoneType.RESTRICTED:
180            raise SimulationError(
181                turn,
182                f"D{drone} flies toward {target.name}, which is not "
183                "restricted and takes a single turn to enter"
184            )
185        link = self._link_between(turn, drone, was, target)
186        if now.connection.key != link.key:
187            raise SimulationError(
188                turn,
189                f"D{drone} reports {now.connection} but flies from "
190                f"{was.name} to {target.name}"
191            )
192        return link
193
194    def _check_hop(
195        self, turn: int, drone: int, was: Zone, now: Zone
196    ) -> Connection:
197        """Check a drone crossing to a neighboring zone in one turn.
198
199        Args:
200            turn: 1-based number of the turn.
201            drone: Identifier of the drone.
202            was: Zone it left.
203            now: Zone it entered.
204
205        Returns:
206            The connection it used.
207
208        Raises:
209            SimulationError: If the zones are not joined, if the
210                destination is blocked, or if it is restricted and so
211                cannot be entered in a single turn.
212        """
213        target = self._known(turn, drone, now)
214        if not target.is_passable:
215            raise SimulationError(
216                turn, f"D{drone} entered the blocked zone {target.name}"
217            )
218        if target.zone_type is ZoneType.RESTRICTED:
219            raise SimulationError(
220                turn,
221                f"D{drone} entered the restricted zone {target.name} "
222                "in a single turn"
223            )
224        return self._link_between(turn, drone, was, target)
225
226    def _known(self, turn: int, drone: int, zone: Zone) -> Zone:
227        """Check a placement names a zone this map actually holds.
228
229        Args:
230            turn: 1-based number of the turn.
231            drone: Identifier of the drone.
232            zone: The zone named by the placement.
233
234        Returns:
235            The map's own copy of that zone.
236
237        Raises:
238            SimulationError: If the map holds no such zone.
239        """
240        known = self._network.zones.get(zone.name)
241        if known is None or known != zone:
242            raise SimulationError(
243                turn, f"D{drone} moved to unknown zone {zone.name!r}"
244            )
245        return known
246
247    def _link_between(
248        self, turn: int, drone: int, was: Zone, now: Zone
249    ) -> Connection:
250        """Find the connection joining two zones.
251
252        Args:
253            turn: 1-based number of the turn.
254            drone: Identifier of the drone.
255            was: Zone left.
256            now: Zone entered.
257
258        Returns:
259            The connection joining them.
260
261        Raises:
262            SimulationError: If no connection joins them.
263        """
264        first, second = sorted((was.name, now.name))
265        link = self._network.connections.get((first, second))
266        if link is None:
267            raise SimulationError(
268                turn,
269                f"D{drone} jumped from {was.name} to {now.name}, "
270                "which share no connection"
271            )
272        return link
273
274    def _check_occupancy(self, turn: int) -> None:
275        """Check no zone holds more than it may.
276
277        Occupancy is counted once the turn has been applied, so a
278        drone that left frees its place for one that arrives. The
279        start and end zone report no limit.
280
281        Args:
282            turn: 1-based number of the turn.
283
284        Raises:
285            SimulationError: If the zone is over its limit.
286        """
287        held: dict[str, int] = {}
288        for place in self._places.values():
289            if isinstance(place, AtZone):
290                held[place.zone.name] = held.get(place.zone.name, 0) + 1
291        for name, count in held.items():
292            allowed = self._network.zones[name].capacity
293            if count > allowed:
294                raise SimulationError(
295                    turn, f"{name} holds {count} drones, over its {allowed}"
296                )
297
298    def _check_links(
299        self, turn: int, entered: dict[tuple[str, str], int]
300    ) -> None:
301        """Check no connection was entered by too many drones.
302
303        A drone finishing a crossing is leaving the connection, not
304        entering it, so it is not counted here: the same reading of
305        the rules the solver uses when it builds its network.
306
307        Args:
308            turn: 1-based number of the turn.
309            entered: How many drones took each connection this turn.
310
311        Raises:
312            SimulationError: If a connection is over its limits.
313        """
314        for key, count in entered.items():
315            link = self._network.connections[key]
316            if count > link.max_link_capacity:
317                raise SimulationError(
318                    turn,
319                    f"{link} carries {count} drones, over its "
320                    f"{link.max_link_capacity}"
321                )
322
323    def _require_delivery(self, turn: int) -> None:
324        """Check the run ends with every drone delivered.
325
326        Args:
327            turn: Number of the last rurn played.
328
329        Raises:
330            SimulationError: If any drone is elsewhere.
331        """
332        stranded = sorted(
333            drone
334            for drone, place in self._places.items()
335            if not (
336                isinstance(place, AtZone)
337                and place.zone.role is ZoneRole.END
338            )
339        )
340        if stranded:
341            names = " ".join(f"D{drone}" for drone in stranded)
342            raise SimulationError(
343                turn, f"the run ends with {names} undelivered"
344            )