schedule_generators.py 9.84 KB
Newer Older
u214892's avatar
u214892 committed
1
"""Schedule generators (railway undertaking, "EVU")."""
2
import warnings
u214892's avatar
u214892 committed
3
4
5
6
7
8
9
10
11
12
from typing import Tuple, List, Callable, Mapping, Optional, Any

import msgpack
import numpy as np

from flatland.core.grid.grid4_utils import get_new_position
from flatland.core.transition_map import GridTransitionMap
from flatland.envs.agent_utils import EnvAgentStatic

AgentPosition = Tuple[int, int]
u214892's avatar
u214892 committed
13
14
ScheduleGeneratorProduct = Tuple[List[AgentPosition], List[AgentPosition], List[AgentPosition], List[float]]
ScheduleGenerator = Callable[[GridTransitionMap, int, Optional[Any]], ScheduleGeneratorProduct]
u214892's avatar
u214892 committed
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


def speed_initialization_helper(nb_agents: int, speed_ratio_map: Mapping[float, float] = None) -> List[float]:
    """
    Parameters
    -------
    nb_agents : int
        The number of agents to generate a speed for
    speed_ratio_map : Mapping[float,float]
        A map of speeds mappint to their ratio of appearance. The ratios must sum up to 1.

    Returns
    -------
    List[float]
        A list of size nb_agents of speeds with the corresponding probabilistic ratios.
    """
    if speed_ratio_map is None:
        return [1.0] * nb_agents

    nb_classes = len(speed_ratio_map.keys())
    speed_ratio_map_as_list: List[Tuple[float, float]] = list(speed_ratio_map.items())
    speed_ratios = list(map(lambda t: t[1], speed_ratio_map_as_list))
    speeds = list(map(lambda t: t[0], speed_ratio_map_as_list))
    return list(map(lambda index: speeds[index], np.random.choice(nb_classes, nb_agents, p=speed_ratios)))


41
def complex_schedule_generator(speed_ratio_map: Mapping[float, float] = None) -> ScheduleGenerator:
u214892's avatar
u214892 committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    def generator(rail: GridTransitionMap, num_agents: int, hints: Any = None):
        start_goal = hints['start_goal']
        start_dir = hints['start_dir']
        agents_position = [sg[0] for sg in start_goal[:num_agents]]
        agents_target = [sg[1] for sg in start_goal[:num_agents]]
        agents_direction = start_dir[:num_agents]

        if speed_ratio_map:
            speeds = speed_initialization_helper(num_agents, speed_ratio_map)
        else:
            speeds = [1.0] * len(agents_position)

        return agents_position, agents_direction, agents_target, speeds

    return generator


59
def sparse_schedule_generator(speed_ratio_map: Mapping[float, float] = None) -> ScheduleGenerator:
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
    def generator(rail: GridTransitionMap, num_agents: int, hints: Any = None):
        train_stations = hints['train_stations']
        agent_start_targets_nodes = hints['agent_start_targets_nodes']
        # Place agents and targets within available train stations
        agents_position = []
        agents_target = []
        agents_direction = []
        for agent_idx in range(num_agents):
            # Set target for agent
            current_target_node = agent_start_targets_nodes[agent_idx][1]
            target_station_idx = np.random.randint(len(train_stations[current_target_node]))
            target = train_stations[current_target_node][target_station_idx]
            tries = 0
            while (target[0], target[1]) in agents_target:
                target_station_idx = np.random.randint(len(train_stations[current_target_node]))
                target = train_stations[current_target_node][target_station_idx]
                tries += 1
                if tries > 100:
                    warnings.warn("Could not set target position, removing an agent")
                    break
            agents_target.append((target[0], target[1]))

            # Set start for agent
            current_start_node = agent_start_targets_nodes[agent_idx][0]
            start_station_idx = np.random.randint(len(train_stations[current_start_node]))
            start = train_stations[current_start_node][start_station_idx]
            tries = 0
            while (start[0], start[1]) in agents_position:
                tries += 1
                if tries > 100:
                    warnings.warn("Could not set start position, please change initial parameters!!!!")
                    break
                start_station_idx = np.random.randint(len(train_stations[current_start_node]))
                start = train_stations[current_start_node][start_station_idx]

            agents_position.append((start[0], start[1]))

            # Orient the agent correctly
            for orientation in range(4):
                transitions = rail.get_transitions(start[0], start[1], orientation)
                if any(transitions) > 0:
                    agents_direction.append(orientation)
                    continue

        if speed_ratio_map:
            speeds = speed_initialization_helper(num_agents, speed_ratio_map)
        else:
            speeds = [1.0] * len(agents_position)

        return agents_position, agents_direction, agents_target, speeds

    return generator


114
def random_schedule_generator(speed_ratio_map: Mapping[float, float] = None) -> ScheduleGenerator:
u214892's avatar
u214892 committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    """
    Given a `rail' GridTransitionMap, return a random placement of agents (initial position, direction and target).

    Parameters
    -------
        rail : GridTransitionMap
            The railway to place agents on.
        num_agents : int
            The number of agents to generate a speed for
        speed_ratio_map : Mapping[float,float]
            A map of speeds mappint to their ratio of appearance. The ratios must sum up to 1.
    Returns
    -------
        Tuple[List[Tuple[int,int]], List[Tuple[int,int]], List[Tuple[int,int]], List[float]]
        initial positions, directions, targets speeds
    """

u214892's avatar
u214892 committed
132
    def generator(rail: GridTransitionMap, num_agents: int, hints: Any = None) -> ScheduleGeneratorProduct:
u214892's avatar
u214892 committed
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
        def _path_exists(rail, start, direction, end):
            # BFS - Check if a path exists between the 2 nodes

            visited = set()
            stack = [(start, direction)]
            while stack:
                node = stack.pop()
                if node[0][0] == end[0] and node[0][1] == end[1]:
                    return 1
                if node not in visited:
                    visited.add(node)
                    moves = rail.get_transitions(node[0][0], node[0][1], node[1])
                    for move_index in range(4):
                        if moves[move_index]:
                            stack.append((get_new_position(node[0], move_index),
                                          move_index))

                    # If cell is a dead-end, append previous node with reversed
                    # orientation!
                    nbits = 0
                    tmp = rail.get_full_transitions(node[0][0], node[0][1])
                    while tmp > 0:
                        nbits += (tmp & 1)
                        tmp = tmp >> 1
                    if nbits == 1:
                        stack.append((node[0], (node[1] + 2) % 4))

            return 0

        valid_positions = []
        for r in range(rail.height):
            for c in range(rail.width):
                if rail.get_full_transitions(r, c) > 0:
                    valid_positions.append((r, c))
        if len(valid_positions) == 0:
            return [], [], [], []
        re_generate = True
        while re_generate:
            agents_position = [
                valid_positions[i] for i in
                np.random.choice(len(valid_positions), num_agents)]
            agents_target = [
                valid_positions[i] for i in
                np.random.choice(len(valid_positions), num_agents)]

            # agents_direction must be a direction for which a solution is
            # guaranteed.
            agents_direction = [0] * num_agents
            re_generate = False
            for i in range(num_agents):
                valid_movements = []
                for direction in range(4):
                    position = agents_position[i]
                    moves = rail.get_transitions(position[0], position[1], direction)
                    for move_index in range(4):
                        if moves[move_index]:
                            valid_movements.append((direction, move_index))

                valid_starting_directions = []
                for m in valid_movements:
                    new_position = get_new_position(agents_position[i], m[1])
                    if m[0] not in valid_starting_directions and _path_exists(rail, new_position, m[0],
                                                                              agents_target[i]):
                        valid_starting_directions.append(m[0])

                if len(valid_starting_directions) == 0:
                    re_generate = True
                else:
                    agents_direction[i] = valid_starting_directions[
                        np.random.choice(len(valid_starting_directions), 1)[0]]

        agents_speed = speed_initialization_helper(num_agents, speed_ratio_map)
        return agents_position, agents_direction, agents_target, agents_speed

    return generator


u214892's avatar
u214892 committed
210
def agents_from_file(filename) -> ScheduleGenerator:
u214892's avatar
u214892 committed
211
212
213
214
215
216
217
218
219
220
221
222
223
    """
    Utility to load pickle file

    Parameters
    -------
    input_file : Pickle file generated by env.save() or editor

    Returns
    -------
    Tuple[List[Tuple[int,int]], List[Tuple[int,int]], List[Tuple[int,int]], List[float]]
        initial positions, directions, targets speeds
    """

u214892's avatar
u214892 committed
224
    def generator(rail: GridTransitionMap, num_agents: int, hints: Any = None) -> ScheduleGeneratorProduct:
u214892's avatar
u214892 committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        with open(filename, "rb") as file_in:
            load_data = file_in.read()
        data = msgpack.unpackb(load_data, use_list=False)

        # agents are always reset as not moving
        agents_static = [EnvAgentStatic(d[0], d[1], d[2], moving=False) for d in data[b"agents_static"]]
        # setup with loaded data
        agents_position = [a.position for a in agents_static]
        agents_direction = [a.direction for a in agents_static]
        agents_target = [a.target for a in agents_static]

        return agents_position, agents_direction, agents_target, [1.0] * len(agents_position)

    return generator