LaserTag

Grid variant, LaserTagPOMDP: one recorded episode planned by PFT-DPW, replayed in 3D. Drag to orbit, scroll to zoom, and use the bar to play, scrub and switch camera.

Continuous variant, ContinuousLaserTagPOMDP: the same, in the continuous world. Drag to orbit, scroll to zoom, and use the bar to play, scrub and switch camera.

Chase an opponent through a walled arena and fire the tag action from its cell. The only sensor is eight noisy laser ranges, one per compass direction. A ray stops at a wall or at the opponent, so a ray that reaches the opponent gives its distance up to sensor noise, while a ray that ends at a wall only says the opponent is not on it.

So the robot learns where the opponent is only on steps when the two share a row, column or diagonal with no wall between them. Between sightings the belief spreads out under the opponent’s movement model, so a planner has to decide whether to manoeuvre for an unblocked ray to the opponent or to commit to a tag on evidence from earlier steps. There is a grid variant and a continuous one; see Variants.

What the agent sees and does

  • State — np.ndarray of shape (5,): [robot_row, robot_col, opponent_row, opponent_col, terminal_flag] (grid), or the same layout in continuous coordinates.

  • Actions (discrete in the grid, continuous otherwise) — grid: integers 0 north, 1 south, 2 east, 3 west, 4 tag. Continuous: [dx, dy, tag_flag].

  • Observations (continuous) — eight laser ranges with Gaussian noise measurement_noise. The grid variant returns a tuple, the continuous one a length-8 np.ndarray. Terminal grid states emit (-1.0,) * 8. Both variants sweep the same eight headings but number them differently: the grid order is N, NE, E, SE, S, SW, W, NW, while the continuous order starts two places later, at E. Continuous beam \(i\) is grid beam \((i + 2) \bmod 8\), so a planner must not carry a beam index from one variant to the other.

Formal definition

The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\). It is written for the grid variant.

State space. Let \(G\) be the free cells of an \(M \times N\) grid with wall set \(\mathcal{W}\); a cell is written (row, column). Both positions and an absorbing flag:

\[s = (\mathbf{u},\; \mathbf{v},\; \top), \qquad S = G \times G \times \{0, 1\}\]

Here:

  • \(\mathbf{u}\) is the robot’s cell.

  • \(\mathbf{v}\) is the opponent’s cell.

  • \(\top = 1\) once the episode has ended.

Action space.

\[A = \{0,1,2,3,4\} = \{\textsf{N}, \textsf{S}, \textsf{E}, \textsf{W}, \textsf{tag}\}\]

The actions are:

  • \(0\) moves one row up (row \(-1\)).

  • \(1\) moves one row down (row \(+1\)).

  • \(2\) moves one column right (column \(+1\)).

  • \(3\) moves one column left (column \(-1\)).

  • \(4\) (tag) stays and tries to tag the opponent on the robot’s cell.

The continuous variant uses \((\mathrm{d}x, \mathrm{d}y, \text{tag flag}) \in \mathbb{R}^3\) instead.

Observation space. Eight non-negative laser ranges, or the all \(-1\) vector a terminal state emits:

\[Z = \mathbb{R}_{\geq 0}^{8} \cup \{(-1, \dots, -1)\}\]

Component \(k\) is the range along heading N, NE, E, SE, S, SW, W, NW for \(k = 0..7\). The continuous variant returns the same eight ranges as a length-8 array starting at E: its beam \(i\) is grid beam \((i + 2) \bmod 8\).

Transition model. The robot’s move first. With \(p\) = transition_error_prob, a movement action executes as commanded with probability \(1 - p\) and as one of the other three otherwise, chosen uniformly. Let \(a'\) be the executed move. Its (row, column) offset is:

  • \(\Delta_0 = (-1, 0)\)

  • \(\Delta_1 = (1, 0)\)

  • \(\Delta_2 = (0, 1)\)

  • \(\Delta_3 = (0, -1)\)

The robot’s new cell is:

\[\begin{split}\mathbf{u}' = \begin{cases} \mathbf{u} + \Delta_{a'} & \mathbf{u} + \Delta_{a'} \in G \\ \mathbf{u} & \text{otherwise} \end{cases}\end{split}\]

\(\textsf{tag}\) does not move the robot. A tag on the opponent’s cell ends the episode immediately, \(\top' = 1\), with no opponent draw.

The opponent then moves under a stochastic policy with a fixed mass schedule. Write \(\mathbf{w}\) for the robot cell it conditions on — post-move under PURSUE, pre-move under EVADE and EVADE_WHEN_SPOTTED (for a tag these coincide, since tagging does not move). Per axis independently, the policy puts \(0.4\) on one neighbour:

\[\begin{split}\begin{array}{lll} \texttt{PURSUE} & 0.4 \text{ on the cell toward } \mathbf{w} & 0.0 \text{ away} \\ \texttt{EVADE} & 0.0 \text{ toward} & 0.4 \text{ away} \\ \text{axes aligned } (w_i = v_i) & 0.2 \text{ each way} & \text{(policy-invariant)} \end{array}\end{split}\]

plus \(0.2\) on staying put. Invalid neighbours are dropped and their mass falls back onto stay, so the distribution always normalizes and a cornered opponent stands still.

EVADE_WHEN_SPOTTED switches on visibility: while the opponent is not on an unoccluded laser ray, it walks uniformly (\(0.2\) per valid cardinal neighbour, remainder on stay); once spotted, it flees as EVADE. That makes the robot’s own sensing change the opponent’s dynamics — the reason this variant is harder than either fixed policy.

In short: the opponent moves with probability 0.4 along x, 0.4 along y and stays with probability 0.2. Those are nominal weights: when the robot is aligned on an axis the 0.4 splits 0.2/0.2 across both directions, and a blocked neighbour folds its mass into “stay”, so 0.2 is a floor rather than the actual stay probability. opponent_policy selects one of:

  • EVADE (default; away from the robot’s pre-move position).

  • PURSUE.

  • EVADE_WHEN_SPOTTED, which only runs from the robot once a laser has seen it.

Observation model. Eight laser ranges, one per compass direction \(\Delta_k\) (N, NE, E, SE, S, SW, W, NW). The true range is the number of free cells before the first blocker — a wall, the grid edge, or the opponent:

\[d_k(s') = \min\{ j \geq 0 :\; \mathbf{u}' + (j{+}1)\Delta_k \notin G \ \text{ or }\ \mathbf{u}' + (j{+}1)\Delta_k = \mathbf{v}' \}\]

Each is read through independent noise and clipped at zero:

\[o_k = \max\big(0,\; d_k(s') + n_k\big), \qquad n_k \sim \mathcal{N}(0, \sigma^2)\]

with \(\sigma\) = measurement_noise. This is the whole inference problem: the opponent is visible only as a shortened ray, so a reading short by one is ambiguous between an opponent and the sensor’s noise, and a ray blocked by a wall carries no information about the opponent at all. Terminal states emit \((-1, \dots, -1)\).

Reward function. Evaluated against the pre-transition positions for the tag, the realised position for the hazard:

\[\begin{split}R(s, a, s') = \begin{cases} 0 & \top = 1 \\ +\texttt{tag\_reward} + H(\mathbf{u}') & a = \textsf{tag},\ \mathbf{u} = \mathbf{v} \\ -\texttt{tag\_penalty} + H(\mathbf{u}') & a = \textsf{tag},\ \mathbf{u} \neq \mathbf{v} \\ -\texttt{step\_cost} + H(\mathbf{u}') & \text{otherwise} \end{cases}\end{split}\]

The hazard term charges one penalty on a wall or a danger zone, not one for each:

\[\begin{split}H(\mathbf{u}') = \;&-\texttt{dangerous\_area\_penalty} \\ &\cdot \mathbb{1}\big[\mathbf{u}' \in \mathcal{W} \ \text{ or }\ \exists c:\ \lVert \mathbf{u}' - c \rVert_2 \leq \texttt{dangerous\_area\_radius} \big]\end{split}\]

where \(c\) ranges over the danger-zone centres dangerous_areas.

A mistimed tag costs tag_penalty rather than merely a step, which is what makes guessing expensive and the belief worth maintaining.

Initial belief. Uniform over every pair of distinct free cells:

\[b_0\big((\mathbf{u}, \mathbf{v}, 0)\big) = \frac{1}{|G|(|G| - 1)}, \qquad \mathbf{u} \neq \mathbf{v}\]

so the robot’s own position starts unknown too, and the first laser reading must localize both. With initial_state supplied, \(b_0\) is a point mass on it instead.

Note

The opening observation is a fixed mid-range placeholder \((3, \dots, 3)\), not a draw from \(O\) under \(b_0\). A filter that weights the first reading through observation_log_probability is therefore scoring a reading the observation model did not produce.

Discount. \(\gamma\) = discount_factor, required.

Terminal set. \(S_T = \{s : \top = 1\}\) — set by a successful tag, or by a hazard hit when is_dangerous_area_hit_terminal.

Rewards

Event

Reward

Tag on the opponent’s cell

tag_reward (+10.0)

Tag and miss

-tag_penalty (-10.0)

Any move

-step_cost (-1.0)

Inside a wall or a dangerous area

-dangerous_area_penalty (-5.0)

Warning

As in PacMan, dangerous_area_penalty is a positive magnitude that is subtracted, the opposite of the RockSample and Push convention.

Key settings

Argument

Default

What it changes

floor_shape (grid)

(11, 7)

Arena size as (rows, cols). The module docstring says “7x11”; the code says (11, 7).

grid_size (continuous)

(11.0, 7.0)

Arena size as (width, height) — note the axis order differs from floor_shape.

walls

8 fixed cells / box list

Layout. Walls both block movement and shape the laser readings.

measurement_noise

1.0

Laser noise — the partial-observability knob.

opponent_policy

OpponentPolicy.EVADE

PURSUE makes the opponent close on the robot; EVADE_WHEN_SPOTTED makes it flee only while a laser has line of sight.

tag_reward / tag_penalty / step_cost

10.0 / 10.0 / 1.0

The impatience trade-off: raise tag_penalty to punish speculative tags.

dangerous_areas

{(5,3), (7,1), (2,5)}

evasion_speed

0.6 (continuous only)

An episode ends when the terminal flag is set — on a successful tag, or on a hazard hit when is_dangerous_area_hit_terminal=True.

Variants

  • LaserTagPOMDP — a grid, five discrete actions.

  • ContinuousLaserTagPOMDP — continuous positions, axis-aligned box walls, and a continuous [dx, dy, tag_flag] action. ContinuousLaserTagPOMDPDiscreteActions gives that world a five-action set.

VOPP needs a finite action set, so only ContinuousLaserTagPOMDPDiscreteActions of the two continuous classes has a torch model, ContinuousLaserTagVectorizedModel. It models every configuration of that class: all three opponent policies, any dangerous_area_hit_probability, and is_dangerous_area_hit_terminal. It declines nothing.

Can I use?

LaserTagPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

❌

✔️

ContinuousLaserTagPOMDP

Discrete

Continuous

State

❌

✔️

Action

❌

✔️

Observation

❌

✔️

ContinuousLaserTagPOMDPDiscreteActions

Discrete

Continuous

State

❌

✔️

Action

✔️

❌

Observation

❌

✔️

Also supports

LaserTagPOMDP

ContinuousLaserTagPOMDP

ContinuousLaserTagPOMDPDiscreteActions

Native C++ backend

✔️ (loaded lazily; falls back to Python if the extension is missing)

✔️

✔️

Vectorized (torch) model

✔️ LaserTagVectorizedModel (some configurations; others raise NotImplementedError)

❌ (no finite action set)

✔️ ContinuousLaserTagVectorizedModel (every configuration)

In the get_environment registry

✔️

✔️

✔️

Optional dependencies

None

None

None

Example

from POMDPPlanners.environments.laser_tag_pomdp import LaserTagPOMDP

env = LaserTagPOMDP(discount_factor=0.95)

state = env.initial_state_dist().sample(1)[0]
north = 0
next_state = env.sample_next_state(state, north)
laser_ranges = env.sample_observation(next_state, north)
print(next_state, laser_ranges)

Parameters

class POMDPPlanners.environments.laser_tag_pomdp.LaserTagPOMDP(discount_factor, name='LaserTagPOMDP', floor_shape=(11, 7), walls={(1, 2), (3, 0), (3, 4), (5, 0), (6, 4), (9, 1), (9, 4), (10, 6)}, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, dangerous_areas={(2, 5), (5, 3), (7, 1)}, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, transition_error_prob=0.0, reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, penalty_decay=1.0, is_dangerous_area_hit_terminal=False, opponent_policy=OpponentPolicy.EVADE)[source]

Bases: DiscreteActionsEnvironment

LaserTag POMDP environment implementation.

This is a pursuit-evasion problem where a robot must navigate a grid to tag an opponent. The robot receives noisy observations of the opponent’s position and must decide when and where to attempt tagging.

Problem Structure: - States: numpy array [robot_row, robot_col, opp_row, opp_col, terminal] - Actions: North(0), South(1), East(2), West(3), Tag(4) - Observations: 8-directional laser measurements (N,NE,E,SE,S,SW,W,NW) - Rewards: Tag success(+10), Tag failure(-10), Movement(-1)

Parameters:
floor_shape

Grid dimensions as (rows, cols)

walls

Set of wall positions as (row, col) tuples

tag_reward

Reward for successful tagging

tag_penalty

Penalty for unsuccessful tagging

step_cost

Cost per movement action

measurement_noise

Standard deviation of observation noise

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = LaserTagPOMDP(discount_factor=0.95)
>>>
>>> # Get initial state and actions
>>> initial_state = env.initial_state_dist().sample()[0]
>>> actions = env.get_actions()
>>>
>>> # Sample complete step using convenience method
>>> action = actions[0]
>>> next_state, observation, reward = env.sample_next_step(initial_state, action)
>>>
>>> # Check terminal condition
>>> env.is_terminal(initial_state)
False
compute_metrics(histories)[source]

Compute LaserTag POMDP specific metrics from simulation histories.

Parameters:

histories (List[History]) – List of simulation histories.

Return type:

List[MetricValue]

Returns:

All seven metrics in declaration order.

Raises:

ValueError – If histories is empty, or if an episode ran without being measured. See compute_metrics().

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

LaserTagVisualizer

get_actions()[source]

Get all possible actions in the discrete action space.

Return type:

List[int]

get_metric_names()[source]

Get names of LaserTag POMDP specific metrics.

Returns:

the five derived from per-step channels plus the two reward-derived ones.

Return type:

List[str]

get_metric_specs()[source]

Declare the LaserTag metrics derived from the per-step channels.

Return type:

List[StepInfoMetric]

Returns:

Specs for the five state- and transition-derived metrics, in the same order the enum declares them. The two reward-derived metrics are absent here and produced by compute_metrics().

hash_action(action)[source]

Return a hashable key consistent with action equality.

Used by tree-search planners to index action children of a belief node in O(1). The returned key MUST satisfy:

action_a == action_b   (per env's notion of equality)
==> hash_action(action_a) == hash_action(action_b)

Subclasses with non-hashable actions (e.g. np.ndarray) must override to return a hashable surrogate (tobytes() is the standard choice for ndarray actions, which mirrors the np.array_equal semantics used by the linear-scan fallback).

Parameters:

action (Any) – Action to hash.

Return type:

Hashable

Returns:

A hashable key derived from action.

initial_observation_dist()[source]

Get the initial observation distribution.

Return type:

Distribution

initial_state_dist()[source]

Get the initial state distribution.

Return type:

Distribution

is_equal_observation(observation1, observation2)[source]

Check if two observations are equal.

Observations are 8-dimensional laser measurements or terminal observations.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Check if a state is terminal.

Return type:

bool

Parameters:

state (ndarray)

observation_log_probability(next_state, action, observations)[source]

Log-probability of each candidate observation under (next_state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate observations. Subclasses must implement.

Return type:

ndarray

Parameters:
observation_log_probability_per_state(next_states, action, observation)[source]

Log-probability of one observation under each candidate next-state.

Used by particle filters: given N candidate next-states and ONE observation, return N log-likelihoods.

The default implementation falls back to a per-state Python loop delegating to observation_log_probability(). Native-backed envs (those whose observation kernel exposes batch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.

Parameters:
  • next_states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of candidate next-states.

  • action (int) – The action that was executed.

  • observation (Any) – A single observation.

Return type:

ndarray

Returns:

ndarray of shape (N,) with log-probabilities or log-PDFs.

reward(state, action, next_state=None)[source]

Calculate the immediate reward for a state-action transition.

The wall / dangerous-area penalty is computed against the realised post-action robot position taken from next_state. When the caller omits next_state (e.g., the open-loop scalar API path) the method resamples a transition via sample_next_state() so the penalty is always scored against an actual draw from the transition kernel — never against the open-loop state + action_vector intended position. Environment.sample_next_step() threads its sampled next_state into this method so trajectory and reward agree on the same realisation.

Return type:

float

Parameters:
reward_batch(states, action, next_states=None)[source]

Vectorised reward for a batch of states under a single action.

When next_states is supplied the danger-area / wall penalty is evaluated against the realised positions in next_states[:, :2] (matching the contract honoured by Environment.sample_next_step()). When it is None the method resamples via sample_next_state_batch() whenever penalty terms exist, then delegates to the reward model so reward and trajectory remain consistent end-to-end.

Return type:

ndarray

Parameters:
  • states (Any)

  • action (int)

  • next_states (Any)

property reward_requires_next_state: bool

Reward depends on the realised next_state iff hazard-terminal is on.

When enabled, the dangerous-area penalty is deterministic given the terminal slot set during the transition, so drivers sample the transition first and thread the realised next_state into reward().

sample_next_state(state, action, n_samples=1)[source]

Sample one or more next states for (state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single next state of the env’s native type. When n_samples > 1: an array-like of length n_samples (numeric envs return np.ndarray of shape (n_samples, *dim); structured envs return List[T]).

Return type:

Any

Parameters:
sample_next_state_batch(states, action)[source]

Sample one next state per input state, all under the same action.

Used by particle filters: given N current particles and one action, draw N next states (one per particle) in a single vectorized call.

The default implementation falls back to a per-state Python loop delegating to sample_next_state(). Native-backed envs (those whose state-transition kernel exposes batch_sample(states_array)) should override to avoid the loop.

Parameters:
  • states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of input particles.

  • action (int) – A single action to apply to every particle.

Returns:

np.ndarray of shape (N, *dim). For structured envs (Tiger strings, Pacman tuples): a list of length N.

Return type:

ndarray

sample_observation(next_state, action, n_samples=1)[source]

Sample one or more observations for (next_state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single observation. When n_samples > 1: an array-like of length n_samples.

Return type:

Any

Parameters:
step_info(state, action, next_state)[source]

Report tag status, hazard exposure and wall collisions for this step.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal step.

  • action (Any) – The action taken, or None on the terminal step.

  • next_state (Any) – The realised successor state, or None on the terminal step. Needed to tell a blocked move from a completed one.

Return type:

Dict[str, float]

Returns:

The per-step channels. recorded_step is a constant 1.0 so that summing it reproduces len(history.history), including the terminal bookkeeping step, which the historical episode-length count included.

Note

Nothing here reads the realised reward, which step_info is not given. tag_success_rate and average_failed_tag_attempts are defined in terms of it, so they stay in compute_metrics(). Recomputing the reward here is not an option: two of the reward models draw from np.random, so it would both return a different number and shift the RNG stream for every later transition.

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate next state under (state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate next states. Subclasses must implement.

Return type:

ndarray

Parameters:
class POMDPPlanners.environments.laser_tag_pomdp.ContinuousLaserTagPOMDP(discount_factor, name='ContinuousLaserTagPOMDP', grid_size=(11.0, 7.0), walls=None, robot_radius=0.3, opponent_radius=0.3, tag_radius=0.5, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, robot_transition_cov_matrix=array([[0.1, 0.], [0., 0.1]]), opponent_transition_cov_matrix=array([[0.05, 0.], [0., 0.05]]), evasion_speed=0.6, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, dangerous_area_hit_probability=1.0, is_dangerous_area_hit_terminal=False, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, opponent_policy=OpponentPolicy.EVADE)[source]

Bases: Environment

Continuous LaserTag POMDP with continuous [dx, dy, tag_flag] actions.

A pursuit-evasion problem in continuous 2-D space where a robot must navigate to tag an opponent. The robot receives noisy 8-direction laser range observations.

Stochasticity:

The dangerous-area penalty can be applied either deterministically (the default) or stochastically. When dangerous_area_hit_probability == 1.0 (default), the kernel’s deterministic deduction is preserved verbatim, matching legacy behavior. When dangerous_area_hit_probability < 1.0, the accumulated dangerous-area deduction is applied to the reward only with that probability per reward() call, producing a heavy-tailed return distribution suitable for benchmarking risk-sensitive planners (e.g. ICVaR-aware MCTS) against expected-value MCTS on the same env. Note that this makes reward(state, action) non-deterministic given a state-action pair, so any external caching that assumes deterministic rewards must be aware of this. transition_log_probability is unaffected.

Example

>>> import numpy as np
>>> np.random.seed(42)
>>>
>>> # Initialize environment
>>> env = ContinuousLaserTagPOMDP(discount_factor=0.95)
>>>
>>> # Get initial state
>>> initial_state = env.initial_state_dist().sample()[0]
>>>
>>> # Sample complete step
>>> action = np.array([1.0, 0.0, 0.0])
>>> next_state, observation, reward = env.sample_next_step(initial_state, action)
>>>
>>> # Check terminal condition
>>> env.is_terminal(initial_state)
False

Example

Risk-sensitive evaluation – a 10%-tail-risk environment suitable for benchmarking ICVaR-aware planners against expected-value MCTS:

>>> env = ContinuousLaserTagPOMDP(
...     discount_factor=0.95,
...     dangerous_area_penalty=150.0,
...     dangerous_area_hit_probability=0.1,
... )
Parameters:
  • discount_factor (float)

  • name (str)

  • grid_size (Tuple[float, float])

  • walls (Optional[List[Tuple[float, float, float, float]]])

  • robot_radius (float)

  • opponent_radius (float)

  • tag_radius (float)

  • tag_reward (float)

  • tag_penalty (float)

  • step_cost (float)

  • measurement_noise (float)

  • robot_transition_cov_matrix (np.ndarray)

  • opponent_transition_cov_matrix (np.ndarray)

  • evasion_speed (float)

  • dangerous_areas (Optional[List[Tuple[float, float]]])

  • dangerous_area_radius (float)

  • dangerous_area_penalty (float)

  • dangerous_area_hit_probability (float)

  • is_dangerous_area_hit_terminal (bool)

  • output_dir (Optional[Path])

  • debug (bool)

  • use_queue_logger (bool)

  • initial_state (Optional[np.ndarray])

  • opponent_policy (OpponentPolicy)

compute_metrics(histories)[source]

Compute all seven metrics, in declaration order.

Parameters:

histories (List[History]) – List of simulation histories.

Return type:

List[MetricValue]

Returns:

All seven metrics, in declaration order.

Raises:

ValueError – If histories is empty, or if an episode ran without being measured. See compute_metrics().

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

ContinuousLaserTagVisualizer

get_metric_names()[source]

Get names of environment-specific metrics.

This method returns the names of custom metrics that this environment computes in the compute_metrics() method. It enables users to discover what metrics are available for hyperparameter optimization.

Return type:

List[str]

Returns:

List of metric names that this environment produces. Derived from get_metric_specs(), so declaring a spec is enough; environments with a bespoke compute_metrics override this directly instead.

Note

Subclasses that override compute_metrics() should also override this method to return the names of metrics they produce. Use an Enum to ensure consistency between the names returned here and the names used in compute_metrics().

get_metric_specs()[source]

Declare the metrics derived from the per-step channels.

Return type:

List[StepInfoMetric]

Returns:

Specs for the five state-derived metrics, in enum order. The two reward-derived metrics are produced by compute_metrics().

hash_action(action)[source]

Return a hashable key consistent with action equality.

Used by tree-search planners to index action children of a belief node in O(1). The returned key MUST satisfy:

action_a == action_b   (per env's notion of equality)
==> hash_action(action_a) == hash_action(action_b)

Subclasses with non-hashable actions (e.g. np.ndarray) must override to return a hashable surrogate (tobytes() is the standard choice for ndarray actions, which mirrors the np.array_equal semantics used by the linear-scan fallback).

Parameters:

action (Any) – Action to hash.

Return type:

Hashable

Returns:

A hashable key derived from action.

hash_observation(observation)[source]

Return a hashable key consistent with is_equal_observation().

Used by tree-search planners to index belief children by observation in O(1). The returned key MUST satisfy the contract:

is_equal_observation(a, b) implies hash_observation(a) == hash_observation(b)
Parameters:

observation (Any) – Observation to hash.

Returns:

the observation itself when it is already hashable).

Return type:

Hashable

Raises:

NotImplementedError – If the observation is not hashable and the subclass has not provided an override. Subclasses with non-hashable observations (e.g. np.ndarray) MUST override.

initial_observation_dist()[source]

Get the initial observation distribution.

Return type:

Distribution

Returns:

Distribution over initial observations

Note

Subclasses must implement this method to define initial observations.

initial_state_dist()[source]

Get the initial state distribution.

Return type:

Distribution

Returns:

Distribution over initial states

Note

Subclasses must implement this method to define the starting distribution.

is_equal_observation(observation1, observation2)[source]

Check if two observations are equal.

Parameters:
  • observation1 (Any) – First observation to compare

  • observation2 (Any) – Second observation to compare

Return type:

bool

Returns:

True if observations are considered equal, False otherwise

Note

Subclasses must implement this method to define observation equality. This is particularly important for discrete observation spaces.

is_terminal(state)[source]

Check if a state is terminal.

Parameters:

state (ndarray) – State to check for terminal condition

Return type:

bool

Returns:

True if the state is terminal, False otherwise

Note

Subclasses must implement this method to define terminal conditions.

observation_log_probability(next_state, action, observations)[source]

Log-probability of each candidate observation under (next_state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate observations. Subclasses must implement.

Return type:

ndarray

Parameters:
observation_log_probability_per_state(next_states, action, observation)[source]

Log-probability of one observation under each candidate next-state.

Used by particle filters: given N candidate next-states and ONE observation, return N log-likelihoods.

The default implementation falls back to a per-state Python loop delegating to observation_log_probability(). Native-backed envs (those whose observation kernel exposes batch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.

Parameters:
  • next_states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of candidate next-states.

  • action (ndarray) – The action that was executed.

  • observation (Any) – A single observation.

Return type:

ndarray

Returns:

ndarray of shape (N,) with log-probabilities or log-PDFs.

observation_log_probability_single(next_state, action, observation)[source]

Scalar log-likelihood for one (next_state, observation) pair.

Per-state fast-path used by incremental belief updates (e.g. POMCPOW’s WeightedParticleBeliefStateUpdate.inplace_update()) to skip the per-call numpy setup overhead of the batched observation_log_probability() path on a singleton input.

The default falls back to the batched method with a one-element observations list. Envs with cheap scalar likelihoods (e.g. the 2-D Gaussian on Push or the cached-inverse-cov path on ContinuousLightDark) should override to skip array allocation.

Return type:

float

Parameters:
  • next_state (Any)

  • action (Any)

  • observation (Any)

reward(state, action, next_state=None)[source]

Calculate the immediate reward for a state-action(-next_state) tuple.

next_state is the realised post-transition state when known (e.g. threaded by sample_next_step()), allowing rewards that depend on stochastic transition outcomes to use the same draw as the trajectory instead of resampling. Subclasses whose reward is a pure function of (state, action) may ignore it; subclasses whose reward depends on the realised next state (collision penalties, win bonuses) should consume it when provided and fall back to drawing/computing one when None.

Parameters:
  • state (ndarray) – Current state.

  • action (ndarray) – Action executed from state.

  • next_state (Any) – Realised next state, or None if the caller did not pre-sample one. Defaults to None.

Return type:

float

Returns:

Immediate reward value.

Note

Subclasses must implement this method to define reward structure.

reward_batch(states, action, next_states=None)[source]

Calculate rewards for a batch of states given a single action.

Provides a loop-based default that subclasses can override with vectorized numpy implementations for better performance.

Parameters:
Return type:

ndarray

Returns:

1-D array of reward values with shape (N,).

property reward_requires_next_state: bool

Reward depends on the realised next_state iff hazard-terminal is on.

When enabled, the dangerous-area penalty is deterministic given the terminal slot set during the transition, so drivers must sample the transition first and thread the realised next_state into reward().

sample_next_state(state, action, n_samples=1)[source]

Sample one or more next states for (state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single next state of the env’s native type. When n_samples > 1: an array-like of length n_samples (numeric envs return np.ndarray of shape (n_samples, *dim); structured envs return List[T]).

Return type:

Any

Parameters:
sample_next_state_batch(states, action)[source]

Sample one next state per input state, all under the same action.

Used by particle filters: given N current particles and one action, draw N next states (one per particle) in a single vectorized call.

The default implementation falls back to a per-state Python loop delegating to sample_next_state(). Native-backed envs (those whose state-transition kernel exposes batch_sample(states_array)) should override to avoid the loop.

Parameters:
  • states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of input particles.

  • action (ndarray) – A single action to apply to every particle.

Returns:

np.ndarray of shape (N, *dim). For structured envs (Tiger strings, Pacman tuples): a list of length N.

Return type:

ndarray

sample_observation(next_state, action, n_samples=1)[source]

Sample one or more observations for (next_state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single observation. When n_samples > 1: an array-like of length n_samples.

Return type:

Any

Parameters:
simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]

Random rollout dispatched to native C++ via cont_simulate_rollout.

Pre-samples actions from action_sampler, packs them into a (N, 3) buffer, and runs the full discounted-return loop inside C++. Results are numerically identical to the Environment.simulate_random_rollout() Python fallback.

When dangerous_area_hit_probability < 1.0, falls back to the Python rollout: the native kernel applies the dangerous-area penalty deterministically per step, which contradicts the stochastic semantics; routing through Python reward() keeps the per-step Bernoulli intact.

Also falls back when dangerous_areas is non-empty: the C++ cont_simulate_rollout kernel scores the danger penalty against the pre-transition robot position, while the Python reward() path (post-fix) consumes the realised post-transition position. Until the C++ kernel is rebuilt this is the only correctness-preserving path for configs with danger areas.

Return type:

float

Parameters:
step_info(state, action, next_state)[source]

Report tag status and hazard exposure for this step.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal step.

  • action (Any) – Unused; every channel here is a property of the state.

  • next_state (Any) – Unused; each state is scored when it is recorded.

Return type:

Dict[str, float]

Returns:

The per-step channels. recorded_step is a constant 1.0 so that summing it reproduces len(history.history), terminal bookkeeping step included.

Note

tag_success_rate and average_failed_tag_attempts are defined in terms of the realised reward, which step_info is not given, so they stay in compute_metrics().

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate next state under (state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate next states. Subclasses must implement.

Return type:

ndarray

Parameters:
class POMDPPlanners.environments.laser_tag_pomdp.continuous_laser_tag_pomdp.ContinuousLaserTagPOMDPDiscreteActions(discount_factor, name='ContinuousLaserTagPOMDPDiscreteActions', grid_size=(11.0, 7.0), walls=None, robot_radius=0.3, opponent_radius=0.3, tag_radius=0.5, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, robot_transition_cov_matrix=array([[0.1, 0.], [0., 0.1]]), opponent_transition_cov_matrix=array([[0.05, 0.], [0., 0.05]]), evasion_speed=0.6, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, dangerous_area_hit_probability=1.0, is_dangerous_area_hit_terminal=False, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, opponent_policy=OpponentPolicy.EVADE)[source]

Bases: ContinuousLaserTagPOMDP, DiscreteActionsEnvironment

Continuous LaserTag POMDP with discrete string actions.

Actions: "up", "down", "right", "left", "tag".

Example

>>> import numpy as np
>>> np.random.seed(42)
>>>
>>> env = ContinuousLaserTagPOMDPDiscreteActions(discount_factor=0.95)
>>>
>>> initial_state = env.initial_state_dist().sample()[0]
>>> actions = env.get_actions()
>>>
>>> action = actions[0]
>>> next_state, observation, reward = env.sample_next_step(initial_state, action)
>>>
>>> env.is_terminal(initial_state)
False
Parameters:
  • discount_factor (float)

  • name (str)

  • grid_size (Tuple[float, float])

  • walls (Optional[List[Tuple[float, float, float, float]]])

  • robot_radius (float)

  • opponent_radius (float)

  • tag_radius (float)

  • tag_reward (float)

  • tag_penalty (float)

  • step_cost (float)

  • measurement_noise (float)

  • robot_transition_cov_matrix (np.ndarray)

  • opponent_transition_cov_matrix (np.ndarray)

  • evasion_speed (float)

  • dangerous_areas (Optional[List[Tuple[float, float]]])

  • dangerous_area_radius (float)

  • dangerous_area_penalty (float)

  • dangerous_area_hit_probability (float)

  • is_dangerous_area_hit_terminal (bool)

  • output_dir (Optional[Path])

  • debug (bool)

  • use_queue_logger (bool)

  • initial_state (Optional[np.ndarray])

  • opponent_policy (OpponentPolicy)

get_actions()[source]

Get all possible actions in the discrete action space.

Return type:

List[str]

Returns:

List containing all valid actions that can be executed

Note

Subclasses must implement this method to enumerate all possible actions. This is used by planning algorithms that need to iterate over actions.

hash_action(action)[source]

Return a hashable key consistent with action equality.

Used by tree-search planners to index action children of a belief node in O(1). The returned key MUST satisfy:

action_a == action_b   (per env's notion of equality)
==> hash_action(action_a) == hash_action(action_b)

Subclasses with non-hashable actions (e.g. np.ndarray) must override to return a hashable surrogate (tobytes() is the standard choice for ndarray actions, which mirrors the np.array_equal semantics used by the linear-scan fallback).

Parameters:

action (Any) – Action to hash.

Return type:

Hashable

Returns:

A hashable key derived from action.

observation_log_probability(next_state, action, observations)[source]

Log-probability of each candidate observation under (next_state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate observations. Subclasses must implement.

Return type:

ndarray

Parameters:
observation_log_probability_per_state(next_states, action, observation)[source]

Log-probability of one observation under each candidate next-state.

Used by particle filters: given N candidate next-states and ONE observation, return N log-likelihoods.

The default implementation falls back to a per-state Python loop delegating to observation_log_probability(). Native-backed envs (those whose observation kernel exposes batch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.

Parameters:
  • next_states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of candidate next-states.

  • action (Any) – The action that was executed.

  • observation (Any) – A single observation.

Return type:

ndarray

Returns:

ndarray of shape (N,) with log-probabilities or log-PDFs.

observation_log_probability_single(next_state, action, observation)[source]

Scalar log-likelihood for one (next_state, observation) pair.

Per-state fast-path used by incremental belief updates (e.g. POMCPOW’s WeightedParticleBeliefStateUpdate.inplace_update()) to skip the per-call numpy setup overhead of the batched observation_log_probability() path on a singleton input.

The default falls back to the batched method with a one-element observations list. Envs with cheap scalar likelihoods (e.g. the 2-D Gaussian on Push or the cached-inverse-cov path on ContinuousLightDark) should override to skip array allocation.

Return type:

float

Parameters:
  • next_state (Any)

  • action (Any)

  • observation (Any)

reward(state, action, next_state=None)[source]

Calculate the immediate reward for a state-action(-next_state) tuple.

next_state is the realised post-transition state when known (e.g. threaded by sample_next_step()), allowing rewards that depend on stochastic transition outcomes to use the same draw as the trajectory instead of resampling. Subclasses whose reward is a pure function of (state, action) may ignore it; subclasses whose reward depends on the realised next state (collision penalties, win bonuses) should consume it when provided and fall back to drawing/computing one when None.

Parameters:
  • state (ndarray) – Current state.

  • action (Any) – Action executed from state.

  • next_state (Any) – Realised next state, or None if the caller did not pre-sample one. Defaults to None.

Return type:

float

Returns:

Immediate reward value.

Note

Subclasses must implement this method to define reward structure.

reward_batch(states, action, next_states=None)[source]

Calculate rewards for a batch of states given a single action.

Provides a loop-based default that subclasses can override with vectorized numpy implementations for better performance.

Parameters:
  • states (Union[ndarray, Sequence[Any]]) – Sequence of states of length N.

  • action (Any) – Action executed from each state.

  • next_states (Union[ndarray, Sequence[Any], None]) – Optional realised next states (length N) threaded through to reward(). Defaults to None.

Return type:

ndarray

Returns:

1-D array of reward values with shape (N,).

sample_next_state(state, action, n_samples=1)[source]

Sample one or more next states for (state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single next state of the env’s native type. When n_samples > 1: an array-like of length n_samples (numeric envs return np.ndarray of shape (n_samples, *dim); structured envs return List[T]).

Return type:

Any

Parameters:
sample_next_state_batch(states, action)[source]

Sample one next state per input state, all under the same action.

Used by particle filters: given N current particles and one action, draw N next states (one per particle) in a single vectorized call.

The default implementation falls back to a per-state Python loop delegating to sample_next_state(). Native-backed envs (those whose state-transition kernel exposes batch_sample(states_array)) should override to avoid the loop.

Parameters:
  • states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of input particles.

  • action (Any) – A single action to apply to every particle.

Returns:

np.ndarray of shape (N, *dim). For structured envs (Tiger strings, Pacman tuples): a list of length N.

Return type:

ndarray

sample_observation(next_state, action, n_samples=1)[source]

Sample one or more observations for (next_state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single observation. When n_samples > 1: an array-like of length n_samples.

Return type:

Any

Parameters:
simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]

Random rollout dispatched to native C++ via cont_simulate_rollout.

Pre-samples actions from action_sampler, packs them into a (N, 3) buffer, and runs the full discounted-return loop inside C++. Results are numerically identical to the Environment.simulate_random_rollout() Python fallback.

When dangerous_area_hit_probability < 1.0, falls back to the Python rollout: the native kernel applies the dangerous-area penalty deterministically per step, which contradicts the stochastic semantics; routing through Python reward() keeps the per-step Bernoulli intact.

Also falls back when dangerous_areas is non-empty: the C++ cont_simulate_rollout kernel scores the danger penalty against the pre-transition robot position, while the Python reward() path (post-fix) consumes the realised post-transition position. Until the C++ kernel is rebuilt this is the only correctness-preserving path for configs with danger areas.

Return type:

float

Parameters:
transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate next state under (state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate next states. Subclasses must implement.

Return type:

ndarray

Parameters:

See also

  • Batched torch model: POMDPPlanners.environments.laser_tag_pomdp.laser_tag_vectorized_model.LaserTagVectorizedModel (grid variant) and POMDPPlanners.environments.laser_tag_pomdp.ContinuousLaserTagVectorizedModel (ContinuousLaserTagPOMDPDiscreteActions).

  • Base Environment Class — the full catalog and the environment interface.