predictions.py 6.96 KB
Newer Older
u214892's avatar
u214892 committed
1
2
3
4
"""
Collection of environment-specific PredictionBuilder.
"""

u214892's avatar
u214892 committed
5
6
import numpy as np

u214892's avatar
u214892 committed
7
from flatland.core.env_prediction_builder import PredictionBuilder
u214892's avatar
u214892 committed
8
from flatland.core.grid.grid4_utils import get_new_position
u214892's avatar
u214892 committed
9
from flatland.envs.rail_env import RailEnvActions
u214892's avatar
u214892 committed
10
11
12
13
14
15
16
17
18
19


class DummyPredictorForRailEnv(PredictionBuilder):
    """
    DummyPredictorForRailEnv object.

    This object returns predictions for agents in the RailEnv environment.
    The prediction acts as if no other agent is in the environment and always takes the forward action.
    """

20
    def get(self, custom_args=None, handle=None):
u214892's avatar
u214892 committed
21
        """
22
        Called whenever get_many in the observation build is called.
u214892's avatar
u214892 committed
23
24
25

        Parameters
        -------
26
27
        custom_args: dict
            Not used in this dummy implementation.
u214892's avatar
u214892 committed
28
29
30
31
32
        handle : int (optional)
            Handle of the agent for which to compute the observation vector.

        Returns
        -------
33
        np.array
34
            Returns a dictionary indexed by the agent handle and for each agent a vector of (max_depth + 1)x5 elements:
u214892's avatar
u214892 committed
35
36
37
38
39
            - time_offset
            - position axis 0
            - position axis 1
            - direction
            - action taken to come here
40
41
            The prediction at 0 is the current position, direction etc.

u214892's avatar
u214892 committed
42
43
44
45
46
47
        """
        agents = self.env.agents
        if handle:
            agents = [self.env.agents[handle]]

        prediction_dict = {}
u214892's avatar
u214892 committed
48

u214892's avatar
u214892 committed
49
        for agent in agents:
50
            action_priorities = [RailEnvActions.MOVE_FORWARD, RailEnvActions.MOVE_LEFT, RailEnvActions.MOVE_RIGHT]
u214892's avatar
u214892 committed
51
52
            _agent_initial_position = agent.position
            _agent_initial_direction = agent.direction
53
            prediction = np.zeros(shape=(self.max_depth + 1, 5))
54
            prediction[0] = [0, *_agent_initial_position, _agent_initial_direction, 0]
55
            for index in range(1, self.max_depth + 1):
u214892's avatar
u214892 committed
56
                action_done = False
57
58
                # if we're at the target, stop moving...
                if agent.position == agent.target:
59
                    prediction[index] = [index, *agent.target, agent.direction, RailEnvActions.STOP_MOVING]
60
61

                    continue
u214892's avatar
u214892 committed
62
                for action in action_priorities:
u214892's avatar
u214892 committed
63
64
                    cell_isFree, new_cell_isValid, new_direction, new_position, transition_isValid = \
                        self.env._check_action_on_agent(action, agent)
u214892's avatar
u214892 committed
65
66
67
68
69
                    if all([new_cell_isValid, transition_isValid]):
                        # move and change direction to face the new_direction that was
                        # performed
                        agent.position = new_position
                        agent.direction = new_direction
70
                        prediction[index] = [index, *new_position, new_direction, action]
u214892's avatar
u214892 committed
71
72
73
                        action_done = True
                        break
                if not action_done:
74
                    raise Exception("Cannot move further. Something is wrong")
u214892's avatar
u214892 committed
75
76
77
78
            prediction_dict[agent.handle] = prediction
            agent.position = _agent_initial_position
            agent.direction = _agent_initial_direction
        return prediction_dict
79
80
81
82


class ShortestPathPredictorForRailEnv(PredictionBuilder):
    """
83
    ShortestPathPredictorForRailEnv object.
84

85
    This object returns shortest-path predictions for agents in the RailEnv environment.
86
87
88
    The prediction acts as if no other agent is in the environment and always takes the forward action.
    """

89
    def get(self, custom_args=None, handle=None):
90
        """
91
92
        Called whenever get_many in the observation build is called.
        Requires distance_map to extract the shortest path.
93
94
95

        Parameters
        -------
96
97
        custom_args: dict
            - distance_map : dict
98
99
100
101
102
        handle : int (optional)
            Handle of the agent for which to compute the observation vector.

        Returns
        -------
103
        np.array
104
            Returns a dictionary indexed by the agent handle and for each agent a vector of (max_depth + 1)x5 elements:
105
106
107
108
109
            - time_offset
            - position axis 0
            - position axis 1
            - direction
            - action taken to come here
110
            The prediction at 0 is the current position, direction etc.
111
112
113
114
        """
        agents = self.env.agents
        if handle:
            agents = [self.env.agents[handle]]
115
        assert custom_args is not None
116
117
        distance_map = custom_args.get('distance_map')
        assert distance_map is not None
118
119
120
121
122
123

        prediction_dict = {}
        for agent in agents:
            _agent_initial_position = agent.position
            _agent_initial_direction = agent.direction
            prediction = np.zeros(shape=(self.max_depth + 1, 5))
124
            prediction[0] = [0, *_agent_initial_position, _agent_initial_direction, 0]
125
126
127
            for index in range(1, self.max_depth + 1):
                # if we're at the target, stop moving...
                if agent.position == agent.target:
128
                    prediction[index] = [index, *agent.target, agent.direction, RailEnvActions.STOP_MOVING]
129
130
                    continue
                if not agent.moving:
131
                    prediction[index] = [index, *agent.position, agent.direction, RailEnvActions.STOP_MOVING]
132
133
                    continue
                # Take shortest possible path
u214892's avatar
u214892 committed
134
                cell_transitions = self.env.rail.get_transitions(*agent.position, agent.direction)
135

136
137
                new_position = None
                new_direction = None
138
139
                if np.sum(cell_transitions) == 1:
                    new_direction = np.argmax(cell_transitions)
140
                    new_position = get_new_position(agent.position, new_direction)
141
142
                elif np.sum(cell_transitions) > 1:
                    min_dist = np.inf
143
                    no_dist_found = True
144
145
                    for direction in range(4):
                        if cell_transitions[direction] == 1:
146
147
                            neighbour_cell = get_new_position(agent.position, direction)
                            target_dist = distance_map[agent.handle, neighbour_cell[0], neighbour_cell[1], direction]
148
                            if target_dist < min_dist or no_dist_found:
149
                                min_dist = target_dist
150
                                new_direction = direction
151
                                no_dist_found = False
152
153
154
155
                    new_position = get_new_position(agent.position, new_direction)
                else:
                    raise Exception("No transition possible {}".format(cell_transitions))

156
                # update the agent's position and direction
157
158
                agent.position = new_position
                agent.direction = new_direction
159
160

                # prediction is ready
161
                prediction[index] = [index, *new_position, new_direction, 0]
162
            prediction_dict[agent.handle] = prediction
163
164

            # cleanup: reset initial position
165
166
167
168
            agent.position = _agent_initial_position
            agent.direction = _agent_initial_direction

        return prediction_dict