Create a custom environment

A custom environment is a subclass of Environment. If the action set is a finite list, subclass DiscreteActionsEnvironment instead — it adds get_actions and lets the discrete-action planners enumerate.

What you must implement

The base class is a generative model, not a table: planners sample from it far more often than they ask for a probability, so the sampling methods are the ones that need to be fast.

Method

What it returns

initial_state_dist()

Distribution over start states.

initial_observation_dist()

Distribution over the observation before the first action.

sample_next_state(state, action, n_samples=1)

n_samples draws from \(T(\cdot \mid s, a)\).

sample_observation(next_state, action, n_samples=1)

n_samples draws from \(O(\cdot \mid s', a)\).

transition_log_probability(state, action, next_states)

Array of shape (N,) — log \(T(s'_i \mid s, a)\).

observation_log_probability(next_state, action, observations)

Array of shape (N,) — log \(O(o_i \mid s', a)\). This is what weights the particles in a belief update.

reward(state, action, next_state=None)

Scalar reward.

is_terminal(state)

Whether the episode has ended.

is_equal_observation(o1, o2)

Observation equality. Needed because observations are often numpy arrays, where == is elementwise.

hash_action(action)

A hashable key for an action, used to index search-tree children.

get_actions()

Only on DiscreteActionsEnvironment: the list of actions.

Traps worth knowing before you start

  • ``reward_range`` is only structurally validated. The constructor checks the tuple’s shape, not that your rewards fall inside it. The rollout check that catches a wrong range is a conformance test, and it runs only over the environments listed in ENV_BUILDERS in tests/test_environments/test_env_api_conformance.py — so you have to add yours there to get it. Until then, leave reward_range None rather than guessing.

  • ``config_id`` must not change between runs. It is derived from the attributes the instance stores, not from the constructor signature, and it is the cache key for simulation results. A constructor argument you never assign to self has no effect on it; an attribute you set after construction does. Anything that changes between runs — a path, a timestamp, a seed drawn at construction — silently splits or, worse, merges cached results.

  • Log-probabilities, not probabilities. Both *_log_probability methods return logs. Returning a probability produces beliefs that look plausible and are wrong.

A minimal working environment

A hidden coin, a 90 %-accurate peek that costs 1, and a guess that pays ±10:

import numpy as np

from POMDPPlanners.core.distributions import DiscreteDistribution
from POMDPPlanners.core.environment import (
    DiscreteActionsEnvironment,
    SpaceInfo,
    SpaceType,
)


class CoinFlipPOMDP(DiscreteActionsEnvironment):
    """Guess whether a hidden coin is heads, seeing a 90%-accurate peek."""

    STATES = ["heads", "tails"]
    ACTIONS = ["peek", "say_heads", "say_tails"]

    def __init__(self, discount_factor: float = 0.95, peek_accuracy: float = 0.9):
        super().__init__(
            discount_factor=discount_factor,
            name="CoinFlipPOMDP",
            space_info=SpaceInfo(
                action_space=SpaceType.DISCRETE,
                observation_space=SpaceType.DISCRETE,
            ),
            reward_range=(-10.0, 10.0),
        )
        self.peek_accuracy = peek_accuracy

    def get_actions(self):
        return list(self.ACTIONS)

    def initial_state_dist(self):
        return DiscreteDistribution(list(self.STATES), np.array([0.5, 0.5]))

    def initial_observation_dist(self):
        return DiscreteDistribution(["saw_nothing"], np.array([1.0]))

    # The coin does not change; only the agent's knowledge does.
    def sample_next_state(self, state, action, n_samples=1):
        return [state] * n_samples

    def transition_log_probability(self, state, action, next_states):
        return np.log(np.array([s == state for s in next_states], dtype=float))

    def _observation_probs(self, next_state, action):
        if action != "peek":
            return {"saw_nothing": 1.0}
        correct = "saw_heads" if next_state == "heads" else "saw_tails"
        wrong = "saw_tails" if next_state == "heads" else "saw_heads"
        return {correct: self.peek_accuracy, wrong: 1.0 - self.peek_accuracy}

    def sample_observation(self, next_state, action, n_samples=1):
        probs = self._observation_probs(next_state, action)
        values = list(probs)
        weights = np.array([probs[v] for v in values])
        return DiscreteDistribution(values, weights).sample(n_samples)

    def observation_log_probability(self, next_state, action, observations):
        probs = self._observation_probs(next_state, action)
        with np.errstate(divide="ignore"):
            return np.log(np.array([probs.get(o, 0.0) for o in observations], dtype=float))

    def is_equal_observation(self, observation1, observation2):
        return observation1 == observation2

    def hash_action(self, action):
        return action

    def reward(self, state, action, next_state=None):
        if action == "peek":
            return -1.0
        guessed = "heads" if action == "say_heads" else "tails"
        return 10.0 if guessed == state else -10.0

    def is_terminal(self, state):
        return False


env = CoinFlipPOMDP()
state = env.initial_state_dist().sample(1)[0]
observation = env.sample_observation(state, "peek")[0]

Metrics

An environment reports its own metrics through get_metric_specs and step_info. At minimum, report a task-completion rate and why each episode ended; without them a simulation batch can only tell you the mean return, which does not distinguish “solved slowly” from “failed safely”.

The base interface

class POMDPPlanners.core.environment.Environment(discount_factor, name, space_info, reward_range=None, output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: ABC

Abstract base class for POMDP environments.

This is the core abstract class that all POMDP environments must inherit from. It defines the essential interface for POMDP environments including state transitions, observations, rewards, and terminal conditions.

Note

This is an abstract base class and cannot be instantiated directly. Subclasses must implement all abstract methods.

Parameters:
discount_factor

Discount factor for future rewards

name

Environment identifier string

space_info

Information about action and observation space types

reward_range

Optional tuple containing (min_reward, max_reward)

output_dir

Optional directory for logging output

debug

Flag to enable debug logging

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.

property config_id: str

Generate a deterministic identifier based on environment configuration.

Note

Uses custom serialization logic (not centralized serialize_value) to ensure: - Deterministic dict key ordering for consistent hashing - Compact format without __type__ markers - Recursive handling of nested objects Changing this serialization format would invalidate all cached results.

encode_observation(observation)[source]

Encode a raw observation into the space the belief and planner use.

The base implementation is the identity: for environments whose raw and working observations coincide (the classic single-environment case), the observation is returned unchanged. A planner-side model whose working observation is an encoding of a richer raw observation (e.g. an image encoder the user supplies) overrides this to map the world’s raw observation into that encoded space.

This is the only method that consumes a raw observation; every other observation method (sample_observation(), observation_log_probability(), hash_observation(), is_equal_observation()) operates in the encoded space.

Parameters:

observation (Any) – The raw observation emitted by the world.

Return type:

Any

Returns:

The observation in the encoded space the belief and planner use.

episode_visualizer()[source]

Return the visualizer that shows this environment’s episodes.

Each environment shows its episodes in exactly one way. Environments implemented in this repo return a TraceVisualizer, whose trace a three.js scene replays in the browser. Environments that wrap an external simulator return a VideoVisualizer that saves the simulator’s own camera footage.

Return type:

Optional[EpisodeVisualizer]

Returns:

The visualizer, or None when this environment has no visualization. None is the default.

classmethod from_dict(data)[source]

Reconstruct environment from dictionary.

Dynamically imports the environment class and instantiates it with the saved parameters.

Parameters:

data (Dict[str, Any]) – Dictionary containing environment serialization data with keys: class, module, params, config_id

Return type:

Environment

Returns:

Reconstructed environment instance

Raises:
  • ImportError – If environment class cannot be imported

  • ValueError – If required data fields are missing

  • TypeError – If parameters are invalid for environment constructor

Example

>>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
>>> env = TigerPOMDP(discount_factor=0.95)
>>> env_dict = env.to_dict()
>>> reconstructed_env = Environment.from_dict(env_dict)
>>> reconstructed_env.discount_factor
0.95
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 metrics derived from this environment’s per-step channels.

Environments that report measurements through step_info() can declare how those channels become metrics here, and get the aggregation, averaging and confidence intervals from the default compute_metrics() instead of hand-rolling them.

Only declare a channel this environment actually emits on every step. A declared-but-unreported channel yields a metric that is silently dropped, which breaks the invariant that declared names match produced names.

Return type:

List[StepInfoMetric]

Returns:

The metric specifications to compute. Empty by default, so environments that do not use the per-step channel are unaffected.

abstractmethod 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.

abstractmethod 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.

abstractmethod 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.

abstractmethod 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.

abstractmethod is_terminal(state)[source]

Check if a state is terminal.

Parameters:

state (Any) – 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.

property logger: Logger

Get logger instance for this environment.

The logger is implemented as a property to maintain pickle compatibility, as logger objects cannot be pickled directly.

Returns:

Configured logger instance with hierarchical naming

abstractmethod 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:
  • next_state (Any)

  • action (Any)

  • observations (Any)

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)

abstractmethod 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 (Any) – 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,).

property reward_requires_next_state: bool

Whether reward() must be given the realised next_state.

Simulation and rollout drivers consult this hook to decide the order in which they sample the transition and compute the reward:

  • False (default): the reward is a pure function of (state, action). Drivers compute reward(state, action) before sampling the transition, preserving the historical RNG-draw interleaving so seeded trajectories stay bit-identical.

  • True: the reward depends on the realised post-transition state (e.g. draw-coupled hazard termination). Drivers sample the transition first, then call reward(state, action, next_state) with the realised next state so both consume the same draw.

Subclasses whose reward becomes next-state dependent (e.g. when a draw-coupled is_*_hit_terminal flag is enabled) must override this to return True only in that configuration; otherwise the default keeps flag-off behaviour bit-identical to today.

Returns:

True if reward() needs the realised next state, False otherwise.

abstractmethod 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:

Any

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 (Any) – 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]

abstractmethod 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:
  • next_state (Any)

  • action (Any)

  • n_samples (int)

step_info(state, action, next_state)[source]

Report auxiliary measurements for the transition just taken.

Simulation drivers call this once per recorded step and store the result on info, so the values travel back with the episode History.

This exists because a quantity may only be measurable at step time — an impact impulse read from a physics engine, a termination reason from a task manager — while compute_metrics() runs afterwards, in the parent process, on a different instance of this environment. Accumulating such a value on self during an episode is therefore silently lost under every multiprocess task manager; routing it through the returned mapping is what makes it survive.

Environments whose measurements are a pure function of the transition should implement this as such. Environments wrapping a live simulator may instead serve values cached during their own step, in which case the arguments are typically used only to assert the request matches the transition actually taken.

This is also called once more per terminated episode, for the terminal bookkeeping step, with action and next_state both None — that step records the final state, which no transition ever produces a successor for. Implementations must therefore tolerate None and report a neutral value for any channel that describes the transition rather than the state. Predicates written as float(action == <something>) already do this, since None matches nothing. Channels measured from state alone should still be reported, because a metric that counts every visited state needs the final one.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal bookkeeping 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.

Return type:

Dict[str, float]

Returns:

A flat mapping of channel name to scalar, e.g. {"success": 1.0, "impact": 12.4}. Values must be plain picklable scalars. The default implementation reports nothing.

Note

Name channels after the quantity and unit actually measured (e.g. "contact_impulse_ns"), not after a category. There is no shared cross-environment channel vocabulary on purpose: a name like "impact" could mean a force, an impulse, an energy or a count, and a shared name would imply a comparability that does not hold.

Warning

Implementations must be side-effect-free and must not consume randomness. This runs inside the episode loop, between the transition and the belief update, so a single np.random draw here shifts the stream for every subsequent transition and observation — silently changing seeded trajectories throughout the run, not just the metrics. Where a value would have to be resampled to be reported, do not report it.

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.

abstractmethod 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.core.environment.DiscreteActionsEnvironment(discount_factor, name, space_info, reward_range=None, output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: Environment

Abstract base class for POMDP environments with discrete action spaces.

This class extends the base Environment class with additional functionality specific to environments that have finite, enumerable action sets.

Note

This is an abstract base class and cannot be instantiated directly. Subclasses must implement all abstract methods from Environment plus the get_actions() method.

Parameters:
abstractmethod 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.

abstractmethod 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.

abstractmethod 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.

abstractmethod 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.

abstractmethod is_terminal(state)[source]

Check if a state is terminal.

Parameters:

state (Any) – 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.

abstractmethod 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 (Any) – 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.

Space types

SpaceInfo records the action and observation space types. There is no declared state-space type — a state is whatever the environment stores.

class POMDPPlanners.core.environment.SpaceType(*values)[source]

Enumeration for categorizing action and observation spaces.

This enum is used to classify the mathematical structure of action and observation spaces in POMDP environments.

DISCRETE

Finite, countable spaces (e.g., {0, 1, 2, …})

CONTINUOUS

Real-valued continuous spaces (e.g., R^n)

MIXED

Combination of discrete and continuous elements

CONTINUOUS = 'continuous'
DISCRETE = 'discrete'
MIXED = 'mixed'
class POMDPPlanners.core.environment.SpaceInfo(action_space, observation_space)[source]

Data class containing space type information for an environment.

This class encapsulates the space type classifications for both actions and observations in a POMDP environment.

Parameters:
action_space

The type of action space (discrete, continuous, or mixed)

observation_space

The type of observation space (discrete, continuous, or mixed)

Example

Creating space info for different environment types:

>>> # Discrete actions, continuous observations
>>> space_info = SpaceInfo(
...     action_space=SpaceType.DISCRETE,
...     observation_space=SpaceType.CONTINUOUS
... )
action_space: SpaceType
observation_space: SpaceType

See also