Light-Dark

ContinuousLightDarkPOMDP: 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.

ContinuousLightDarkPOMDP — continuous position, action and observation. The discrete variant has no replay.

Navigate to a goal in a world where your position sensor is less noisy within beacon_radius of a beacon than anywhere else. The shortest path is rarely the best one: going the long way through a beacon buys the localization needed to land on the goal.

It tests whether a planner values information: visiting a beacon is the only way to shrink position uncertainty. A planner optimizing expected reward under a point estimate drives straight at the goal and misses; one that reasons over beliefs detours.

Two variants ship, a continuous one and a discrete grid one, sharing the same reward shape. See Variants.

What the agent sees and does

Continuous variant

  • State — np.array([x, y]). Because is_obstacle_hit_terminal defaults to True, a third terminal-flag slot is appended, so states are 3-D by default.

  • Actions (continuous) — a displacement np.array([dx, dy]). The next state is state + action + N(0, state_transition_cov_matrix). No bound on the step is enforced.

  • Observations (continuous) — noisy position. The covariance is halved within beacon_radius of any beacon. Three models are selectable through observation_model_type: NORMAL_NOISE, NORMAL_NOISE_NO_OBS_IN_DARK and DISTANCE_BASED.

Discrete variant

  • State — np.array([x, y]) on an integer grid.

  • Actions (discrete) — "up", "down", "right", "left".

  • Observations (discrete) — a grid cell: the true cell with probability 1 - error, otherwise a neighbour. The error is observation_error_prob * 0.2 near a beacon and observation_error_prob away from one. Its observation_model_type is a different enum, with members NORMAL, NO_OBS_IN_DARK and DISTANCE_BASED.

Formal definition

Both variants share one geometry:

  • beacons \(\mathcal{Q}\);

  • obstacles \(\mathcal{O}\);

  • goal \(\mathbf{g}\);

  • start \(\mathbf{x}_0\);

  • a grid of side \(\mathcal{G}\) = grid_size.

Each variant is its own tuple.

Continuous variant

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

State space. The plane, plus a terminal slot when is_obstacle_hit_terminal (which defaults to True, so states are 3-D by default):

\[S = \mathbb{R}^2 \times \{0, 1\}, \qquad s = (\mathbf{p}, \top)\]

with \(\mathbf{p} = (x, y)\) the agent’s position and \(\top = 1\) once an obstacle hit has ended the episode. \(S\) is not restricted to the grid.

Action space. An unbounded displacement \(\mathbf{a} = (\mathrm{d}x, \mathrm{d}y)\) added to the position:

\[A = \mathbb{R}^2\]

Observation space. A position reading, plus the null symbol under the two models that can withhold one:

\[Z = \mathbb{R}^2 \quad (\texttt{NORMAL\_NOISE}), \qquad Z = \mathbb{R}^2 \cup \{\textsf{None}\} \quad (\text{otherwise})\]

Transition model. Additive Gaussian, with the commanded displacement as the mean:

\[T(\mathbf{p}' \mid \mathbf{p}, \mathbf{a}) = \mathcal{N}\big(\mathbf{p}';\; \mathbf{p} + \mathbf{a},\; \Sigma_T\big), \qquad \Sigma_T = \texttt{state\_transition\_cov\_matrix}\]

A terminal state is absorbing and draws nothing. When is_obstacle_hit_terminal is on, the transition also sets \(\top' = 1\) with probability obstacle_hit_probability when \(\mathbf{p}'\) lies within obstacle_radius of an obstacle in \(\mathcal{O}\).

Observation model. This is the environment’s whole point. It uses:

  • the distance to the nearest beacon,

    \[d(\mathbf{p}) = \min_{\mathbf{q} \in \mathcal{Q}} \lVert \mathbf{p} - \mathbf{q} \rVert_2\]
  • \(r_\mathcal{Q}\) = beacon_radius;

  • \(\Sigma_O\) = observation_cov_matrix.

Under NORMAL_NOISE (the default) the agent always sees its position, but the covariance is halved inside a beacon:

\[\begin{split}O(\mathbf{o} \mid \mathbf{p}', \cdot) = \mathcal{N}\big(\mathbf{o};\; \mathbf{p}',\; \Sigma_O(\mathbf{p}')\big), \qquad \Sigma_O(\mathbf{p}') = \begin{cases} \tfrac{1}{2}\Sigma_O & d(\mathbf{p}') < r_\mathcal{Q} \\ \Sigma_O & \text{otherwise} \end{cases}\end{split}\]

The other two models replace the reading in the dark with a null symbol instead of a wider one:

\[\begin{split}\texttt{NORMAL\_NOISE\_NO\_OBS\_IN\_DARK}: \quad \mathbf{o} = \begin{cases} \mathcal{N}(\mathbf{p}', \tfrac{1}{2}\Sigma_O) & d(\mathbf{p}') < r_\mathcal{Q} \\ \textsf{None} & \text{otherwise} \end{cases}\end{split}\]
\[\begin{split}\texttt{DISTANCE\_BASED}: \quad \mathbf{o} = \begin{cases} \textsf{None} & d(\mathbf{p}') > r_\mathcal{Q} \\ \mathcal{N}(\mathbf{p}', \tfrac{1}{2}\Sigma_O) & d(\mathbf{p}') < r_\mathcal{Q} \\ \mathcal{N}(\mathbf{p}', \Sigma_O) & \text{otherwise (on the boundary)} \end{cases}\end{split}\]

Note

That third branch is not a typo. The “near” test is a strict \(<\) and the “no reading” test is a strict \(>\), so a position exactly at \(d = r_\mathcal{Q}\) falls through to the wide covariance. The mismatch is preserved from the original model.

Reward function. A fuel cost plus a distance-to-goal shaping term, with one exclusive bonus or penalty on top:

\[\begin{split}R(s, \mathbf{a}, s') = -\texttt{fuel\_cost} - \lVert \mathbf{p}' - \mathbf{g} \rVert_2 + \begin{cases} +\texttt{goal\_reward} & \lVert \mathbf{p}' - \mathbf{g} \rVert_2 \leq r_{\mathbf{g}} \\ +\texttt{obstacle\_reward} & \text{hazard fires} \\ +\texttt{obstacle\_reward} & \mathbf{p}' \notin [0, \mathcal{G}]^2 \\ 0 & \text{otherwise} \end{cases}\end{split}\]

where \(r_{\mathbf{g}}\) = goal_state_radius and the hazard fires when \(\mathbf{p}'\) is within obstacle_radius of an obstacle in \(\mathcal{O}\) and a draw with probability obstacle_hit_probability succeeds (obstacle_reward is negative by default, so both middle branches are penalties). The shaping term is what a planner using a point estimate follows straight into the dark.

Note

The declared reward_range bounds in-grid states only, using the grid diagonal \(\sqrt{2}\,\mathcal{G}\) as the largest in-grid distance to the goal. A state can drift arbitrarily far outside the grid, and its reward can fall below that minimum. Those states sit outside the region the bound is defined over.

Initial belief. \(b_0(\mathbf{p}) = \mathbb{1}[\mathbf{p} = \mathbf{x}_0]\) — the start is known exactly. Uncertainty is produced entirely by the process noise as the agent moves, and removed only by visiting a beacon. A zero terminal slot is appended when is_obstacle_hit_terminal=True, and the initial observation is fixed at the placeholder value \(1.0\).

Discount. \(\gamma\) = discount_factor, required; the class has no default.

Terminal set.

\[S_T = \{s : \lVert \mathbf{p} - \mathbf{g} \rVert_2 \leq r_{\mathbf{g}}\} \;\cup\; \{s : \top = 1\}\]

with \(r_{\mathbf{g}}\) = goal_state_radius.

Discrete variant

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

State space. The agent’s cell \(\mathbf{p} \in \mathbb{Z}^2\), plus a terminal slot \(\top\) (\(1\) once an obstacle hit has ended the episode) when is_obstacle_hit_terminal=True:

\[S = \mathbb{Z}^2 \quad \text{or} \quad S = \mathbb{Z}^2 \times \{0, 1\}\]

Action space.

\[A = \{\textsf{up}, \textsf{down}, \textsf{right}, \textsf{left}\}\]

each a one-cell move:

  • up: \(y + 1\)

  • down: \(y - 1\)

  • right: \(x + 1\)

  • left: \(x - 1\)

Observation space. A grid cell, plus the null symbol under NO_OBS_IN_DARK and DISTANCE_BASED:

\[Z = \mathbb{Z}^2 \quad (\texttt{NORMAL}), \qquad Z = \mathbb{Z}^2 \cup \{\textsf{None}\} \quad (\text{otherwise})\]

Transition model. The commanded move is executed with probability \(1 - e_T\), and otherwise one of the other three fires, uniformly:

\[\begin{split}T(\mathbf{p}' \mid \mathbf{p}, a) = \begin{cases} 1 - e_T & \mathbf{p}' = \mathbf{p} + \Delta_a \\ e_T / 3 & \mathbf{p}' = \mathbf{p} + \Delta_{a'},\; a' \neq a \end{cases}\end{split}\]

with \(e_T\) = transition_error_prob. \(\Delta_a\) is the offset of move \(a\):

  • \(\Delta_{\textsf{up}} = (0, 1)\)

  • \(\Delta_{\textsf{down}} = (0, -1)\)

  • \(\Delta_{\textsf{right}} = (1, 0)\)

  • \(\Delta_{\textsf{left}} = (-1, 0)\)

There are no walls: the agent can step outside the grid, and pays for it through the reward.

Observation model. Five outcomes — the true cell, or one of the four neighbours:

\[\begin{split}O(\mathbf{o} \mid \mathbf{p}', \cdot) = \begin{cases} 1 - e(\mathbf{p}') & \mathbf{o} = \mathbf{p}' \\ e(\mathbf{p}') / 4 & \mathbf{o} = \mathbf{p}' \pm (1, 0) \text{ or } \mathbf{p}' \pm (0, 1) \end{cases}\end{split}\]

The beacon effect is a five-fold reduction in the error rate rather than the continuous variant’s halved covariance:

\[\begin{split}e(\mathbf{p}') = \begin{cases} 0.2 \cdot e_O & d(\mathbf{p}') < r_\mathcal{Q} \\ e_O & \text{otherwise} \end{cases}\end{split}\]

where:

  • \(e_O\) = observation_error_prob;

  • \(d(\mathbf{p}')\) is the Euclidean distance from \(\mathbf{p}'\) to the nearest beacon in \(\mathcal{Q}\);

  • \(r_\mathcal{Q}\) = beacon_radius.

Reward function. The same shape, with the goal and obstacle tests by exact cell equality rather than by radius, and the obstacle penalty gated by a Bernoulli:

\[\begin{split}R = \;&-\texttt{fuel\_cost} - \lVert \mathbf{p}' - \mathbf{g} \rVert_2 \\ &+ \begin{cases} +\texttt{goal\_reward} & \mathbf{p}' = \mathbf{g} \\ \texttt{obstacle\_reward} \cdot \mathrm{Bern}(\texttt{obstacle\_hit\_probability}) & \mathbf{p}' \in \mathcal{O} \\ +\texttt{obstacle\_reward} & \mathbf{p}' \notin [0, \mathcal{G}]^2 \\ 0 & \text{otherwise} \end{cases}\end{split}\]

The branches are exclusive, in that order. The Bernoulli makes reward non-deterministic in \((s, a)\); is_obstacle_hit_terminal=True moves the draw into the transition and removes that. This class declares no reward_range.

Initial belief. As in the continuous variant, the start is known exactly:

\[b_0(\mathbf{p}) = \mathbb{1}[\mathbf{p} = \mathbf{x}_0]\]

with a zero terminal slot appended when is_obstacle_hit_terminal=True, and the initial observation fixed at the placeholder value \(1.0\).

Discount. \(\gamma\) = discount_factor, required; the class has no default.

Terminal set. The goal cell, plus either every obstacle cell (the default, is_obstacle_hit_terminal=False) or only the states whose terminal slot the hazard draw set (True):

\[\begin{split}S_T = \{s : \mathbf{p} = \mathbf{g}\} \;\cup\; \begin{cases} \{s : \mathbf{p} \in \mathcal{O}\} & \texttt{is\_obstacle\_hit\_terminal=False} \\ \{s : \top = 1\} & \texttt{is\_obstacle\_hit\_terminal=True} \end{cases}\end{split}\]

Rewards

Both variants start from -fuel_cost - ||next_state - goal|| and then follow an ordered chain — the first branch that matches wins, so the terms never stack:

base = -fuel_cost - ||next_state - goal||

inside the goal radius   ->  base + goal_reward
else on an obstacle      ->  base            (the hazard penalty is applied
                                              separately, via the hazard draw)
else outside the grid    ->  base + obstacle_reward
otherwise                ->  base

Defaults:

  • fuel_cost=2.0

  • goal_reward=10.0

  • obstacle_reward=-10.0

  • obstacle_hit_probability=0.2

Note

A step that leaves the grid can pay less than the declared reward_range minimum on the continuous variant. This is known, documented in the source, and covered by a strict xfail test — do not treat it as a new bug.

Key settings

Argument

Default

What it changes

grid_size

11

World extent.

beacons

9 points on a 3×3 lattice

Where observation noise is lower. Removing beacons makes the problem harder.

start_state / goal_state

[0, 5] / [10, 5]

goal_state_radius (continuous only)

1.5

How precisely you must arrive. Shrink it to force a beacon detour. The discrete variant has no such argument — it terminates on exact cell equality with goal_state.

obstacles

[(3, 7), (5, 5)]

state_transition_cov_matrix

np.eye(2) * 0.05

Motion noise (continuous variant).

observation_cov_matrix

np.eye(2) * 0.05

Sensor noise away from a beacon (continuous variant).

is_obstacle_hit_terminal

True (continuous), False (discrete)

On the continuous variant, whether an obstacle ends the episode. On the discrete variant it chooses which termination rule applies, not whether: False is the legacy behaviour where obstacles are always terminal, True makes them Bernoulli-terminal through the hazard draw and adds the terminal slot.

An episode ends at the goal — inside goal_state_radius on the continuous variant, on the exact cell on the discrete one — or on an obstacle hit under the rule above. Leaving the grid is penalized but not terminal.

Variants

There is also ContinuousLightDarkPOMDPDiscreteActions: the continuous world with the four discrete moves, for planners that need a finite action set. Note its noise defaults differ — np.eye(2) rather than np.eye(2) * 0.05.

Can I use?

ContinuousLightDarkPOMDP

Discrete

Continuous

State

❌

✔️

Action

❌

✔️

Observation

❌

✔️

ContinuousLightDarkPOMDPDiscreteActions

Discrete

Continuous

State

❌

✔️

Action

✔️

❌

Observation

❌

✔️

DiscreteLightDarkPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

ContinuousLightDarkPOMDP

ContinuousLightDarkPOMDPDiscreteActions

DiscreteLightDarkPOMDP

Native C++ backend

✔️

✔️

✔️

Vectorized (torch) model

✔️ ContinuousLightDarkVectorizedModel (is_obstacle_hit_terminal=False, NORMAL_NOISE, CONSTANT_HAZARD_PENALTY only)

✔️ ContinuousLightDarkVectorizedModel (is_obstacle_hit_terminal=False, NORMAL_NOISE, CONSTANT_HAZARD_PENALTY only)

✔️ DiscreteLightDarkVectorizedModel (is_obstacle_hit_terminal=False, NORMAL only)

In the get_environment registry

✔️

✔️

✔️

Optional dependencies

None

None

None

Example

import numpy as np

from POMDPPlanners.environments.light_dark_pomdp.continuous_light_dark_pomdp import (
    ContinuousLightDarkPOMDP,
)

env = ContinuousLightDarkPOMDP(discount_factor=0.95)

state = env.initial_state_dist().sample(1)[0]
step_right = np.array([1.0, 0.0])
next_state = env.sample_next_state(state, step_right)
observation = env.sample_observation(next_state, step_right)
print(state[:2], "->", next_state[:2], "seen as", observation)

Parameters

class POMDPPlanners.environments.light_dark_pomdp.continuous_light_dark_pomdp.ContinuousLightDarkPOMDP(discount_factor, name='ContinuousLightDarkPOMDP', state_transition_cov_matrix=array([[0.05, 0.], [0., 0.05]]), observation_cov_matrix=array([[0.05, 0.], [0., 0.05]]), beacons=[(0, 0), (0, 5), (0, 10), (5, 0), (5, 5), (5, 10), (10, 0), (10, 5), (10, 10)], goal_state=array([10, 5]), start_state=array([0, 5]), obstacles=[(3, 7), (5, 5)], obstacle_hit_probability=0.2, obstacle_reward=-10.0, goal_reward=10.0, fuel_cost=2.0, grid_size=11, goal_state_radius=1.5, beacon_radius=1.0, obstacle_radius=1.5, reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, observation_model_type=ObservationModelType.NORMAL_NOISE, penalty_decay=1.0, is_obstacle_hit_terminal=True)[source]

Bases: BaseLightDarkPOMDP

Continuous Light-Dark POMDP environment with continuous actions.

This environment extends the base Light-Dark problem to continuous 2D space with continuous action vectors. The agent navigates toward a goal while dealing with position-dependent observation noise and optional obstacles.

Key features: - Continuous 2D state and action spaces - Light beacons reduce observation noise when nearby - Multiple observation models available (normal noise, normal noise with no observation in dark) - Multiple reward models available (standard, decaying hit probability, high-variance states) - Optional obstacles with configurable hit penalties - Terminal conditions for goal reaching, obstacle hits, and boundary violations

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = ContinuousLightDarkPOMDP(
...     discount_factor=0.95,
...     goal_state=np.array([10, 5]),
...     start_state=np.array([0, 5])
... )
>>>
>>> # Get initial state
>>> initial_state = env.initial_state_dist().sample()[0]
>>>
>>> # Sample complete step (action must be provided based on environment type)
>>> action = np.array([1.0, 0.0])  # Move right
>>> next_state, observation, reward = env.sample_next_step(initial_state, action)
>>>
>>> # Check terminal condition
>>> env.is_terminal(initial_state)
False
Parameters:
compute_metrics(histories)[source]

Compute environment-specific metrics from episode histories.

The default implementation aggregates the per-step channels reported by step_info() according to get_metric_specs(). Subclasses with metrics that are not expressible as a per-step channel (for example ones needing cross-step reasoning) override this instead.

Parameters:

histories (List[History]) – List of episode histories to analyze

Return type:

List[MetricValue]

Returns:

List of computed metrics with confidence intervals

Raises:

ValueError – If histories is empty — a metric over no episodes is an average over nothing, so any value reported for it is invented. Also if this environment declares metric specs and any episode recorded transition steps while carrying none of the declared channels — a history produced before the per-step channel existed, or by a runner that does not call step_info(). Scoring those would report every metric as zero rather than as unmeasured.

get_metric_names()[source]

Get names of Continuous Light-Dark POMDP specific metrics.

Returns:

task_completion_rate, collision_rate, average_collisions, out_of_grid_rate, and average_high_variance_steps

Return type:

List[str]

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_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_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 the flag is on.

When enabled, the hazard penalty is deterministic given the terminal slot set during the transition, so drivers sample the transition first and pass the realised next_state to 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:

ndarray

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:
to_dict()[source]

Serialize environment to dictionary format.

Extracts environment class information and constructor parameters to enable JSON serialization and reconstruction.

Returns:

  • class: Full class path (module.ClassName)

  • module: Module name

  • params: Constructor parameters

  • config_id: Deterministic configuration identifier

Return type:

Dict[str, Any]

Example

>>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
>>> env = TigerPOMDP(discount_factor=0.95)
>>> env_dict = env.to_dict()
>>> 'class' in env_dict and 'params' in env_dict
True

Note

Uses centralized serialization system with registered SpaceInfo handler.

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.light_dark_pomdp.continuous_light_dark_pomdp.ContinuousLightDarkPOMDPDiscreteActions(discount_factor, state_transition_cov_matrix=array([[1., 0.], [0., 1.]]), observation_cov_matrix=array([[1., 0.], [0., 1.]]), obstacle_hit_probability=0.2, obstacle_reward=-10.0, goal_reward=10.0, fuel_cost=2.0, grid_size=11, goal_state_radius=1.5, beacon_radius=1.0, obstacle_radius=1.5, name='ContinuousLightDarkPOMDPDiscreteActions', beacons=[(0, 0), (0, 5), (0, 10), (5, 0), (5, 5), (5, 10), (10, 0), (10, 5), (10, 10)], goal_state=array([10, 5]), start_state=array([0, 5]), obstacles=[(3, 7), (5, 5)], reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, observation_model_type=ObservationModelType.NORMAL_NOISE, penalty_decay=1.0, is_obstacle_hit_terminal=True)[source]

Bases: ContinuousLightDarkPOMDP, DiscreteActionsEnvironment

Continuous Light-Dark POMDP environment with discrete actions.

This variant of the Continuous Light-Dark POMDP uses discrete directional actions (up, down, left, right) instead of continuous action vectors. The continuous state space and observation model are preserved.

Actions are mapped to unit vectors: - “up”: [0, 1] - “down”: [0, -1] - “right”: [1, 0] - “left”: [-1, 0]

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = ContinuousLightDarkPOMDPDiscreteActions(
...     discount_factor=0.95,
...     goal_state=np.array([10, 5]),
...     start_state=np.array([0, 5])
... )
>>>
>>> # 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
Parameters:
get_actions()[source]

Get all possible actions in the discrete action space.

Return type:

List[Any]

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.

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:

ndarray

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 via native C++.

The variant-aware _native.simulate_rollout kernel covers all three reward models in expectation (the rollout RNG draws come from the module-level C++ RNG and match the Python reward models sample-mean, not bit-exact), so no variant gate is required here. The Python fallback is retained only for the realised-position correctness case below.

Parameters:
  • state (Any) – Current 2-D position [x, y].

  • action_sampler (Any) – Object with a sample() method; used only for the Python fallback path. On the native path, action indices are pre-drawn inside this method.

  • max_depth (int) – Maximum rollout depth.

  • discount_factor (float) – Per-step discount factor.

  • depth (int) – Depth already consumed by the search tree. Defaults to 0.

Return type:

float

Returns:

Discounted sum of immediate rewards along the sampled trajectory.

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.light_dark_pomdp.discrete_light_dark_pomdp.DiscreteLightDarkPOMDP(discount_factor, name='DiscreteLightDarkPOMDP', transition_error_prob=0.05, observation_error_prob=0.05, beacons=[(0, 0), (0, 5), (0, 10), (5, 0), (5, 5), (5, 10), (10, 0), (10, 5), (10, 10)], goal_state=array([10, 5]), start_state=array([0, 5]), obstacles=[(3, 7), (5, 5)], obstacle_hit_probability=0.2, obstacle_reward=-10.0, goal_reward=10.0, beacon_radius=1.0, fuel_cost=2.0, grid_size=11, is_stochastic_reward=True, observation_model_type=ObservationModelType.NORMAL, is_obstacle_hit_terminal=False)[source]

Bases: BaseLightDarkPOMDPDiscreteActions, DiscreteActionsEnvironment

Discrete Light-Dark POMDP Environment for Robot Navigation with Observation Uncertainty.

This environment implements a discretized version of the classic Light-Dark POMDP problem, where a robot must navigate from a start position to a goal position in a grid world with beacons and obstacles. The key challenge is that the robot’s observation quality depends on its distance from beacons - closer to beacons means more accurate observations.

Problem Description: The robot operates in a discrete grid world where it can move in four cardinal directions. The environment includes: - Beacons: Fixed positions that provide location reference with varying accuracy - Obstacles: Grid cells that incur penalties when hit - Goal: Target position that provides high reward when reached - Observation uncertainty: Decreases with proximity to beacons (light areas)

Key Features: - Discrete state space: Robot positions are restricted to grid cells - Discrete action space: North, South, East, West movements - Multiple observation models available (normal, no observation in dark) - Distance-dependent observation accuracy: Closer to beacons = better observations - Stochastic transitions: Actions may fail with configurable probability - Obstacle avoidance: Penalties for hitting obstacles during navigation - Configurable environment parameters: Grid size, beacon positions, obstacles

State Space: - 2D grid coordinates (x, y) representing robot position - Bounded by grid_size parameter (default: 11x11 grid)

Action Space: - Discrete actions: [‘North’, ‘South’, ‘East’, ‘West’] - Each action moves robot one grid cell in the corresponding direction - Boundary conditions: Actions that would move outside grid are blocked

Observation Space: - Discrete observations based on beacon proximity and noise - Observation accuracy improves with proximity to beacons - Stochastic observation errors controlled by observation_error_prob

Reward Structure: - Goal reward: Large positive reward for reaching the goal state - Obstacle penalty: Negative reward for hitting obstacles - Fuel cost: Small negative reward for each movement action - Distance-based penalties: Encourage efficient navigation

Parameters:
transition_error_prob

Probability that an action fails (results in different movement)

observation_error_prob

Probability of observation noise/error

is_stochastic_reward

Whether rewards include stochastic components

beacons

List of (x, y) beacon positions that provide navigation references

goal_state

Target position (x, y) that robot should reach

start_state

Initial robot position (x, y)

obstacles

List of (x, y) obstacle positions to avoid

grid_size

Dimension of the square grid world

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = DiscreteLightDarkPOMDP(
...     discount_factor=0.95,
...     transition_error_prob=0.1,
...     observation_error_prob=0.15,
...     beacons=[(1, 1), (2, 2)],
...     grid_size=11
... )
>>>
>>> # 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

References: - Platt, R., et al. “Belief space planning assuming maximum likelihood observations.” (2010) - Kurniawati, H., et al. “SARSOP: Efficient point-based POMDP planning by approximating optimally reachable belief spaces.” (2008) - Light-Dark domain: Classic POMDP benchmark for testing observation uncertainty

compute_metrics(histories)[source]

Compute environment-specific metrics from episode histories.

The default implementation aggregates the per-step channels reported by step_info() according to get_metric_specs(). Subclasses with metrics that are not expressible as a per-step channel (for example ones needing cross-step reasoning) override this instead.

Parameters:

histories (List[History]) – List of episode histories to analyze

Return type:

List[MetricValue]

Returns:

List of computed metrics with confidence intervals

Raises:

ValueError – If histories is empty — a metric over no episodes is an average over nothing, so any value reported for it is invented. Also if this environment declares metric specs and any episode recorded transition steps while carrying none of the declared channels — a history produced before the per-step channel existed, or by a runner that does not call step_info(). Scoring those would report every metric as zero rather than as unmeasured.

get_metric_names()[source]

Get names of Discrete Light-Dark POMDP specific metrics.

Returns:

task_completion_rate, collision_rate, average_collisions, out_of_grid_rate, and average_high_variance_steps

Return type:

List[str]

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_state_dist()[source]

Get the initial state distribution.

Returns:

Distribution over initial states

Note

Subclasses must implement this method to define the starting distribution.

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 (Union[ndarray, Sequence[Any]]) – A sequence (length N) or ndarray of shape (N, *dim) of candidate next-states.

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

  • observation (ndarray) – 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(-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 (str) – 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,).

property reward_requires_next_state: bool

Reward depends on the realised next_state iff the flag is on.

When enabled, the obstacle penalty is deterministic given the terminal slot drawn during the transition, so drivers sample the transition first and pass the realised next_state to 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 (Union[ndarray, Sequence[Any]]) – A sequence (length N) or ndarray of shape (N, *dim) of input particles.

  • action (str) – 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_next_step(state, action)[source]

Sample a complete state transition step.

This convenience method combines state transition, observation generation, and reward calculation in a single operation.

Parameters:
  • state (ndarray) – Current state

  • action (Any) – Action to execute

Returns:

  • next_state: Sampled next state

  • next_observation: Sampled observation

  • reward: Immediate reward

Return type:

Tuple[Any, Any, float]

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 via native C++.

Pre-draws the per-step action indices on the Python side (so the action_sampler interaction stays observable for tests / hooks) and forwards to the native discrete rollout kernel. The kernel uses the module-level C++ RNG for the per-step obstacle-hit and transition-error draws.

Falls back to the base-class Python loop when the env is configured for a non-NORMAL observation model only if the rollout would otherwise short-circuit at the wrong place — actually rollout reward and dynamics are independent of the observation model, so the native path is safe for all observation models.

Parameters:
  • state (Any) – Current 2-D position [x, y].

  • action_sampler (Any) – Object with a sample() method; used only for the Python fallback path. On the native path, action indices are pre-drawn via np.random.randint.

  • max_depth (int) – Maximum rollout depth.

  • discount_factor (float) – Per-step discount factor.

  • depth (int) – Depth already consumed by the search tree. Defaults to 0.

Return type:

float

Returns:

Discounted sum of immediate rewards along the sampled trajectory.

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 models, which VOPP plans on. Each raises NotImplementedError on a configuration it does not implement:

    • POMDPPlanners.environments.light_dark_pomdp.continuous_light_dark_vectorized_model.ContinuousLightDarkVectorizedModel serves both continuous classes. It needs is_obstacle_hit_terminal=False, because it keeps 2-D states and has no terminal slot; that is not the continuous default. It also needs the NORMAL_NOISE observation model and the CONSTANT_HAZARD_PENALTY reward model.

    • POMDPPlanners.environments.light_dark_pomdp.discrete_light_dark_vectorized_model.DiscreteLightDarkVectorizedModel serves DiscreteLightDarkPOMDP. It needs is_obstacle_hit_terminal=False (the discrete default), for the same reason, and the NORMAL observation model: NO_OBS_IN_DARK and DISTANCE_BASED emit the string "None" away from beacons, which its [N, 2] observation tensor cannot hold.

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