Source code for flatland.envs.malfunction_effects_generators

from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union

import flatland.envs.malfunction_generators as mfg
from flatland.core.effects_generator import EffectsGenerator
from flatland.core.grid.grid_utils import IntVector2D
from flatland.envs import malfunction_generators as mal_gen
from flatland.envs.agent_utils import EnvAgent
from flatland.envs.step_utils.states import TrainState
from flatland.utils.cli_utils import resolve_type


[docs] class MalfunctionEffectsGenerator(EffectsGenerator["RailEnv"]): def __init__(self, malfunction_generator=None, **kwargs): super().__init__() if malfunction_generator is not None: self.malfunction_generator = malfunction_generator else: if kwargs: self.malfunction_generator = mal_gen.ParamMalfunctionGen.extract_malfunction_generator(kwargs, key="param_malfunction_gen") else: # TODO https://github.com/flatland-association/flatland-rl/issues/242 not generic! self.malfunction_generator = mal_gen.NoMalfunctionGen()
[docs] def on_episode_start(self, env: "RailEnv", *args, **kwargs) -> "RailEnv": # start the generator over, so that an episode draws its malfunctions as in a new env: after a seeded reset, # the malfunctions repeat. if isinstance(self.malfunction_generator, mfg.ParamMalfunctionGen): self.malfunction_generator.reset() return env
[docs] def on_episode_step_start(self, env: "RailEnv", *args, **kwargs) -> "RailEnv": for agent in env.agents: agent.malfunction_handler.generate_malfunction(self.malfunction_generator, env.np_random) return env
def __getstate__(self): if isinstance(self.malfunction_generator, mfg.ParamMalfunctionGen): return { "cls": self.fullname, "specs": { "kwargs": { "param_malfunction_gen": self.malfunction_generator.get_process_data()._asdict(), "malfunction_cached_random_state": self.malfunction_generator._cached_random_state, "malfunction_rand_idx": self.malfunction_generator._rand_idx, } } } else: return { "cls": self.fullname, }
# TODO https://github.com/flatland-association/flatland-rl/issues/242 generalize serialization # Third argument: in_malfunction as of the end of the *previous* step - see # ConditionalMalfunctionEffectsGenerator._previous_in_malfunction and EnvAgent.derived_state()'s own # docstring for why a condition can't just read agent.malfunction_handler.in_malfunction directly. MalfunctionCondition = Callable[["EnvAgent", int, bool], bool]
[docs] def on_map_state_condition(env_agent: EnvAgent, elapsed_steps: int, previous_in_malfunction: bool) -> bool: return env_agent.derived_state(in_malfunction=previous_in_malfunction).is_on_map_state()
[docs] class ConditionalMalfunctionEffectsGenerator(EffectsGenerator["RailEnv"]): def __init__(self, malfunction_rate: float = None, min_duration: float = None, max_duration: float = None, earliest_malfunction: int = None, max_num_malfunctions: int = None, condition: Union[MalfunctionCondition, str] = None, condition_pkg: str = None, condition_cls: str = None, num_malfunctions: int = 0, malfunction_cached_random_state: Optional[tuple] = None, malfunction_rand_idx: int = 0, previous_in_malfunction: Optional[Iterable[Tuple[int, bool]]] = None, ): """ Generate agent malfunctions conditionally with conditional rate and duration. Parameters ---------- malfunction_rate : float Poisson process with given rate. min_duration : int If malfunction, duration uniformly in [min_duration,max_duration]. max_duration : int If malfunction, duration uniformly in [min_duration,max_duration]. earliest_malfunction : int Defaults to `None`. max_num_malfunctions : int Maximum number of malfunctions per episode, over all agents. Defaults to `None` (no maximum). condition : MalfunctionCondition | str Additional condition. Defaults to None. condition_pkg : str Additional condition to be created instead of instance via `condition`. Defaults to None. condition_cls : str Additional condition to be created instead of instance via `condition`. Defaults to None. num_malfunctions : int State of a snapshot taken mid-episode, restored by `EffectsGenerator.from_state()`, not a setting: the number of malfunctions so far in the episode. Defaults to 0. malfunction_cached_random_state : tuple State of a snapshot: the random state the generator's block of random numbers was drawn from. Defaults to `None` (no draw yet). malfunction_rand_idx : int State of a snapshot: the position of the last draw in the block. Defaults to 0. previous_in_malfunction : Iterable[Tuple[int, bool]] State of a snapshot: per agent handle, whether the agent was in malfunction at the end of the previous step. Defaults to none. A state saved before 5.0.0 has no episode state: a snapshot restored mid-episode then continues with a new count and block, so its malfunctions differ from the recorded ones. """ super().__init__() self._malfunction_rate = float(malfunction_rate) self._min_duration = int(min_duration) self._max_duration = int(max_duration) self._malfunction_generator = mal_gen.ParamMalfunctionGen( mal_gen.MalfunctionParameters(malfunction_rate=self._malfunction_rate, min_duration=self._min_duration, max_duration=self._max_duration) ) self._earliest_condition = int(earliest_malfunction) if earliest_malfunction is not None else None self._max_num_malfunctions = int(max_num_malfunctions) if max_num_malfunctions is not None else None self._condition = resolve_type(condition, condition_pkg, condition_cls) # episode state, restored from a snapshot taken mid-episode, so that the episode continues as recorded self._num_malfunctions = int(num_malfunctions) self._malfunction_generator.restore(malfunction_cached_random_state, int(malfunction_rand_idx)) self._previous_in_malfunction: Dict[int, bool] = {int(h): bool(m) for h, m in (previous_in_malfunction or [])}
[docs] def on_episode_start(self, env: "RailEnv", *args, **kwargs) -> "RailEnv": self._previous_in_malfunction = {} # start the generator over and count malfunctions per episode, so that a seeded reset repeats them. self._malfunction_generator.reset() self._num_malfunctions = 0 return env
[docs] def on_episode_step_start(self, env: "RailEnv", *args, **kwargs) -> "RailEnv": if self._earliest_condition is not None and env._elapsed_steps < self._earliest_condition: return env for agent in env.agents: previous_in_malfunction = self._previous_in_malfunction.get(agent.handle, False) if (self._max_num_malfunctions is None or self._num_malfunctions < self._max_num_malfunctions) and \ (self._condition is None or self._condition(agent, env._elapsed_steps, previous_in_malfunction)): in_malfunction_before = agent.malfunction_handler.in_malfunction agent.malfunction_handler.generate_malfunction(self._malfunction_generator, env.np_random) in_malfunction_after = agent.malfunction_handler.in_malfunction if in_malfunction_after and not in_malfunction_before: self._num_malfunctions += 1 self._previous_in_malfunction[agent.handle] = agent.malfunction_handler.in_malfunction return env
def __getstate__(self): return { "cls": self.fullname, "specs": { "kwargs": { "malfunction_rate": self._malfunction_rate, "min_duration": self._min_duration, "max_duration": self._max_duration, "earliest_malfunction": self._earliest_condition, "max_num_malfunctions": self._max_num_malfunctions, "condition_pkg": None if self._condition is None else self._condition.__module__, "condition_cls": None if self._condition is None else self._condition.__qualname__, **self._episode_state(), } } } def _episode_state(self) -> Dict[str, Any]: """The episode state persisted in a snapshot, as keyword arguments of `__init__`.""" return { "num_malfunctions": self._num_malfunctions, "malfunction_cached_random_state": self._malfunction_generator._cached_random_state, "malfunction_rand_idx": self._malfunction_generator._rand_idx, # pairs instead of a dict: msgpack doesn't load integer map keys by default "previous_in_malfunction": sorted(self._previous_in_malfunction.items()), }
[docs] def make_multi_malfunction_condition(conditions: List[MalfunctionCondition]) -> MalfunctionCondition: """ Disjunctively wrap multiple MalfunctionCondition into one. Parameters ---------- conditions : List[MalfunctionCondition] list of disjunctive conditions Returns ------- MalfunctionCondition """ def _condition(agent: "EnvAgent", elapsed_steps: int, previous_in_malfunction: bool): for c in conditions: if c(agent, elapsed_steps, previous_in_malfunction): return True return False return _condition
[docs] def condition_stopped_intermediate_and_range(start_step_incl: int, end_step_excl: int) -> MalfunctionCondition: """ Malfunction condition: stopped at an intermediate waypoint and in range of timesteps. Parameters ---------- start_step_incl : int start step of positive range (incl.) end_step_excl : int end step of positive range (excl.) Returns ------- MalfunctionCondition """ def _condition(agent: "EnvAgent", elapsed_steps: int, previous_in_malfunction: bool): position = agent.current_entry_point[0] if agent.current_entry_point is not None else None return ((position in {w.position for ws in agent.waypoints[1:-1] for w in ws}) and agent.derived_state(in_malfunction=previous_in_malfunction) == TrainState.STOPPED and elapsed_steps >= start_step_incl and elapsed_steps < end_step_excl) return _condition
[docs] def condition_stopped_cells_and_range(start_step_incl: int, end_step_excl: int, cells: List[IntVector2D]) -> MalfunctionCondition: """ Malfunction condition: stopped on any given cell and during range of timesteps. Parameters ---------- start_step_incl : int start step of positive range (incl.) end_step_excl : int end step of positive range (excl.) Returns ------- MalfunctionCondition """ def _condition(agent: "EnvAgent", elapsed_steps: int, previous_in_malfunction: bool): position = agent.current_entry_point[0] if agent.current_entry_point is not None else None return (position in cells and agent.derived_state(in_malfunction=previous_in_malfunction) == TrainState.STOPPED and elapsed_steps >= start_step_incl and elapsed_steps < end_step_excl) return _condition
[docs] class IntermediateStopMalfunctionEffectsGenerator(ConditionalMalfunctionEffectsGenerator): """ Departure malfunctions at (intermediate) stops: generate malfunction when stopped at an (intermediate) waypoint. """ @staticmethod def _condition(agent: "EnvAgent", elapsed_steps: int, previous_in_malfunction: bool): if agent.derived_state(in_malfunction=previous_in_malfunction) != TrainState.STOPPED: return False stops = {(wp.position, wp.direction) for wps in agent.waypoints for wp in wps} return agent.current_entry_point in stops def __init__(self, malfunction_rate: float = 0, min_duration: float = 0, max_duration: float = 0, earliest_malfunction: int = 0, num_malfunctions: int = 0, malfunction_cached_random_state: Optional[tuple] = None, malfunction_rand_idx: int = 0, previous_in_malfunction: Optional[Iterable[Tuple[int, bool]]] = None, ): super().__init__( malfunction_rate=malfunction_rate, min_duration=min_duration, max_duration=max_duration, earliest_malfunction=earliest_malfunction, condition=IntermediateStopMalfunctionEffectsGenerator._condition, num_malfunctions=num_malfunctions, malfunction_cached_random_state=malfunction_cached_random_state, malfunction_rand_idx=malfunction_rand_idx, previous_in_malfunction=previous_in_malfunction, ) def __getstate__(self): return { "cls": self.fullname, "specs": { "kwargs": dict( malfunction_rate=self._malfunction_rate, min_duration=self._min_duration, max_duration=self._max_duration, earliest_malfunction=self._earliest_condition, **self._episode_state(), ) } }