transition_map.py 25.4 KB
Newer Older
1 2 3 4 5
"""
TransitionMap and derived classes.
"""

import numpy as np
6
from importlib_resources import path
7
from numpy import array
8

u214892's avatar
u214892 committed
9
from flatland.core.grid.grid4 import Grid4Transitions
10
from flatland.core.grid.grid4_utils import get_new_position, get_direction
11
from flatland.core.grid.grid_utils import IntVector2DArray, IntVector2D
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
12
from flatland.core.grid.grid_utils import Vec2dOperations as Vec2d
13
from flatland.core.grid.rail_env_grid import RailEnvTransitions
u214892's avatar
u214892 committed
14
from flatland.core.transitions import Transitions
u214892's avatar
u214892 committed
15
from flatland.utils.ordered_set import OrderedSet
16

17

u214892's avatar
u214892 committed
18
# TODO are these general classes or for grid4 only?
19 20 21 22 23 24 25 26 27 28 29
class TransitionMap:
    """
    Base TransitionMap class.

    Generic class that implements a collection of transitions over a set of
    cells.
    """

    def get_transitions(self, cell_id):
        """
        Return a tuple of transitions available in a cell specified by
u214892's avatar
u214892 committed
30
        `cell_id` (e.g., a tuple of size of the maximum number of transitions,
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
        with values 0 or 1, or potentially in between,
        for stochastic transitions).

        Parameters
        ----------
        cell_id : [cell identifier]
            The cell_id object depends on the specific implementation.
            It generally is an int (e.g., an index) or a tuple of indices.

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

        """
        raise NotImplementedError()

    def set_transitions(self, cell_id, new_transitions):
        """
u214892's avatar
u214892 committed
50 51
        Replaces the available transitions in cell `cell_id` with the tuple
        `new_transitions'. `new_transitions` must have
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        one element for each possible transition.

        Parameters
        ----------
        cell_id : [cell identifier]
            The cell_id object depends on the specific implementation.
            It generally is an int (e.g., an index) or a tuple of indices.
        new_transitions : tuple
            Tuple of new transitions validitiy for the cell.

        """
        raise NotImplementedError()

    def get_transition(self, cell_id, transition_index):
        """
u214892's avatar
u214892 committed
67
        Return the status of whether an agent in cell `cell_id` can perform a
u214892's avatar
u214892 committed
68
        movement along transition `transition_index` (e.g., the NESW direction
69 70 71 72 73 74 75 76 77 78 79 80 81 82
        of movement, for agents on a grid).

        Parameters
        ----------
        cell_id : [cell identifier]
            The cell_id object depends on the specific implementation.
            It generally is an int (e.g., an index) or a tuple of indices.
        transition_index : int
            Index of the transition to probe, as index in the tuple returned by
            get_transitions(). e.g., the NESW direction of movement, for agents
            on a grid.

        Returns
        -------
u214892's avatar
u214892 committed
83
        int or float (depending on Transitions used)
84 85 86 87 88 89 90 91
            Validity of the requested transition (e.g.,
            0/1 allowed/not allowed, a probability in [0,1], etc...)

        """
        raise NotImplementedError()

    def set_transition(self, cell_id, transition_index, new_transition):
        """
u214892's avatar
u214892 committed
92 93
        Replaces the validity of transition to `transition_index` in cell
        `cell_id' with the new `new_transition`.
94 95 96 97 98 99 100 101 102 103 104


        Parameters
        ----------
        cell_id : [cell identifier]
            The cell_id object depends on the specific implementation.
            It generally is an int (e.g., an index) or a tuple of indices.
        transition_index : int
            Index of the transition to probe, as index in the tuple returned by
            get_transitions(). e.g., the NESW direction of movement, for agents
            on a grid.
u214892's avatar
u214892 committed
105
        new_transition : int or float (depending on Transitions used)
106 107 108 109 110 111 112 113 114 115 116 117 118 119
            Validity of the requested transition (e.g.,
            0/1 allowed/not allowed, a probability in [0,1], etc...)

        """
        raise NotImplementedError()


class GridTransitionMap(TransitionMap):
    """
    Implements a TransitionMap over a 2D grid.

    GridTransitionMap implements utility functions.
    """

120
    def __init__(self, width, height, transitions: Transitions = Grid4Transitions([]), random_seed=None):
121 122 123 124 125 126 127 128 129
        """
        Builder for GridTransitionMap object.

        Parameters
        ----------
        width : int
            Width of the grid.
        height : int
            Height of the grid.
130
        transitions : Transitions object
131 132 133 134 135 136 137 138
            The Transitions object to use to encode/decode transitions over the
            grid.

        """

        self.width = width
        self.height = height
        self.transitions = transitions
139 140 141 142 143
        self.random_generator = np.random.RandomState()
        if random_seed is None:
            self.random_generator.seed(12)
        else:
            self.random_generator.seed(random_seed)
u214892's avatar
u214892 committed
144
        self.grid = np.zeros((height, width), dtype=self.transitions.get_type())
145

u214892's avatar
u214892 committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    def get_full_transitions(self, row, column):
        """
        Returns the full transitions for the cell at (row, column) in the format transition_map's transitions.

        Parameters
        ----------
        row: int
        column: int
            (row,column) specifies the cell in this transition map.

        Returns
        -------
        self.transitions.get_type()
            The cell content int the format of this map's Transitions.

        """
        return self.grid[row][column]

    def get_transitions(self, row, column, orientation):
165 166
        """
        Return a tuple of transitions available in a cell specified by
u214892's avatar
u214892 committed
167
        `cell_id` (e.g., a tuple of size of the maximum number of transitions,
168 169 170 171 172 173 174 175 176 177 178 179 180 181
        with values 0 or 1, or potentially in between,
        for stochastic transitions).

        Parameters
        ----------
        cell_id : tuple
            The cell_id indices a cell as (column, row, orientation),
            where orientation is the direction an agent is facing within a cell.
            Alternatively, it can be accessed as (column, row) to return the
            full cell content.

        Returns
        -------
        tuple
u214892's avatar
u214892 committed
182
            List of the validity of transitions in the cell as given by the maps transitions.
183 184

        """
u214892's avatar
u214892 committed
185
        return self.transitions.get_transitions(self.grid[row][column], orientation)
186 187 188

    def set_transitions(self, cell_id, new_transitions):
        """
u214892's avatar
u214892 committed
189 190
        Replaces the available transitions in cell `cell_id` with the tuple
        `new_transitions'. `new_transitions` must have
191 192 193 194 195 196 197 198 199 200 201 202 203
        one element for each possible transition.

        Parameters
        ----------
        cell_id : tuple
            The cell_id indices a cell as (column, row, orientation),
            where orientation is the direction an agent is facing within a cell.
            Alternatively, it can be accessed as (column, row) to replace the
            full cell content.
        new_transitions : tuple
            Tuple of new transitions validitiy for the cell.

        """
u214892's avatar
u214892 committed
204 205
        assert len(cell_id) in (2, 3), \
            'GridTransitionMap.set_transitions() ERROR: cell_id tuple must have length 2 or 3.'
206
        if len(cell_id) == 3:
spiglerg's avatar
spiglerg committed
207 208 209
            self.grid[cell_id[0]][cell_id[1]] = self.transitions.set_transitions(self.grid[cell_id[0]][cell_id[1]],
                                                                                 cell_id[2],
                                                                                 new_transitions)
210 211 212 213 214
        elif len(cell_id) == 2:
            self.grid[cell_id[0]][cell_id[1]] = new_transitions

    def get_transition(self, cell_id, transition_index):
        """
u214892's avatar
u214892 committed
215
        Return the status of whether an agent in cell `cell_id` can perform a
u214892's avatar
u214892 committed
216
        movement along transition `transition_index` (e.g., the NESW direction
217 218 219 220 221 222 223 224 225 226 227 228 229 230
        of movement, for agents on a grid).

        Parameters
        ----------
        cell_id : tuple
            The cell_id indices a cell as (column, row, orientation),
            where orientation is the direction an agent is facing within a cell.
        transition_index : int
            Index of the transition to probe, as index in the tuple returned by
            get_transitions(). e.g., the NESW direction of movement, for agents
            on a grid.

        Returns
        -------
u214892's avatar
u214892 committed
231
        int or float (depending on Transitions used in the )
232 233 234 235
            Validity of the requested transition (e.g.,
            0/1 allowed/not allowed, a probability in [0,1], etc...)

        """
u214892's avatar
u214892 committed
236 237 238

        assert len(cell_id) == 3, \
            'GridTransitionMap.get_transition() ERROR: cell_id tuple must have length 2 or 3.'
239 240
        return self.transitions.get_transition(self.grid[cell_id[0]][cell_id[1]], cell_id[2], transition_index)

241
    def set_transition(self, cell_id, transition_index, new_transition, remove_deadends=False):
242
        """
u214892's avatar
u214892 committed
243 244
        Replaces the validity of transition to `transition_index` in cell
        `cell_id' with the new `new_transition`.
245 246 247 248 249 250 251 252 253 254 255


        Parameters
        ----------
        cell_id : tuple
            The cell_id indices a cell as (column, row, orientation),
            where orientation is the direction an agent is facing within a cell.
        transition_index : int
            Index of the transition to probe, as index in the tuple returned by
            get_transitions(). e.g., the NESW direction of movement, for agents
            on a grid.
u214892's avatar
u214892 committed
256
        new_transition : int or float (depending on Transitions used in the map.)
257 258 259 260
            Validity of the requested transition (e.g.,
            0/1 allowed/not allowed, a probability in [0,1], etc...)

        """
u214892's avatar
u214892 committed
261 262
        assert len(cell_id) == 3, \
            'GridTransitionMap.set_transition() ERROR: cell_id tuple must have length 3.'
263 264 265 266 267 268
        self.grid[cell_id[0]][cell_id[1]] = self.transitions.set_transition(
            self.grid[cell_id[0]][cell_id[1]],
            cell_id[2],
            transition_index,
            new_transition,
            remove_deadends)
269

270 271
    def save_transition_map(self, filename):
        """
u214892's avatar
u214892 committed
272
        Save the transitions grid as `filename`, in npy format.
273 274 275 276 277 278 279 280 281

        Parameters
        ----------
        filename : string
            Name of the file to which to save the transitions grid.

        """
        np.save(filename, self.grid)

u214892's avatar
u214892 committed
282
    def load_transition_map(self, package, resource):
283
        """
u214892's avatar
u214892 committed
284
        Load the transitions grid from `filename` (npy format).
285
        The load function only updates the transitions grid, and possibly width and height, but the object has to be
u214892's avatar
u214892 committed
286
        initialized with the correct `transitions` object anyway.
287 288 289

        Parameters
        ----------
290 291 292 293
        package : string
            Name of the package from which to load the transitions grid.
        resource : string
            Name of the file from which to load the transitions grid within the package.
294 295
        override_gridsize : bool
            If override_gridsize=True, the width and height of the GridTransitionMap object are replaced with the size
u214892's avatar
u214892 committed
296
            of the map loaded from `filename`. If override_gridsize=False, the transitions grid is either cropped (if
spiglerg's avatar
spiglerg committed
297 298
            the grid size is larger than (height,width) ) or padded with zeros (if the grid size is smaller than
            (height,width) )
299 300

        """
301 302
        with path(package, resource) as file_in:
            new_grid = np.load(file_in)
303 304 305 306

        new_height = new_grid.shape[0]
        new_width = new_grid.shape[1]

u214892's avatar
u214892 committed
307 308 309
        self.width = new_width
        self.height = new_height
        self.grid = new_grid
310

311
    def is_dead_end(self, rcPos: IntVector2DArray):
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
312
        """
313 314 315 316 317 318 319 320 321 322
        Check if the cell is a dead-end.

        Parameters
        ----------
        rcPos: Tuple[int,int]
            tuple(row, column) with grid coordinate
        Returns
        -------
        boolean
            True if and only if the cell is a dead-end.
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
323 324 325 326 327 328
        """
        nbits = 0
        tmp = self.get_full_transitions(rcPos[0], rcPos[1])
        while tmp > 0:
            nbits += (tmp & 1)
            tmp = tmp >> 1
329 330
        return nbits == 1

331
    def is_simple_turn(self, rcPos: IntVector2DArray):
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        """
        Check if the cell is a left/right simple turn

        Parameters
        ----------
            rcPos: Tuple[int,int]
                tuple(row, column) with grid coordinate
        Returns
        -------
            boolean
                True if and only if the cell is a left/right simple turn.
        """
        tmp = self.get_full_transitions(rcPos[0], rcPos[1])

        def is_simple_turn(trans):
u214892's avatar
u214892 committed
347
            all_simple_turns = OrderedSet()
348 349 350 351 352 353 354 355 356 357
            for trans in [int('0100000000000010', 2),  # Case 1b (8)  - simple turn right
                          int('0001001000000000', 2)  # Case 1c (9)  - simple turn left]:
                          ]:
                for _ in range(3):
                    trans = self.transitions.rotate_transition(trans, rotation=90)
                    all_simple_turns.add(trans)
            return trans in all_simple_turns

        return is_simple_turn(tmp)

358
    def check_path_exists(self, start: IntVector2DArray, direction: int, end: IntVector2DArray):
359 360 361 362 363 364 365
        """
        Breath first search for a possible path from one node with a certain orientation to a target node.
        :param start: Start cell rom where we want to check the path
        :param direction: Start direction for the path we are testing
        :param end: Cell that we try to reach from the start cell
        :return: True if a path exists, False otherwise
        """
u214892's avatar
u214892 committed
366
        visited = OrderedSet()
367 368 369 370 371
        stack = [(start, direction)]
        while stack:
            node = stack.pop()
            node_position = node[0]
            node_direction = node[1]
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
372 373

            if Vec2d.is_equal(node_position, end):
374 375 376 377 378 379 380 381 382 383 384
                return True
            if node not in visited:
                visited.add(node)

                moves = self.get_transitions(node_position[0], node_position[1], node_direction)
                for move_index in range(4):
                    if moves[move_index]:
                        stack.append((get_new_position(node_position, move_index),
                                      move_index))

        return False
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
385

386
    def cell_neighbours_valid(self, rcPos: IntVector2DArray, check_this_cell=False):
387 388 389
        """
        Check validity of cell at rcPos = tuple(row, column)
        Checks that:
u214892's avatar
u214892 committed
390
        - surrounding cells have inbound transitions for all the outbound transitions of this cell.
391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        These are NOT checked - see transition.is_valid:
        - all transitions have the mirror transitions (N->E <=> W->S)
        - Reverse transitions (N -> S) only exist for a dead-end
        - a cell contains either no dead-ends or exactly one

        Returns: True (valid) or False (invalid)
        """
        cell_transition = self.grid[tuple(rcPos)]

        if check_this_cell:
            if not self.transitions.is_valid(cell_transition):
                return False

        gDir2dRC = self.transitions.gDir2dRC  # [[-1,0] = N, [0,1]=E, etc]
        grcPos = array(rcPos)
        grcMax = self.grid.shape

u214892's avatar
u214892 committed
409
        binTrans = self.get_full_transitions(*rcPos)  # 16bit integer - all trans in/out
410 411
        lnBinTrans = array([binTrans >> 8, binTrans & 0xff], dtype=np.uint8)  # 2 x uint8
        g2binTrans = np.unpackbits(lnBinTrans).reshape(4, 4)  # 4x4 x uint8 binary(0,1)
412 413
        gDirOut = g2binTrans.any(axis=0)  # outbound directions as boolean array (4)
        giDirOut = np.argwhere(gDirOut)[:, 0]  # valid outbound directions as array of int
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

        # loop over available outbound directions (indices) for rcPos
        for iDirOut in giDirOut:
            gdRC = gDir2dRC[iDirOut]  # row,col increment
            gPos2 = grcPos + gdRC  # next cell in that direction

            # Check the adjacent cell is within bounds
            # if not, then this transition is invalid!
            if np.any(gPos2 < 0):
                return False
            if np.any(gPos2 >= grcMax):
                return False

            # Get the transitions out of gPos2, using iDirOut as the inbound direction
            # if there are no available transitions, ie (0,0,0,0), then rcPos is invalid
u214892's avatar
u214892 committed
429
            t4Trans2 = self.get_transitions(*gPos2, iDirOut)
430 431 432 433
            if any(t4Trans2):
                continue
            else:
                return False
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        # If the cell is empty but has incoming connections we return false
        if binTrans < 1:
            connected = 0

            for iDirOut in np.arange(4):
                gdRC = gDir2dRC[iDirOut]  # row,col increment
                gPos2 = grcPos + gdRC  # next cell in that direction

                # Check the adjacent cell is within bounds
                # if not, then ignore it for the count of incoming connections
                if np.any(gPos2 < 0):
                    continue
                if np.any(gPos2 >= grcMax):
                    continue

                # Get the transitions out of gPos2, using iDirOut as the inbound direction
                # if there are no available transitions, ie (0,0,0,0), then rcPos is invalid

                for orientation in range(4):
                    connected += self.get_transition((gPos2[0], gPos2[1], orientation), mirror(iDirOut))
            if connected > 0:
                return False
456 457 458

        return True

459
    def fix_neighbours(self, rcPos: IntVector2DArray, check_this_cell=False):
460 461 462
        """
        Check validity of cell at rcPos = tuple(row, column)
        Checks that:
u214892's avatar
u214892 committed
463
        - surrounding cells have inbound transitions for all the outbound transitions of this cell.
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

        These are NOT checked - see transition.is_valid:
        - all transitions have the mirror transitions (N->E <=> W->S)
        - Reverse transitions (N -> S) only exist for a dead-end
        - a cell contains either no dead-ends or exactly one

        Returns: True (valid) or False (invalid)
        """
        cell_transition = self.grid[tuple(rcPos)]

        if check_this_cell:
            if not self.transitions.is_valid(cell_transition):
                return False

        gDir2dRC = self.transitions.gDir2dRC  # [[-1,0] = N, [0,1]=E, etc]
        grcPos = array(rcPos)
        grcMax = self.grid.shape

        binTrans = self.get_full_transitions(*rcPos)  # 16bit integer - all trans in/out
        lnBinTrans = array([binTrans >> 8, binTrans & 0xff], dtype=np.uint8)  # 2 x uint8
        g2binTrans = np.unpackbits(lnBinTrans).reshape(4, 4)  # 4x4 x uint8 binary(0,1)
        gDirOut = g2binTrans.any(axis=0)  # outbound directions as boolean array (4)
        giDirOut = np.argwhere(gDirOut)[:, 0]  # valid outbound directions as array of int

        # loop over available outbound directions (indices) for rcPos
        for iDirOut in giDirOut:
            gdRC = gDir2dRC[iDirOut]  # row,col increment
            gPos2 = grcPos + gdRC  # next cell in that direction

            # Check the adjacent cell is within bounds
            # if not, then this transition is invalid!
            if np.any(gPos2 < 0):
                return False
            if np.any(gPos2 >= grcMax):
                return False

            # Get the transitions out of gPos2, using iDirOut as the inbound direction
            # if there are no available transitions, ie (0,0,0,0), then rcPos is invalid
            t4Trans2 = self.get_transitions(*gPos2, iDirOut)
            if any(t4Trans2):
                continue
            else:
                self.set_transition((gPos2[0], gPos2[1], iDirOut), mirror(iDirOut), 1)
                return False

        return True

511
    def fix_transitions(self, rcPos: IntVector2DArray, direction: IntVector2D = -1):
512 513 514 515 516 517
        """
        Fixes broken transitions
        """
        gDir2dRC = self.transitions.gDir2dRC  # [[-1,0] = N, [0,1]=E, etc]
        grcPos = array(rcPos)
        grcMax = self.grid.shape
518 519 520 521 522 523 524
        # Transition elements
        transitions = RailEnvTransitions()
        cells = transitions.transition_list
        simple_switch_east_south = transitions.rotate_transition(cells[10], 90)
        simple_switch_west_south = transitions.rotate_transition(cells[2], 270)
        symmetrical = cells[6]
        double_slip = cells[5]
525
        three_way_transitions = [simple_switch_east_south, simple_switch_west_south]
526
        # loop over available outbound directions (indices) for rcPos
527

u214892's avatar
u214892 committed
528
        incoming_connections = np.zeros(4)
529 530 531 532 533
        for iDirOut in np.arange(4):
            gdRC = gDir2dRC[iDirOut]  # row,col increment
            gPos2 = grcPos + gdRC  # next cell in that direction

            # Check the adjacent cell is within bounds
u214892's avatar
u214892 committed
534
            # if not, then ignore it for the count of incoming connections
535
            if np.any(gPos2 < 0):
u214892's avatar
u214892 committed
536
                continue
537
            if np.any(gPos2 >= grcMax):
u214892's avatar
u214892 committed
538
                continue
539 540 541 542 543 544 545

            # Get the transitions out of gPos2, using iDirOut as the inbound direction
            # if there are no available transitions, ie (0,0,0,0), then rcPos is invalid
            connected = 0
            for orientation in range(4):
                connected += self.get_transition((gPos2[0], gPos2[1], orientation), mirror(iDirOut))
            if connected > 0:
u214892's avatar
u214892 committed
546
                incoming_connections[iDirOut] = 1
547

u214892's avatar
u214892 committed
548
        number_of_incoming = np.sum(incoming_connections)
549
        # Only one incoming direction --> Straight line set deadend
550
        if number_of_incoming == 1:
551 552 553 554 555 556 557 558
            if self.get_full_transitions(*rcPos) == 0:
                self.set_transitions(rcPos, 0)
            else:
                self.set_transitions(rcPos, 0)

                for direction in range(4):
                    if incoming_connections[direction] > 0:
                        self.set_transition((rcPos[0], rcPos[1], mirror(direction)), direction, 1)
559 560
        # Connect all incoming connections
        if number_of_incoming == 2:
561 562
            self.set_transitions(rcPos, 0)

u214892's avatar
u214892 committed
563
            connect_directions = np.argwhere(incoming_connections > 0)
564 565 566
            self.set_transition((rcPos[0], rcPos[1], mirror(connect_directions[0])), connect_directions[1], 1)
            self.set_transition((rcPos[0], rcPos[1], mirror(connect_directions[1])), connect_directions[0], 1)

567
        # Find feasible connection for three entries
568
        if number_of_incoming == 3:
569
            self.set_transitions(rcPos, 0)
u214892's avatar
u214892 committed
570
            hole = np.argwhere(incoming_connections < 1)[0][0]
571
            if direction >= 0:
572 573
                switch_type_idx = (direction - hole + 3) % 4
                if switch_type_idx == 0:
574 575
                    transition = simple_switch_west_south
                elif switch_type_idx == 2:
576 577
                    transition = simple_switch_east_south
                else:
578
                    transition = self.random_generator.choice(three_way_transitions, 1)
579
            else:
580
                transition = self.random_generator.choice(three_way_transitions, 1)
581 582 583 584
            transition = transitions.rotate_transition(transition, int(hole * 90))
            self.set_transitions((rcPos[0], rcPos[1]), transition)

        # Make a double slip switch
585
        if number_of_incoming == 4:
586
            rotation = self.random_generator.randint(2)
587 588
            transition = transitions.rotate_transition(double_slip, int(rotation * 90))
            self.set_transitions((rcPos[0], rcPos[1]), transition)
589 590
        return True

591 592
    def validate_new_transition(self, prev_pos: IntVector2D, current_pos: IntVector2D,
                                new_pos: IntVector2D, end_pos: IntVector2D):
593 594 595
        """
        Utility function to test that a path drawn by a-start algorithm uses valid transition objects.
        We us this to quide a-star as there are many transition elements that are not allowed in RailEnv
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
596

597 598 599 600 601 602
        :param prev_pos: The previous position we were checking
        :param current_pos: The current position we are checking
        :param new_pos: Possible child position we move into
        :param end_pos: End cell of path we are drawing
        :return: True if the transition is valid, False if transition element is illegal
        """
603 604 605 606 607 608 609 610 611 612 613 614
        # start by getting direction used to get to current node
        # and direction from current node to possible child node
        new_dir = get_direction(current_pos, new_pos)
        if prev_pos is not None:
            current_dir = get_direction(prev_pos, current_pos)
        else:
            current_dir = new_dir
        # create new transition that would go to child
        new_trans = self.grid[current_pos]
        if prev_pos is None:
            if new_trans == 0:
                # need to flip direction because of how end points are defined
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
615
                new_trans = self.transitions.set_transition(new_trans, mirror(current_dir), new_dir, 1)
616 617
            else:
                # check if matches existing layout
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
618
                new_trans = self.transitions.set_transition(new_trans, current_dir, new_dir, 1)
619 620
        else:
            # set the forward path
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
621
            new_trans = self.transitions.set_transition(new_trans, current_dir, new_dir, 1)
622
            # set the backwards path
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
623 624
            new_trans = self.transitions.set_transition(new_trans, mirror(new_dir), mirror(current_dir), 1)
        if Vec2d.is_equal(new_pos, end_pos):
625 626 627 628
            # need to validate end pos setup as well
            new_trans_e = self.grid[end_pos]
            if new_trans_e == 0:
                # need to flip direction because of how end points are defined
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
629
                new_trans_e = self.transitions.set_transition(new_trans_e, new_dir, mirror(new_dir), 1)
630 631
            else:
                # check if matches existing layout
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
632
                new_trans_e = self.transitions.set_transition(new_trans_e, new_dir, new_dir, 1)
633

Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
634
            if not self.transitions.is_valid(new_trans_e):
635 636 637
                return False

        # is transition is valid?
Egli Adrian (IT-SCI-API-PFI)'s avatar
Egli Adrian (IT-SCI-API-PFI) committed
638
        return self.transitions.is_valid(new_trans)
639

640 641 642

def mirror(dir):
    return (dir + 2) % 4
u214892's avatar
u214892 committed
643
# TODO: improvement override __getitem__ and __setitem__ (cell contents, not transitions?)