grid4.py 8.25 KB
Newer Older
u214892's avatar
u214892 committed
1
from enum import IntEnum
u214892's avatar
u214892 committed
2
from typing import Type
u214892's avatar
u214892 committed
3
4
5
6
7
8
9
10
11
12
13
14

import numpy as np

from flatland.core.transitions import Transitions


class Grid4TransitionsEnum(IntEnum):
    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

15
16
17
18
19
20
21
    @staticmethod
    def to_char(int: int):
        return {0: 'N',
                1: 'E',
                2: 'S',
                3: 'W'}[int]

u214892's avatar
u214892 committed
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

class Grid4Transitions(Transitions):
    """
    Grid4Transitions class derived from Transitions.

    Special case of `Transitions' over a 2D-grid (FlatLand).
    Transitions are possible to neighboring cells on the grid if allowed.
    GridTransitions keeps track of valid transitions supplied as `transitions'
    list, each represented as a bitmap of 16 bits.

    Whether a transition is allowed or not depends on which direction an agent
    inside the cell is facing (0=North, 1=East, 2=South, 3=West) and which
    direction the agent wants to move to
    (North, East, South, West, relative to the cell).
    Each transition (orientation, direction)
    can be allowed (1) or forbidden (0).

    For example, in case of no diagonal transitions on the grid, the 16 bits
    of the transition bitmaps are organized in 4 blocks of 4 bits each, the
    direction that the agent is facing.
    E.g., the most-significant 4-bits represent the possible movements (NESW)
    if the agent is facing North, etc...

    agent's direction:          North    East   South   West
    agent's allowed movements:  [nesw]   [nesw] [nesw]  [nesw]
    example:                     1000     0000   0010    0000

    In the example, the agent can move from North to South and viceversa.
    """

    def __init__(self, transitions):
        self.transitions = transitions
        self.sDirs = "NESW"
        self.lsDirs = list(self.sDirs)

        # row,col delta for each direction
        self.gDir2dRC = np.array([[-1, 0], [0, 1], [1, 0], [0, -1]])

u214892's avatar
u214892 committed
60
61
62
        # These bits represent all the possible dead ends
        self.maskDeadEnds = 0b0010000110000100

u214892's avatar
u214892 committed
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
    def get_type(self):
        return np.uint16

    def get_transitions(self, cell_transition, orientation):
        """
        Get the 4 possible transitions ((N,E,S,W), 4 elements tuple
        if no diagonal transitions allowed) available for an agent oriented
        in direction `orientation' and inside a cell with
        transitions `cell_transition'.

        Parameters
        ----------
        cell_transition : int
            16 bits used to encode the valid transitions for a cell.
        orientation : int
            Orientation of the agent inside the cell.

        Returns
        -------
        tuple
            List of the validity of transitions in the cell.

        """
        bits = (cell_transition >> ((3 - orientation) * 4))
        return ((bits >> 3) & 1, (bits >> 2) & 1, (bits >> 1) & 1, (bits) & 1)

    def set_transitions(self, cell_transition, orientation, new_transitions):
        """
        Set the possible transitions (e.g., (N,E,S,W), 4 elements tuple
        if no diagonal transitions allowed) available for an agent
        oriented in direction `orientation' and inside a cell with transitions
        `cell_transition'. A new `cell_transition' is returned with
        the specified bits replaced by `new_transitions'.

        Parameters
        ----------
        cell_transition : int
            16 bits used to encode the valid transitions for a cell.
        orientation : int
            Orientation of the agent inside the cell.
        new_transitions : tuple
            Tuple of new transitions validitiy for the cell.

        Returns
        -------
        int
            An updated bitmap that replaces the original transitions validity
            of `cell_transition' with `new_transitions', for the appropriate
            `orientation'.

        """
        mask = (1 << ((4 - orientation) * 4)) - (1 << ((3 - orientation) * 4))
        negmask = ~mask

        new_transitions = \
            (new_transitions[0] & 1) << 3 | \
            (new_transitions[1] & 1) << 2 | \
            (new_transitions[2] & 1) << 1 | \
            (new_transitions[3] & 1)

        cell_transition = (cell_transition & negmask) | (new_transitions << ((3 - orientation) * 4))

        return cell_transition

    def get_transition(self, cell_transition, orientation, direction):
        """
        Get the transition bit (1 value) that determines whether an agent
        oriented in direction `orientation' and inside a cell with transitions
        `cell_transition' can move to the cell in direction `direction'
        relative to the current cell.

        Parameters
        ----------
        cell_transition : int
            16 bits used to encode the valid transitions for a cell.
        orientation : int
            Orientation of the agent inside the cell.
        direction : int
            Direction of movement whose validity is to be tested.

        Returns
        -------
        int
            Validity of the requested transition: 0/1 allowed/not allowed.

        """
        return ((cell_transition >> ((4 - 1 - orientation) * 4)) >> (4 - 1 - direction)) & 1

    def set_transition(self, cell_transition, orientation, direction, new_transition, remove_deadends=False):
        """
        Set the transition bit (1 value) that determines whether an agent
        oriented in direction `orientation' and inside a cell with transitions
        `cell_transition' can move to the cell in direction `direction'
        relative to the current cell.

        Parameters
        ----------
        cell_transition : int
            16 bits used to encode the valid transitions for a cell.
        orientation : int
            Orientation of the agent inside the cell.
        direction : int
            Direction of movement whose validity is to be tested.
        new_transition : int
            Validity of the requested transition: 0/1 allowed/not allowed.
        remove_deadends -- boolean, default False
            remove all deadend transitions.
        Returns
        -------
        int
            An updated bitmap that replaces the original transitions validity
            of `cell_transition' with `new_transitions', for the appropriate
            `orientation'.

        """
        if new_transition:
            cell_transition |= (1 << ((4 - 1 - orientation) * 4 + (4 - 1 - direction)))
        else:
            cell_transition &= ~(1 << ((4 - 1 - orientation) * 4 + (4 - 1 - direction)))

        if remove_deadends:
            cell_transition = self.remove_deadends(cell_transition)

        return cell_transition

    def rotate_transition(self, cell_transition, rotation=0):
        """
        Clockwise-rotate a 16-bit transition bitmap by
        rotation={0, 90, 180, 270} degrees.

        Parameters
        ----------
        cell_transition : int
            16 bits used to encode the valid transitions for a cell.
        rotation : int
            Angle by which to clock-wise rotate the transition bits in
            `cell_transition' by. I.e., rotation={0, 90, 180, 270} degrees.

        Returns
        -------
        int
            An updated bitmap that replaces the original transitions bits
            with the equivalent bitmap after rotation.

        """
        # Rotate the individual bits in each block
        value = cell_transition
        rotation = rotation // 90
        for i in range(4):
            block_tuple = self.get_transitions(value, i)
            block_tuple = block_tuple[(4 - rotation):] + block_tuple[:(4 - rotation)]
            value = self.set_transitions(value, i, block_tuple)

        # Rotate the 4-bits blocks
        value = ((value & (2 ** (rotation * 4) - 1)) << ((4 - rotation) * 4)) | (value >> (rotation * 4))

        cell_transition = value
        return cell_transition

u214892's avatar
u214892 committed
222
    def get_direction_enum(self) -> Type[Grid4TransitionsEnum]:
u214892's avatar
u214892 committed
223
        return Grid4TransitionsEnum
u214892's avatar
u214892 committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

    def has_deadend(self, cell_transition):
        """
        Checks if one entry can only by exited by a turn-around.
        """
        if cell_transition & self.maskDeadEnds > 0:
            return True
        else:
            return False

    def remove_deadends(self, cell_transition):
        """
        Remove all turn-arounds (e.g. N-S, S-N, E-W,...).
        """
        cell_transition &= cell_transition & (~self.maskDeadEnds) & 0xffff
        return cell_transition