Base Environment Class
An environment defines the problem a planner has to solve: what the hidden state
is, what the agent may do, what it gets to see, and what it is paid. Every
environment in the package subclasses
Environment, so any planner can run on
any of them. Pick one from the catalog below, then read its page for the
settings and the reward numbers.
Creating an environment
Construct an environment directly from its class, or by name through the registry. The registry exists so a configuration file can name an environment as a string.
from POMDPPlanners.environments import get_environment
from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
env = TigerPOMDP(discount_factor=0.95)
same_env = get_environment("TigerPOMDP", discount_factor=0.95)
Note
get_environment covers only the classes in ENVIRONMENT_REGISTRY:
In the registry:
ChicheckInvadersPOMDPandFirefightingPOMDP, among others.Import directly:
BattleshipPOMDPandSnakePOMDP.Not in the registry, import directly:
ContinuousPushPOMDP,ContinuousPushPOMDPDiscreteActionsand the realistic worlds (CARLA, Isaac Lab, nuPlan, Racetrack).
Environment catalog
“State” is not a declared property of an environment — SpaceInfo records only the action and
observation space types. The state column below describes what the code
stores.
A world and its variants share one page:
Maze covers the discrete, continuous and T-maze versions.
Light-Dark, Push and LaserTag each cover their continuous and discrete-action forms.
Realistic and experimental worlds covers Racetrack, CARLA, Isaac Lab and nuPlan together.
The Guide column says which page to open for a given class.
Environment |
Purpose |
State |
Actions |
Observations |
Extra dependency |
Guide |
|---|---|---|---|---|---|---|
|
Decide which door hides the tiger from noisy listening. |
discrete label |
discrete |
discrete |
none |
|
|
Sample good rocks with a distance-degraded sensor, then exit east. |
vector |
discrete |
discrete |
none |
|
|
Find every cell of a hidden fleet with exact hit/miss probes. |
occupancy and probe flags |
discrete |
discrete |
none |
|
|
Two teams, two flags: steal theirs and get home without being tagged. |
|
discrete |
continuous |
none |
|
|
Shoot down a diving flock seen through a split camera/radar reading. |
|
discrete |
discrete |
none |
|
|
Put out a wind-driven grid fire with several partially sighted firefighters. |
|
discrete |
discrete |
none |
|
|
Grow the snake to a target length while the food stays hidden. |
|
discrete |
discrete |
none |
|
|
Clear every pellet while dodging noisily-observed ghosts. |
vector (pac, ghosts, pellets) |
discrete |
discrete |
none |
|
|
Reach a goal on a grid, detouring through beacons to localize. |
grid position |
discrete |
discrete |
none |
|
|
The same trade-off in continuous 2-D. |
|
continuous |
continuous |
none |
|
|
The continuous Light-Dark world with four discrete moves. |
|
discrete |
continuous |
none |
|
|
Remember a cue while navigating a generated grid maze. |
|
discrete |
discrete |
none |
|
|
Navigate the same maze with bounded displacements. |
|
continuous |
discrete |
none |
|
|
Remember a cue until choosing an arm of a T corridor. |
|
discrete |
discrete |
none |
|
|
Balance a pole seeing only noisy sensor readings. |
|
discrete |
continuous |
none |
|
|
Push an object onto a target corner of a grid. |
|
discrete |
continuous |
none |
|
|
The same task with a circular robot and free 2-D pushes. |
|
continuous |
continuous |
none |
|
|
The continuous Push world with four discrete moves. |
|
discrete |
continuous |
none |
|
|
Corner an evading opponent on a walled grid and tag it. |
|
discrete |
continuous |
none |
|
|
The same pursuit in continuous space. |
|
continuous |
continuous |
none |
|
|
The continuous LaserTag world with five discrete actions. |
|
discrete |
continuous |
none |
|
|
Move fast while staying under a velocity safety limit. |
|
discrete |
continuous |
none |
|
|
Two states, perfect observations — a debugging baseline. |
discrete label |
discrete |
discrete |
none |
|
|
Build momentum up a hill from noisy readings. |
|
discrete |
continuous |
none |
|
|
A matched MDP/POMDP pair on one track, to isolate partial observability. |
HighwayEnv vehicle state |
discrete |
continuous |
|
|
|
Urban driving against a running CARLA server. |
ego, agent, light and goal slots |
discrete |
dict of 5 sensors |
CARLA server |
|
|
Any registered |
physics state vector |
configurable |
configurable |
Isaac Sim |
|
|
Closed-loop driving on recorded nuPlan scenarios. |
ego, agent and light slots |
discrete |
|
|
The Environment interface
A planner talks to an environment only through the methods below. Write a new environment against them and every planner in the package can run on it; see Create a custom environment for a worked example.
Constructor. Environment.__init__ takes:
discount_factor— discount for future rewards, in \((0, 1]\).name— the environment’s identifier, used in logs and results.space_info— aSpaceInfonaming the action and observation space types (see below).reward_range— optional(min_reward, max_reward). It is checked on construction: two numbers, no NaN, and min no larger than max.output_dir,debug,use_queue_logger— logging options.
Methods every environment must implement. These are abstract on the base class:
sample_next_state(state, action, n_samples=1)— draw next states.sample_observation(next_state, action, n_samples=1)— draw observations. The observation is conditioned on the state after the action.transition_log_probability(state, action, next_states)andobservation_log_probability(next_state, action, observations)— log probabilities, one per candidate. Particle beliefs reweight with these.reward(state, action, next_state=None)— the immediate reward.next_stateis passed when the caller already drew it, so a reward that depends on the outcome uses the same draw as the trajectory.is_terminal(state)— whether the episode ends instate.initial_state_dist()andinitial_observation_dist()— where an episode starts.is_equal_observation(observation1, observation2)— observation equality.hash_action(action)— a hashable key for an action. Tree planners index action children by this key.
With n_samples=1 the two samplers return the value itself, not a list of
one.
Methods with a default. Override them when the default is too slow or does not fit:
hash_observation— a hashable key consistent withis_equal_observation. The default returns the observation itself, so an environment withnp.ndarrayobservations must override it.sample_next_state_batch,observation_log_probability_per_stateandreward_batch— batched forms used by particle filters. The defaults loop in Python over the single-state methods.sample_next_step(state, action)— draws the next state and observation and computes the reward in one call.step_infoandget_metric_specs— the per-step measurements and the metrics built from them. See Create a custom environment for what every environment should report.episode_visualizer()— how this environment’s episodes are shown, orNone.
Discrete actions. DiscreteActionsEnvironment adds one abstract method,
get_actions(), which lists every action. Planners that loop over actions,
such as POMCP, need it.
Configuration, equality and caching. config_id is a deterministic
identifier built from the environment’s public attributes; private attributes,
loggers and bound methods are skipped. Two environments of the same class with
the same public attributes compare equal and hash equal. The simulation cache
keys finished episodes on this identifier, so changing an attribute gives a
new cache entry instead of reusing results computed under the old value.
Environment generators. EnvironmentGenerator is a factory base
class with one abstract method, generate_environment(). Use it to produce
environments with randomized parameters.
Space types
SpaceInfo holds two SpaceType values: action_space and
observation_space. SpaceType is one of DISCRETE (a finite,
countable set), CONTINUOUS (real-valued) or MIXED (both). Some
planners read space_info to decide how to treat actions; the ICVaR planners,
for example, branch on whether the action space is discrete. There is no
state-space type — a state is whatever the environment stores.
The 3D episode viewer
Most environment pages open with a 3D replay of one recorded episode, planned
by PFT-DPW. The page embeds it with the .. episode-viewer:: directive, which
reads a trace JSON written by the environment’s TraceVisualizer. The
traces live in docs/environments/traces/ and are regenerated by
scripts/generate_docs_traces.py.
The replay loads its trace with a web request, and a browser will not let a
file:// page do that. Serve the built docs over HTTP to see it:
python -m http.server -d docs/_build/html
Example
from POMDPPlanners.core.environment import SpaceType
from POMDPPlanners.environments import get_environment
from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
env = TigerPOMDP(discount_factor=0.95)
same_env = get_environment("TigerPOMDP", discount_factor=0.95)
# Same class and same configuration: equal, with the same hash.
assert env == same_env
assert hash(env) == hash(same_env)
assert env.config_id == same_env.config_id
assert env.space_info.action_space == SpaceType.DISCRETE
print(env.get_actions())
Parameters
- class POMDPPlanners.core.environment.Environment(discount_factor, name, space_info, reward_range=None, output_dir=None, debug=False, use_queue_logger=False)[source]
Bases:
ABCAbstract 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 toget_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:
- Returns:
List of computed metrics with confidence intervals
- Raises:
ValueError – If
historiesis 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 callstep_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.
- 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 aVideoVisualizerthat saves the simulator’s own camera footage.- Return type:
- Returns:
The visualizer, or
Nonewhen this environment has no visualization.Noneis 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:
- 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:
- Returns:
List of metric names that this environment produces. Derived from
get_metric_specs(), so declaring a spec is enough; environments with a bespokecompute_metricsoverride 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 defaultcompute_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:
- 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 thenp.array_equalsemantics used by the linear-scan fallback).
- 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:
- 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:
- 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:
- 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:
- Return type:
- 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:
- 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.ndarrayof shape(N,)where N is the number of candidate observations. Subclasses must implement.
- 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 exposesbatch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.
- 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 batchedobservation_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.
- abstractmethod reward(state, action, next_state=None)[source]
Calculate the immediate reward for a state-action(-next_state) tuple.
next_stateis the realised post-transition state when known (e.g. threaded bysample_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 whenNone.- Parameters:
- Return type:
- 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:
- Returns:
1-D array of reward values with shape
(N,).
- property reward_requires_next_state: bool
Whether
reward()must be given the realisednext_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 computereward(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 callreward(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_terminalflag is enabled) must override this to returnTrueonly in that configuration; otherwise the default keeps flag-off behaviour bit-identical to today.- Returns:
Trueifreward()needs the realised next state,Falseotherwise.
- 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.
- 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 exposesbatch_sample(states_array)) should override to avoid the loop.
- 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.
- 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.
- 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 episodeHistory.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 onselfduring 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
actionandnext_statebothNone— that step records the final state, which no transition ever produces a successor for. Implementations must therefore tolerateNoneand report a neutral value for any channel that describes the transition rather than the state. Predicates written asfloat(action == <something>)already do this, sinceNonematches nothing. Channels measured fromstatealone should still be reported, because a metric that counts every visited state needs the final one.- Parameters:
- Return type:
- 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.randomdraw 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:
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.
- class POMDPPlanners.core.environment.DiscreteActionsEnvironment(discount_factor, name, space_info, reward_range=None, output_dir=None, debug=False, use_queue_logger=False)[source]
Bases:
EnvironmentAbstract 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:
- class POMDPPlanners.core.environment.EnvironmentGenerator(name)[source]
Abstract base class for environment generators.
This class implements the factory pattern for creating environment instances. It’s useful for generating environments with randomized parameters or for creating multiple environment variants.
Note
This is an abstract base class and cannot be instantiated directly. Subclasses must implement the generate_environment() method.
- Parameters:
name (str)
- name
Identifier for the generator
- abstractmethod generate_environment()[source]
Generate a new environment instance.
- Return type:
- Returns:
Newly created environment instance
Note
Subclasses must implement this method to define environment creation logic. This may involve randomization, parameter sampling, or deterministic generation.
- 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.
- 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 ... )
- 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
See also
Create a custom environment — write your own environment against this interface.
Realistic and experimental worlds — environments that wrap an external simulator.
Base Planner Class — the planners that run on these environments.