rail_env.py 17.4 KB
Newer Older
1
2
3
4
5
6
"""
Definition of the RailEnv environment and related level-generation functions.

Generator functions are functions that take width, height and num_resets as arguments and return
a GridTransitionMap object.
"""
7

8
9
from enum import IntEnum

maljx's avatar
maljx committed
10
import msgpack
11
import numpy as np
12
13

from flatland.core.env import Environment
u214892's avatar
u214892 committed
14
from flatland.core.grid.grid4_utils import get_new_position
15
from flatland.envs.agent_utils import EnvAgentStatic, EnvAgent
16
17
18
from flatland.envs.generators import random_rail_generator
from flatland.envs.observations import TreeObsForRailEnv

19

spiglerg's avatar
spiglerg committed
20
class RailEnvActions(IntEnum):
21
    DO_NOTHING = 0  # implies change of direction in a dead-end!
spiglerg's avatar
spiglerg committed
22
23
24
25
26
    MOVE_LEFT = 1
    MOVE_FORWARD = 2
    MOVE_RIGHT = 3
    STOP_MOVING = 4

27
28
29
30
31
32
33
34
35
36
    @staticmethod
    def to_char(a: int):
        return {
            0: 'B',
            1: 'L',
            2: 'F',
            3: 'R',
            4: 'S',
        }[a]

u214892's avatar
u214892 committed
37

38
39
40
41
42
43
44
45
46
47
48
class RailEnv(Environment):
    """
    RailEnv environment class.

    RailEnv is an environment inspired by a (simplified version of) a rail
    network, in which agents (trains) have to navigate to their target
    locations in the shortest time possible, while at the same time cooperating
    to avoid bottlenecks.

    The valid actions in the environment are:
        0: do nothing
spiglerg's avatar
spiglerg committed
49
50
51
52
        1: turn left and move to the next cell; if the agent was not moving, movement is started
        2: move to the next cell in front of the agent; if the agent was not moving, movement is started
        3: turn right and move to the next cell; if the agent was not moving, movement is started
        4: stop moving
53
54
55
56
57
58
59
60
61
62
63
64
65
66

    Moving forward in a dead-end cell makes the agent turn 180 degrees and step
    to the cell it came from.

    The actions of the agents are executed in order of their handle to prevent
    deadlocks and to allow them to learn relative priorities.

    TODO: WRITE ABOUT THE REWARD FUNCTION, and possibly allow for alpha and
    beta to be passed as parameters to __init__().
    """

    def __init__(self,
                 width,
                 height,
spiglerg's avatar
spiglerg committed
67
                 rail_generator=random_rail_generator(),
68
                 number_of_agents=1,
u214892's avatar
u214892 committed
69
70
                 obs_builder_object=TreeObsForRailEnv(max_depth=2),
                 ):
71
72
73
74
75
76
        """
        Environment init.

        Parameters
        -------
        rail_generator : function
77
78
79
80
            The rail_generator function is a function that takes the width,
            height and agents handles of a  rail environment, along with the number of times
            the env has been reset, and returns a GridTransitionMap object and a list of
            starting positions, targets, and initial orientations for agent handle.
81
82
83
84
            Implemented functions are:
                random_rail_generator : generate a random rail of given size
                rail_from_GridTransitionMap_generator(rail_map) : generate a rail from
                                        a GridTransitionMap object
85
                rail_from_manual_sp ecifications_generator(rail_spec) : generate a rail from
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
                                        a rail specifications array
        width : int
            The width of the rail map. Potentially in the future,
            a range of widths to sample from.
        height : int
            The height of the rail map. Potentially in the future,
            a range of heights to sample from.
        number_of_agents : int
            Number of agents to spawn on the map. Potentially in the future,
            a range of number of agents to sample from.
        obs_builder_object: ObservationBuilder object
            ObservationBuilder-derived object that takes builds observation
            vectors for each agent.
        """

        self.rail_generator = rail_generator
        self.rail = None
        self.width = width
        self.height = height

        self.obs_builder = obs_builder_object
        self.obs_builder._set_env(self)

109
        self.action_space = [1]
u214892's avatar
u214892 committed
110
        self.observation_space = self.obs_builder.observation_space
111

112
        self.rewards = [0] * number_of_agents
113
114
        self.done = False

115
116
        self.dones = dict.fromkeys(list(range(number_of_agents)) + ["__all__"], False)

117
118
        self.obs_dict = {}
        self.rewards_dict = {}
Erik Nygren's avatar
Erik Nygren committed
119
        self.dev_obs_dict = {}
120

121
122
        self.agents = [None] * number_of_agents  # live agents
        self.agents_static = [None] * number_of_agents  # static agent information
123
124
        self.num_resets = 0
        self.reset()
125
        self.num_resets = 0  # yes, set it to zero again!
126

127
128
        self.valid_positions = None

129
    # no more agent_handles
130
    def get_agent_handles(self):
131
132
133
134
135
136
137
        return range(self.get_num_agents())

    def get_num_agents(self, static=True):
        if static:
            return len(self.agents_static)
        else:
            return len(self.agents)
138

hagrid67's avatar
hagrid67 committed
139
140
141
142
143
144
145
    def add_agent_static(self, agent_static):
        """ Add static info for a single agent.
            Returns the index of the new agent.
        """
        self.agents_static.append(agent_static)
        return len(self.agents_static) - 1

146
147
    def restart_agents(self):
        """ Reset the agents to their starting positions defined in agents_static
hagrid67's avatar
hagrid67 committed
148
        """
149
150
151
152
153
154
        self.agents = EnvAgent.list_from_static(self.agents_static)

    def reset(self, regen_rail=True, replace_agents=True):
        """ if regen_rail then regenerate the rails.
            if replace_agents then regenerate the agents static.
            Relies on the rail_generator returning agent_static lists (pos, dir, target)
hagrid67's avatar
hagrid67 committed
155
        """
156
        tRailAgents = self.rail_generator(self.width, self.height, self.get_num_agents(), self.num_resets)
hagrid67's avatar
hagrid67 committed
157

158
        if regen_rail or self.rail is None:
hagrid67's avatar
hagrid67 committed
159
            self.rail = tRailAgents[0]
160

hagrid67's avatar
hagrid67 committed
161
        if replace_agents:
spiglerg's avatar
spiglerg committed
162
            self.agents_static = EnvAgentStatic.from_lists(*tRailAgents[1:5])
hagrid67's avatar
hagrid67 committed
163

164
        self.restart_agents()
hagrid67's avatar
hagrid67 committed
165

Erik Nygren's avatar
Erik Nygren committed
166
167
168
169
        for iAgent in range(self.get_num_agents()):
            agent = self.agents[iAgent]
            agent.speed_data['position_fraction'] = 0.0

170
171
        self.num_resets += 1

u214892's avatar
u214892 committed
172
        # TODO perhaps dones should be part of each agent.
173
        self.dones = dict.fromkeys(list(range(self.get_num_agents())) + ["__all__"], False)
174

175
176
        # Reset the state of the observation builder with the new environment
        self.obs_builder.reset()
spiglerg's avatar
spiglerg committed
177
        self.observation_space = self.obs_builder.observation_space  # <-- change on reset?
178
179
180
181

        # Return the new observation vectors for each agent
        return self._get_observations()

spiglerg's avatar
spiglerg committed
182
183
184
    def step(self, action_dict_):
        action_dict = action_dict_.copy()

185
186
187
        alpha = 1.0
        beta = 1.0

188
        invalid_action_penalty = 0  # previously -2; GIACOMO: we decided that invalid actions will carry no penalty
189
190
        step_penalty = -1 * alpha
        global_reward = 1 * beta
191
192
        stop_penalty = 0  # penalty for stopping a moving agent
        start_penalty = 0  # penalty for starting a stopped agent
193
194

        # Reset the step rewards
195
        self.rewards_dict = dict()
u214892's avatar
u214892 committed
196
197
        for i_agent in range(self.get_num_agents()):
            self.rewards_dict[i_agent] = 0
198
199

        if self.dones["__all__"]:
spmohanty's avatar
spmohanty committed
200
            self.rewards_dict = {i: r + global_reward for i, r in self.rewards_dict.items()}
201
202
            return self._get_observations(), self.rewards_dict, self.dones, {}

u214892's avatar
u214892 committed
203
        for i_agent, agent in enumerate(self.agents):
204
205
            agent.old_direction = agent.direction
            agent.old_position = agent.position
u214892's avatar
u214892 committed
206
            if self.dones[i_agent]:  # this agent has already completed...
207
                continue
208

u214892's avatar
u214892 committed
209
210
            if i_agent not in action_dict:  # no action has been supplied for this agent
                action_dict[i_agent] = RailEnvActions.DO_NOTHING
211

u214892's avatar
u214892 committed
212
213
214
            if action_dict[i_agent] < 0 or action_dict[i_agent] > len(RailEnvActions):
                print('ERROR: illegal action=', action_dict[i_agent],
                      'for agent with index=', i_agent,
215
                      '"DO NOTHING" will be executed instead')
u214892's avatar
u214892 committed
216
                action_dict[i_agent] = RailEnvActions.DO_NOTHING
217

u214892's avatar
u214892 committed
218
            action = action_dict[i_agent]
219

spiglerg's avatar
spiglerg committed
220
221
222
223
            if action == RailEnvActions.DO_NOTHING and agent.moving:
                # Keep moving
                action = RailEnvActions.MOVE_FORWARD

Erik Nygren's avatar
Erik Nygren committed
224
            if action == RailEnvActions.STOP_MOVING and agent.moving and agent.speed_data['position_fraction'] == 0.:
225
                # Only allow halting an agent on entering new cells.
spiglerg's avatar
spiglerg committed
226
                agent.moving = False
u214892's avatar
u214892 committed
227
                self.rewards_dict[i_agent] += stop_penalty
228

229
            if not agent.moving and not (action == RailEnvActions.DO_NOTHING or action == RailEnvActions.STOP_MOVING):
230
                # Only allow agent to start moving by pressing forward.
spiglerg's avatar
spiglerg committed
231
                agent.moving = True
u214892's avatar
u214892 committed
232
                self.rewards_dict[i_agent] += start_penalty
spiglerg's avatar
spiglerg committed
233

234
235
236
237
238
239
240
241
242
243
244
245
            # Now perform a movement.
            # If the agent is in an initial position within a new cell (agent.speed_data['position_fraction']<eps)
            #   store the desired action in `transition_action_on_cellexit' (only if the desired transition is
            #   allowed! otherwise DO_NOTHING!)
            # Then in any case (if agent.moving) and the `transition_action_on_cellexit' is valid, increment the
            #   position_fraction by the speed of the agent   (regardless of action taken, as long as no
            #   STOP_MOVING, but that makes agent.moving=False)
            # If the new position fraction is >= 1, reset to 0, and perform the stored
            #   transition_action_on_cellexit

            # If the agent can make an action
            action_selected = False
Erik Nygren's avatar
Erik Nygren committed
246
            if agent.speed_data['position_fraction'] == 0.:
247
248
249
250
                if action != RailEnvActions.DO_NOTHING and action != RailEnvActions.STOP_MOVING:
                    cell_isFree, new_cell_isValid, new_direction, new_position, transition_isValid = \
                        self._check_action_on_agent(action, agent)

Erik Nygren's avatar
Erik Nygren committed
251
                    if all([new_cell_isValid, transition_isValid]):
252
253
254
255
256
257
258
259
260
261
                        agent.speed_data['transition_action_on_cellexit'] = action
                        action_selected = True

                    else:
                        # But, if the chosen invalid action was LEFT/RIGHT, and the agent is moving,
                        # try to keep moving forward!
                        if (action == RailEnvActions.MOVE_LEFT or action == RailEnvActions.MOVE_RIGHT) and agent.moving:
                            cell_isFree, new_cell_isValid, new_direction, new_position, transition_isValid = \
                                self._check_action_on_agent(RailEnvActions.MOVE_FORWARD, agent)

Erik Nygren's avatar
Erik Nygren committed
262
                            if all([new_cell_isValid, transition_isValid]):
263
264
265
266
267
                                agent.speed_data['transition_action_on_cellexit'] = RailEnvActions.MOVE_FORWARD
                                action_selected = True

                            else:
                                # TODO: an invalid action was chosen after entering the cell. The agent cannot move.
u214892's avatar
u214892 committed
268
                                self.rewards_dict[i_agent] += invalid_action_penalty
269
                                agent.moving = False
u214892's avatar
u214892 committed
270
                                self.rewards_dict[i_agent] += stop_penalty
Erik Nygren's avatar
Erik Nygren committed
271

272
                                continue
273
                        else:
274
                            # TODO: an invalid action was chosen after entering the cell. The agent cannot move.
u214892's avatar
u214892 committed
275
                            self.rewards_dict[i_agent] += invalid_action_penalty
276
                            agent.moving = False
u214892's avatar
u214892 committed
277
                            self.rewards_dict[i_agent] += stop_penalty
Erik Nygren's avatar
Erik Nygren committed
278

279
                            continue
280

Erik Nygren's avatar
Erik Nygren committed
281
            if agent.moving and (action_selected or agent.speed_data['position_fraction'] > 0.0):
282
                agent.speed_data['position_fraction'] += agent.speed_data['speed']
283

284
            if agent.speed_data['position_fraction'] >= 1.0:
285

286
287
288
289
290
291
                # Perform stored action to transition to the next cell

                # Now 'transition_action_on_cellexit' will be guaranteed to be valid; it was checked on entering
                # the cell
                cell_isFree, new_cell_isValid, new_direction, new_position, transition_isValid = \
                    self._check_action_on_agent(agent.speed_data['transition_action_on_cellexit'], agent)
292
293
294
295
296
297

                if all([new_cell_isValid, transition_isValid, cell_isFree]):
                    agent.position = new_position
                    agent.direction = new_direction
                    agent.speed_data['position_fraction'] = 0.0

spiglerg's avatar
spiglerg committed
298
            if np.equal(agent.position, agent.target).all():
u214892's avatar
u214892 committed
299
                self.dones[i_agent] = True
spiglerg's avatar
spiglerg committed
300
            else:
u214892's avatar
u214892 committed
301
                self.rewards_dict[i_agent] += step_penalty * agent.speed_data['speed']
spiglerg's avatar
spiglerg committed
302

303
        # Check for end of episode + add global reward to all rewards!
304
        if np.all([np.array_equal(agent2.position, agent2.target) for agent2 in self.agents]):
305
            self.dones["__all__"] = True
spmohanty's avatar
spmohanty committed
306
            self.rewards_dict = {i: 0 * r + global_reward for i, r in self.rewards_dict.items()}
307
308
309

        return self._get_observations(), self.rewards_dict, self.dones, {}

u214892's avatar
u214892 committed
310
311
312
313
314
    def _check_action_on_agent(self, action, agent):
        # compute number of possible transitions in the current
        # cell used to check for invalid actions
        new_direction, transition_isValid = self.check_action(agent, action)
        new_position = get_new_position(agent.position, new_direction)
315

u214892's avatar
u214892 committed
316
        # Is it a legal move?
spiglerg's avatar
spiglerg committed
317
318
319
320
321
322
323
324
        # 1) transition allows the new_direction in the cell,
        # 2) the new cell is not empty (case 0),
        # 3) the cell is free, i.e., no agent is currently in that cell
        new_cell_isValid = (
            np.array_equal(  # Check the new position is still in the grid
                new_position,
                np.clip(new_position, [0, 0], [self.height - 1, self.width - 1]))
            and  # check the new position has some transitions (ie is not an empty cell)
u214892's avatar
u214892 committed
325
            self.rail.get_full_transitions(*new_position) > 0)
326

spiglerg's avatar
spiglerg committed
327
328
329
330
331
        # If transition validity hasn't been checked yet.
        if transition_isValid is None:
            transition_isValid = self.rail.get_transition(
                (*agent.position, agent.direction),
                new_direction)
332

spiglerg's avatar
spiglerg committed
333
334
335
336
337
338
        # Check the new position is not the same as any of the existing agent positions
        # (including itself, for simplicity, since it is moving)
        cell_isFree = not np.any(
            np.equal(new_position, [agent2.position for agent2 in self.agents]).all(1))
        return cell_isFree, new_cell_isValid, new_direction, new_position, transition_isValid

hagrid67's avatar
hagrid67 committed
339
340
    def check_action(self, agent, action):
        transition_isValid = None
u214892's avatar
u214892 committed
341
        possible_transitions = self.rail.get_transitions(*agent.position, agent.direction)
hagrid67's avatar
hagrid67 committed
342
343
344
        num_transitions = np.count_nonzero(possible_transitions)

        new_direction = agent.direction
spiglerg's avatar
spiglerg committed
345
        if action == RailEnvActions.MOVE_LEFT:
hagrid67's avatar
hagrid67 committed
346
347
348
349
            new_direction = agent.direction - 1
            if num_transitions <= 1:
                transition_isValid = False

spiglerg's avatar
spiglerg committed
350
        elif action == RailEnvActions.MOVE_RIGHT:
hagrid67's avatar
hagrid67 committed
351
352
353
354
355
356
            new_direction = agent.direction + 1
            if num_transitions <= 1:
                transition_isValid = False

        new_direction %= 4

spiglerg's avatar
spiglerg committed
357
        if action == RailEnvActions.MOVE_FORWARD:
hagrid67's avatar
hagrid67 committed
358
359
360
361
362
363
364
365
            if num_transitions == 1:
                # - dead-end, straight line or curved line;
                # new_direction will be the only valid transition
                # - take only available transition
                new_direction = np.argmax(possible_transitions)
                transition_isValid = True
        return new_direction, transition_isValid

366
    def _get_observations(self):
367
        self.obs_dict = self.obs_builder.get_many(list(range(self.get_num_agents())))
368
        return self.obs_dict
369

maljx's avatar
maljx committed
370
371
372
373
    def get_full_state_msg(self):
        grid_data = self.rail.grid.tolist()
        agent_static_data = [agent.to_list() for agent in self.agents_static]
        agent_data = [agent.to_list() for agent in self.agents]
374
375
376
377
378

        msgpack.packb(grid_data)
        msgpack.packb(agent_data)
        msgpack.packb(agent_static_data)

maljx's avatar
maljx committed
379
380
381
        msg_data = {
            "grid": grid_data,
            "agents_static": agent_static_data,
382
            "agents": agent_data}
maljx's avatar
maljx committed
383
384
385
386
387
        return msgpack.packb(msg_data, use_bin_type=True)

    def get_agent_state_msg(self):
        agent_data = [agent.to_list() for agent in self.agents]
        msg_data = {
388
            "agents": agent_data}
maljx's avatar
maljx committed
389
390
391
392
393
        return msgpack.packb(msg_data, use_bin_type=True)

    def set_full_state_msg(self, msg_data):
        data = msgpack.unpackb(msg_data, use_list=False)
        self.rail.grid = np.array(data[b"grid"])
spiglerg's avatar
fix?    
spiglerg committed
394
395
        # agents are always reset as not moving
        self.agents_static = [EnvAgentStatic(d[0], d[1], d[2], moving=False) for d in data[b"agents_static"]]
maljx's avatar
maljx committed
396
397
398
        self.agents = [EnvAgent(d[0], d[1], d[2], d[3], d[4]) for d in data[b"agents"]]
        # setup with loaded data
        self.height, self.width = self.rail.grid.shape
399
400
        self.rail.height = self.height
        self.rail.width = self.width
maljx's avatar
maljx committed
401
402
403
404
405
406
407
408
409
410
        self.dones = dict.fromkeys(list(range(self.get_num_agents())) + ["__all__"], False)

    def save(self, filename):
        with open(filename, "wb") as file_out:
            file_out.write(self.get_full_state_msg())

    def load(self, filename):
        with open(filename, "rb") as file_in:
            load_data = file_in.read()
            self.set_full_state_msg(load_data)
u214892's avatar
u214892 committed
411
412
413
414
415

    def load_resource(self, package, resource):
        from importlib_resources import read_binary
        load_data = read_binary(package, resource)
        self.set_full_state_msg(load_data)