flatland.envs.rail_env module#

Definition of the RailEnv environment.

class flatland.envs.rail_env.AbstractRailEnv(rail_generator: RailGenerator = None, line_generator: LineGenerator = None, number_of_agents=2, obs_builder_object: ~flatland.core.env_observation_builder.ObservationBuilder = <flatland.envs.observations.GlobalObsForRailEnv object>, malfunction_generator_and_process_data=None, malfunction_generator: MalfunctionGenerator = None, remove_agents_at_target=True, random_seed=None, timetable_generator=<function timetable_generator>, acceleration_delta: ~fractions.Fraction = Fraction(1, 1), braking_delta: ~fractions.Fraction = Fraction(-1, 1), check_step_pre_post_conditions: bool = True, rewards: ~flatland.envs.rewards.Rewards = None, effects_generator: ~flatland.core.effects_generator.EffectsGenerator[RailEnv] = None, distance_map: ~flatland.core.distance_map.AgentSourceTargetDistanceMap = None)[source]#

Bases: Environment, Generic[TransitionMapT, ResourceMapT, EntryPointT]

AbstractRailEnv 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 (continue moving or stay still)

  • 1: turn left at switch 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 at switch and move to the next cell; if the agent was not moving, movement is started

  • 4: stop moving

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

In order for agents to be able to “understand” the simulation behaviour from the observations, the execution order of actions should not matter (i.e. not depend on the agent handle). However, the agent ordering is still used to resolve conflicts between two agents trying to move into the same cell, for example, head-on collisions, or agents “merging” at junctions. See MotionCheck for more details.

Stochastic malfunctioning of trains: Trains in RailEnv can malfunction if they are halted too often (either by their own choice or because an invalid action or cell is selected.

Every time an agent stops, an agent has a certain probability of malfunctioning. Malfunctions of trains follow a poisson process with a certain rate. Not all trains will be affected by malfunctions during episodes to keep complexity manageable.

TODO: currently, the parameters that control the stochasticity of the environment are hard-coded in init(). For Round 2, they will be passed to the constructor as arguments, to allow for more flexibility.

Parameters#

rail_generatorfunction

The rail_generator function is a function that takes the width, height and agent 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 handles. The rail_generator can pass a distance map in the hints or information for specific line_generators. Implementations can be found in flatland/envs/rail_generators.py

line_generatorfunction

The line_generator function is a function that takes the grid, the number of agents and optional hints and returns a list of starting positions, targets, initial orientations and maximum speeds for all agent handles. Implementations can be found in flatland/envs/line_generators.py

number_of_agentsint

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

ObservationBuilder-derived object that builds observation vectors for each agent.

malfunction_generator_and_process_dataTuple[“MalfunctionGenerator”,”MalfunctionProcessData”]

Deprecated. Use malfunction_generator option instead.

malfunction_generator: “MalfunctionGenerator”

Convenience option to inject effects generator. Defaults to NoMalfunctionGen.

remove_agents_at_targetbool

If remove_agents_at_target is set to true then the agents will be removed by placing to RailEnv.DEPOT_POSITION when the agent has reached its target position.

random_seedint or None

if None, then it is ignored, else the random generators are seeded with this number to ensure that stochastic operations are replicable across multiple operations

timetable_generator

Timetable generator to be used in reset(). Defaults to “ttg.timetable_generator”.

acceleration_deltaFraction

Determines how much speed is increased by MOVE_FORWARD action up to max_speed set by train’s Line (sampled from speed_ratios by LineGenerator). As speed is between 0 and 1, acceleration_delta=1 restores the previous constant speed behaviour (i.e. MOVE_FORWARD always sets to max speed allowed for train). Must be in (0, 1], 1 being MAX_SPEED, the highest speed the env supports so that an agent never jumps over a cell or edge in one step: a delta above 1 would change the speed by more than the whole speed range in one step and has no meaning of its own. Not checked: a delta above a train’s max speed. The delta is the same for all trains, so step() caps the new speed at each train’s max speed instead of failing. A whole number or a float is converted to a Fraction, a float snapped to the nearest 1/n as max speeds are (0.33 to Fraction(1, 3), see speed_counter.py’s _validated_fraction()); pass a Fraction for an exact value. An invalid value raises a ValueError, also when it is assigned later (env.acceleration_delta = …).

braking_deltaFraction

Determines how much speed is decreased by STOP_MOVING action. As speed is between 0 and 1, braking_delta=-1 restores to previous full stop behaviour. Must be in [-1, 0): -1 stops any train in one step, a delta below it has no meaning of its own. Not checked: a delta below minus a train’s speed; step() floors the new speed at 0 instead of failing. Converted and checked as acceleration_delta.

check_step_pre_post_conditionsbool

Set to False to skip checking step() pre- and postconditions, e.g. in performance-sensitive production use.

rewardsDefaultRewards

The rewards function to use. Defaults to standard settings of Flatland 3 behaviour.

effects_generatorOptional[EffectsGenerator[“RailEnv”]]

The effects generator that can modify the env at the end of env reset, at the beginning of the env step and at the end of the env step.

distance_map: AgentSourceTargetDistanceMap

Use pre-computed distance map. Defaults to new distance map.

Notes#

step() never reads or writes agent.state/agent.state_machine - control flow (candidate position/ speed/distance, resource conflict resolution, DONE detection) is derived purely from position/ speed/malfunction signals via EnvAgent.derived_state(), which get_info_dict()’s ‘state’/ ‘action_required’ fields use too - so both stay correct whether or not the env is wrapped via flatland.envs.rail_env_state_machine_wrapper.RailEnvStateMachineWrapper. That wrapper now exists only for a caller that needs agent.state/agent.state_machine themselves (real state-machine semantics, e.g. TrainStateMachine transition/signal internals), not for anything production code or get_info_dict() needs.

property acceleration_delta: Fraction#

Speed gained per step by MOVE_FORWARD (or starting from rest), up to the agent’s max speed. A Fraction > 0.

action_required(is_cell_entry)[source]#

Reports whether an agent needs an action supplied for it in the next env.step() call.

A pure function of the two arguments passed in - this function just evaluates the four cases below against whatever agent_state/is_cell_entry it’s given from derived_state() .

Neither purely state-derived nor purely distance/speed-derived - agent_state gates which of four cases applies, and only one of them actually consults is_cell_entry (despite its name, callers pass agent.speed_counter.is_cell_exit() here, not SpeedCounter.is_cell_entry - a pre-existing naming mismatch between this parameter and the value passed for it): - WAITING / MALFUNCTION_OFF_MAP (off map, not yet eligible to move): always False, regardless

of anything else.

  • READY_TO_DEPART (off map, eligible to move): always True, regardless of anything else.

  • MOVING / STOPPED / MALFUNCTION (on map): collapses to is_cell_entry alone (speed > 0 and distance + speed >= edge_length - see flatland-book’s Design by Contract page, https://flatland-association.github.io/flatland-book/key-concepts/design_by_contract.html) - identical for all three on-map states, with no special case for MALFUNCTION. Since this requires speed > 0, it reads False for any on-map agent parked at speed 0, regardless of distance - including a STOPPED/MALFUNCTION agent after a denied crossing, or parked at its target exactly at the edge boundary (distance == edge_length). This makes “malfunctioning agents never need an action” a state-level guarantee - a malfunctioning agent’s speed is always forced to 0, so this branch is always False throughout any malfunction, on map or off - see test_action_required_false_during_malfunction and test_action_required_after_refused_crossing in test_flatland_envs_rail_env.py.

  • DONE (terminal - neither on map nor off map): always False, even with remove_agents_at_target=False leaving the agent parked at a real position - is_cell_entry is never consulted either way, since DONE is excluded from the on-map branch above.

Parameters#

agent_state: TrainState is_cell_entry: bool

despite the name, this is the caller’s is_cell_exit() value - see above.

Returns#

True: Agent needs to provide an action False: Agent cannot provide an action

add_agent(agent)[source]#

Add static info for a single agent. Returns the index of the new agent.

property braking_delta: Fraction#

Speed change per step by STOP_MOVING, down to 0. A Fraction < 0.

clear_rewards_dict()[source]#

Reset the rewards dictionary

collect(agent: EnvAgent, action: RailEnvActions, candidate_entry_point_independent: EntryPointT | None) → Tuple[Any, Any][source]#

Collect phase for a single agent: derive this step’s candidate entry point/speed/distance unilaterally from the agent’s pre-step state and the given action alone - including for an invalid action, which itself just yields a zeroed/unchanged candidate (e.g. candidate_speed = 0) rather than skipping computation entirely. The distribute phase below decides whether the resource check actually grants it.

candidate_entry_point_independent is this agent’s own pre_step_snapshot. candidate_entry_point_independents[agent.handle] value (see _capture_pre_step_snapshot) - the one field the collect phase needs regardless of check_step_pre_post_conditions, threaded in directly instead of the whole PreStepSnapshot (which the collect phase otherwise has no use for - everything else in it is postcondition-check-only).

Stashes the derived candidate_/action_valid/is_cell_exit/etc. values into self.temp_transition_data[agent.handle] for the distribute phase and post-step checks to read.

Returns (current_resource, new_resource) - the (from, to) resource pair for the caller to register via self.resource_check.add_agent() alongside every other agent’s pair, before self.resource_check.find_conflicts() runs.

distribute(agent: EnvAgent, agent_transition_data: AgentTransitionData)[source]#

Distribute phase for a single agent: resolve this step’s collect-phase candidate against the resource check’s conflict resolution (already run for every agent, via self.resource_check.find_conflicts(), by the time this is called), commit position/speed/distance, handle DONE, and compute this step’s reward.

Returns the value to assign into self.rewards_dict[agent.handle] (self.rewards.cumulate() applied to the existing self.rewards_dict[agent.handle] and this step’s own reward) - left for the caller to assign, mirroring collect()’s own resource-pair return.

end_of_episode_update(have_all_agents_ended)[source]#

Updates made when episode ends Parameters: have_all_agents_ended - Indicates if all agents have reached done state

get_agent_handles() → List[int][source]#

Returns a list of agents’ handles to be used as keys in the step() function.

get_info_dict()[source]#

Returns dictionary of infos for all agents dict_keys : action_required -

malfunction - Counter value for malfunction > 0 means train is in malfunction speed - Speed of the train state - State from the trains’s state machine

‘action_required’ and ‘state’ are derived via agent.derived_state() - safe to call here regardless of whether the env is wrapped via flatland.envs.rail_env_state_machine_wrapper.RailEnvStateMachineWrapper, since both call sites (the end of step()’s own return tuple, and reset()) run after this step’s (or, at reset(), this episode’s initial) position/speed have already settled - see derived_state()’s own docstring for the general safe/unsafe timing distinction.

get_num_agents() → int[source]#
handle_done_state(agent)[source]#

Any updates to agent to be made in Done state.

Re-derives “just reached a target entry point, for the first time” directly from agent.current_entry_point (already updated by (12) above when this step’s candidate was accepted) and agent.arrival_time (still None exactly until this method sets it below) - a rejected candidate (current_entry_point unchanged this step) or an agent already done from an earlier step (arrival_time already set) never re-triggers this, independent of agent.state.

reset(regenerate_rail, regenerate_schedule, activate_agents, random_seed)[source]#

The method resets the rail environment

Parameters#

regenerate_railbool, optional

regenerate the rails

regenerate_schedulebool, optional

regenerate the schedule and the static agents

random_seedint, optional

random seed for environment

Returns#

observation_dict: Dict

Dictionary with an observation for each agent

info_dict: Dict with agent specific information

reset_agents()[source]#

Reset the agents to their starting positions

step(action_dict: Dict[int, RailEnvActions])[source]#

Updates rewards for the agents at a step.

class flatland.envs.rail_env.PreStepAgentSnapshot(speed: Fraction | None, current_entry_point: EntryPointT | None, next_entry_point: EntryPointT | None, done: bool, in_malfunction: bool, distance: Fraction | None)[source]#

Bases: NamedTuple

One agent’s state captured before step() runs, for AbstractRailEnv._check_speed_distance_speedup_postconditions()/_check_position_update_postconditions() to verify the post-step update against. Postcondition-check-only - see PreStepSnapshot below for why candidate_entry_point_independent isn’t part of this bundle.

current_entry_point: EntryPointT | None#

Alias for field number 1

distance: Fraction | None#

Alias for field number 5

done: bool#

Alias for field number 3

in_malfunction: bool#

Alias for field number 4

next_entry_point: EntryPointT | None#

Alias for field number 2

speed: Fraction | None#

Alias for field number 0

class flatland.envs.rail_env.PreStepSnapshot(candidate_entry_point_independents: Dict[int, EntryPointT | None], agents: Dict[int, PreStepAgentSnapshot])[source]#

Bases: NamedTuple

candidate_entry_point_independents is a flat dict (column-oriented, keyed by handle) since it’s the one field the collect phase’s own (4) CANDIDATE ENTRY POINT block needs unconditionally, regardless of check_step_pre_post_conditions - bundling it into agents below would force building one PreStepAgentSnapshot per agent (a real per-agent object-construction cost - measured ~5-8% wall clock, see the git history around this class) even when check_step_pre_post_conditions is False and every other field of that bundle goes unused.

agents is row-oriented (one PreStepAgentSnapshot per agent, agents[h].speed) rather than column-oriented (one dict per field, speeds[h]) since every consumer of these six fields - both post-step checks below - reads all six for the same agent together; empty ({}) whenever check_step_pre_post_conditions is False, since nothing reads it then.

agents: Dict[int, PreStepAgentSnapshot]#

Alias for field number 1

candidate_entry_point_independents: Dict[int, EntryPointT | None]#

Alias for field number 0

class flatland.envs.rail_env.RailEnv(width, height, rail_generator: RailGenerator = None, line_generator: LineGenerator = None, number_of_agents=2, obs_builder_object: ~flatland.core.env_observation_builder.ObservationBuilder = <flatland.envs.observations.GlobalObsForRailEnv object>, malfunction_generator_and_process_data=None, malfunction_generator: MalfunctionGenerator = None, remove_agents_at_target=True, random_seed=None, record_steps=False, timetable_generator=<function timetable_generator>, acceleration_delta: ~fractions.Fraction = Fraction(1, 1), braking_delta: ~fractions.Fraction = Fraction(-1, 1), check_step_pre_post_conditions: bool = True, rewards: ~flatland.envs.rewards.Rewards = None, effects_generator: ~flatland.core.effects_generator.EffectsGenerator[RailEnv] = None)[source]#

Bases: AbstractRailEnv[GridTransitionMap, GridResourceMap, Tuple[Tuple[int, int], int]]

clone_from(env: RailEnv, obs_builder: ObservationBuilder[RailEnv, Any] | None = None)[source]#

Clone an environment by resetting the simulation to its current state. See enlite-ai/maze

Parameters#

envEnvironment

the env to clone into self.

step(action_dict: Dict[int, RailEnvActions])[source]#

Updates rewards for the agents at a step.