summaryrefslogtreecommitdiff
path: root/src/scheduler.py
blob: 9a33aecf70b85513e62ff7ac6a311cc80b8cb3de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""Scheduling of the simulation.
    Does not run the pathfinding algorithm
"""

from drone import Drone
from typing import List, Tuple
from graph import Graph
from models import Zone, ZoneType, Connection
from pathfinder import Pathfinder, PathResult


class Scheduler:
    """Schedule multiple drones on a common path.

        If a zone of the path is RESTRICTED and congested,
        i.e. at max capacity, a new path is computed for
        that drone
    """

    def __init__(
        self,
        graph: Graph,
        path: List[str],
        number_of_drones: int,
    ) -> None:
        """Initialize the scheduler."""
        self.graph = graph
        self.drones = [
            Drone(id_=index, path=path.copy())
            for index in range(1, number_of_drones + 1)
        ]

    @property
    def all_delivered(self) -> bool:
        """Check if all drones have been delivered"""
        return all(drone.delivered for drone in self.drones)

    def run(self) -> None:
        """Run the simulation until all drones have reached the goal."""

        # self.all_delivered using the property above
        while not self.all_delivered:
            movements = self._run_turn()

            if movements:
                print(f"{' '.join(movements)}")

    def _list_moves(self) -> List[Tuple[Drone, str]]:
        """This loop creates an object 'moves', a list
        of Drone and the destination of their next
        move.
        """

        moves: List[Tuple[Drone, str]] = []

        for drone in self.drones:
            if drone.delivered:
                continue

            if drone.next_zone is None:
                raise KeyError("No next zone")
            dest_name: str = drone.next_zone

            if dest_name is not None:
                moves.append((drone, dest_name))

        return moves

    def _compute_new_path(
                        self,
                        src: Zone,
                        dest: Zone,
                        ) -> PathResult | None:
        """ Compute new path when path is congested"""

        # get the end of the current path
        end: Zone = self.graph.get_end()

        pathfinder: Pathfinder = Pathfinder(self.graph)
        if pathfinder is None:
            return None
        path_result: PathResult | None = pathfinder.find_path(src.name,
                                                              end.name
                                                              )
        return path_result

    def _run_turn(self) -> List[str]:
        """Calculate and apply valid movements for one turn.

            for each drone, the algorithm checks if the
            drone can travel to its dest, and if so does so.

            Else, the algorithm computes a new path.

            If there no path is found; the algo moves on to
            the next drone in the list.
        """

        moves: List[Tuple[Drone, str]] = self._list_moves()

        connections_to_clear: List[Connection] = []
        accepted: List[str] = []

        for drone, dest_name in moves:

            # get src and dest
            dest: Zone = self.graph.get_zone(dest_name)
            src_name: str = drone.current_zone
            src: Zone = self.graph.get_zone(src_name)

            if drone.in_transit is True:
                connection = self.graph.get_connection(src, dest)
                drone.leave_transit(src,
                                    dest,
                                    self.graph
                                    )
                accepted.append(f"D{drone.id_}-"
                                f"{self._color_zone(dest_name)}-"
                                f"{dest.occupancy}/{dest.max_drones}")
                connections_to_clear.append(self.graph.get_connection(src,
                                                                      dest
                                                                      )
                                            )
                continue

            # drone is on its way to restricted zone
            if dest.zone_type == ZoneType.RESTRICTED:
                connection = self.graph.get_connection(src, dest)
                if connection.link_capacity > connection.link_occupancy \
                   and dest.reservation < dest.max_drones:
                    dest.reservation += 1
                    connection.link_occupancy += 1
                    drone.in_transit = True
            else:
                # if zone is not restricted
                while not self._can_enter(dest) \
                        or not self._can_transit(src, dest):

                    # if the zone is congested
                    if not self._can_enter(dest) and not dest.name == 'goal':
                        dest.congested = True

                    # if the connection is congested
                    if not self._can_transit(src, dest):
                        self._connection_congested(src, dest, self.graph)

                    path_result: PathResult | None = (
                        self._compute_new_path(src, dest)
                        )
                    if path_result is None:
                        break

                    if self._new_dest_reachable(path_result):
                        drone.update_path(path_result)
                        dest = drone.update_dest(self.graph)
                    else:
                        break

                # when path_result is None
                # for loop moves on to the next drone
                connection = self.graph.get_connection(src, dest)
                if dest.congested is True or connection.congested is True:
                    continue

                # regular move
                drone.move()
                self._increment_connection_occupancy(src, dest, self.graph)
            if src.name != 'start':
                src.occupancy -= 1
            # udpate occupancy of destination zone
            if not dest.name == 'goal':
                dest.occupancy += 1
            accepted.append(f"D{drone.id_}-"
                            f"{self._color_zone(dest.name)}-"
                            f"{dest.occupancy}/{dest.max_drones}")
            connections_to_clear.append(connection)

            # drone is leaving source
            if src.congested is True:
                src.congested = False

        self._clear_connections_occupancy(connections_to_clear)
        return accepted

    def _new_dest_reachable(self, path_result: PathResult) -> bool:
        path = path_result.path
        src_name = path[0]
        src: Zone = self.graph.get_zone(src_name)
        next_zone_name = path[1]
        next_zone: Zone = self.graph.get_zone(next_zone_name)
        if self._can_enter(next_zone) and self._can_transit(src, next_zone):
            return True
        else:
            return False

    @staticmethod
    def _increment_connection_occupancy(src: Zone,
                                        dest: Zone,
                                        graph: Graph
                                        ) -> None:
        """Increment the occupancy attribute of a Connection"""
        connection = graph.get_connection(src, dest)
        connection.link_occupancy += 1

    @staticmethod
    def _connection_congested(src: Zone,
                              dest: Zone,
                              graph: Graph
                              ) -> None:
        """Toogle congested attribute of Connection to True"""
        connection = graph.get_connection(src, dest)
        connection.congested = True

    @staticmethod
    def _clear_connections_occupancy(connections: List[Connection]) -> None:
        """Clear occupancy of connections"""
        for connection in connections:
            if connection.dest.zone_type == ZoneType.RESTRICTED:
                continue
            connection.link_occupancy -= 1
            connection.congested = False

    # spin off color methods to its own class
    def _color_zone(
                self,
                dest: str,
                ) -> str:
        """Color zone name if zone has a color attribute"""
        zone = self.graph.get_zone(dest)
        if zone.color is None:
            return zone.name
        if zone.color:
            return self._color_string(zone, zone.color)
        raise KeyError(f"No zone {dest}")

    def _color_string(
                    self,
                    zone: Zone,
                    zone_color: str
                    ) -> str:
        all_colors: dict[str, str] = {'black': "\033[0;30m",
                                      'red': "\033[0;31m",
                                      'green': "\033[0;32m",
                                      'yellow': "\033[0;33m",
                                      'blue': "\033[0;34m",
                                      'magenta': "\033[0;35m",
                                      'cyan': "\033[0;36m",
                                      'white': "\033[0;37m",
                                      'gray': "\033[0;90m",
                                      'grey': "\033[0;90m",
                                      # using 256-color mode
                                      'brown': "\033[38;5;137",
                                      'crimson': "\033[38;5;160m",
                                      'darkred': "\033[38;5;52m",
                                      'gold': "\033[38;5;226m",
                                      'lime': "\033[38;5;83m",
                                      'maroon': "\033[38;5;001m",
                                      'orange': "\033[38;5;208m",
                                      'purple': "\033[38;5;128m",
                                      'violet': "\033[38;5;93m",
                                      'pink': "\033[38;5;201m"
                                      }

        for color in all_colors:
            if zone_color == color:
                return f"{all_colors[color]}{zone.name}\033[0m"
        raise KeyError(f"No color '{zone_color}', check your map.")

    @staticmethod
    def _can_enter(dest: Zone) -> bool:
        """Return whether a destination has enough capacity."""
        if dest.is_end:
            return True

        return dest.occupancy < dest.max_drones

    def _can_transit(self,
                     src: Zone,
                     dest: Zone
                     ) -> bool:
        """Return whether a drone can transit through a connection."""

        occupancy = self.graph.get_link_occupancy(src, dest)
        capacity = self.graph.get_link_capacity(src, dest)
        return occupancy < capacity