CartPole

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.

Balance a pole on a cart by pushing left or right, seeing only a noisy reading of the four-dimensional state. The dynamics are Gym CartPole’s; the partial observability comes from adding Gaussian sensor noise to every observation.

Use it when you want a continuous-state control problem whose optimal behaviour you can judge by eye — a good policy survives, a bad one drops the pole in a few steps — without any of the information-gathering structure of Light-Dark or RockSample.

What the agent sees and does

  • State — np.ndarray of shape (4,): [cart_position, cart_velocity, pole_angle, pole_angular_velocity]. The initial state is drawn Uniform(-0.05, 0.05) in each coordinate.

  • Actions (discrete) — 0 push left, 1 push right.

  • Observations (continuous) — the state plus zero-mean Gaussian noise with covariance noise_cov.

Formal definition

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

State space

\[S = \mathbb{R}^4, \qquad s = (x, \dot{x}, q, \dot{q})\]

The four components are:

  • \(x\) — the cart position;

  • \(\dot{x}\) — the cart velocity;

  • \(q\) — the pole angle from upright in radians;

  • \(\dot{q}\) — the pole’s angular velocity.

Action space

\[A = \{0, 1\} \quad (\text{push left, push right})\]

Observation space

\[Z = \mathbb{R}^4\]

A noisy reading of the four state components \((x, \dot{x}, q, \dot{q})\), in that order.

Transition model. The Gym CartPole physics, with these constants:

  • \(m_c = 1.0\);

  • \(m_p = 0.1\);

  • half-length \(\ell = 0.5\);

  • \(g = 9.8\);

  • \(F = 10\);

  • \(\Delta t = 0.02\).

Let \(F_a = +F\) for \(a = 1\) and \(-F\) for \(a = 0\). The accelerations are

\[\begin{split}h &= \frac{F_a + m_p \ell \dot{q}^2 \sin q} {m_c + m_p} \\ \ddot{q} &= \frac{g \sin q - h \cos q} {\ell\left(\tfrac{4}{3} - \dfrac{m_p \cos^2 q}{m_c + m_p}\right)} \\ \ddot{x} &= h - \frac{m_p \ell \ddot{q} \cos q} {m_c + m_p}\end{split}\]

integrated by explicit Euler (the configured default):

\[f(s, a) = \big(x + \Delta t\,\dot{x},\;\; \dot{x} + \Delta t\,\ddot{x},\;\; q + \Delta t\,\dot{q},\;\; \dot{q} + \Delta t\,\ddot{q}\big)\]

Gaussian process noise is then added:

\[T(s' \mid s, a) = \mathcal{N}\big(s';\; f(s, a),\; \Sigma_T\big), \qquad \Sigma_T = \mathrm{diag}(10^{-4}, 10^{-4}, 2.5 \times 10^{-5}, 10^{-4})\]

by default, overridable through state_transition_cov.

Observation model. The full state read through noise, with no dependence on the action:

\[O(o \mid s', a) = \mathcal{N}\big(o;\; s',\; \Sigma_O\big), \qquad \Sigma_O = \texttt{noise\_cov}\]

\(\Sigma_O\) is a required constructor argument: the partial observability is entirely this matrix, so the class does not pick one. With \(\Sigma_O = 0\) the problem is exactly Gym CartPole.

Reward function. One unit per step survived:

\[R(s, a) = \mathbb{1}[s \notin S_T]\]

so \(R \in [0, 1]\). Note it is evaluated on the state the action is taken from, so the step that leaves the limits still pays \(1\).

Initial belief. Every coordinate independently uniform on \([-0.05, 0.05]\) around upright:

\[b_0 = \mathrm{Unif}\big([-0.05,\, 0.05]^4\big)\]

The opening observation is a draw, not a fixed placeholder: a state from \(b_0\) plus \(\mathcal{N}(0, \Sigma_O)\).

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

Terminal set. The cart leaving its track or the pole passing 12 degrees:

\[S_T = \{s : |x| > 2.4 \ \text{ or }\ |q| > 12^\circ\}\]

Note

\(S_T\) is a predicate on \(x\) and \(q\), which the agent never observes exactly. A planner therefore cannot know it has terminated; it can only hold a belief about it.

Rewards

+1.0 for every step in a non-terminal state, 0.0 in a terminal one. reward_range is (0.0, 1.0). There is no step cost and no goal bonus: the return is the number of steps survived, discounted.

Key settings

Argument

Default

What it changes

discount_factor

required

noise_cov

required

Observation noise. This is the knob that sets how partially observable the problem is; at zero it degenerates to an MDP.

state_transition_cov

diag([1e-4, 1e-4, 2.5e-5, 1e-4])

Process noise.

The physics constants are fixed in the class, not constructor arguments:

  • gravity 9.8;

  • cart mass 1.0;

  • pole mass 0.1;

  • half-pole length 0.5;

  • force magnitude 10.0;

  • timestep 0.02 s;

  • Euler integration.

An episode ends when |cart_position| > 2.4 or |pole_angle| > 0.2094 rad (12°).

Can I use?

CartPolePOMDP

Discrete

Continuous

State

❌

✔️

Action

✔️

❌

Observation

❌

✔️

Also supports

Native C++ backend

✔️

Vectorized (torch) model

✔️ CartPoleVectorizedModel

In the get_environment registry

✔️

Optional dependencies

None

Example

import numpy as np

from POMDPPlanners.environments.cartpole_pomdp import CartPolePOMDP

env = CartPolePOMDP(discount_factor=0.95, noise_cov=np.eye(4) * 0.01)

state = env.initial_state_dist().sample(1)[0]
push_right = 1
# With n_samples=1 these return the value itself, not a list of one.
next_state = env.sample_next_state(state, push_right)
observation = env.sample_observation(next_state, push_right)
print(next_state, observation, env.reward(state, push_right))

Parameters

class POMDPPlanners.environments.cartpole_pomdp.cartpole_pomdp.CartPolePOMDP(discount_factor, noise_cov, state_transition_cov=None, name='CartPolePOMDP', output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: DiscreteActionsEnvironment

CartPole balancing task formulated as a POMDP.

This environment simulates the classic cart-pole balancing problem where an agent must apply left or right forces to keep a pole balanced on a moving cart. The challenge comes from noisy observations of the cart-pole state.

Problem Structure: - State: [cart_position, cart_velocity, pole_angle, pole_velocity] (continuous) - Actions: [left_force, right_force] (discrete) - Observations: Noisy state measurements (continuous) - Rewards: +1.0 per time step alive, 0.0 when terminated - Termination: Pole falls beyond angle threshold or cart moves too far

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> noise_cov = np.diag([0.1, 0.1, 0.1, 0.1])
>>> env = CartPolePOMDP(discount_factor=0.99, noise_cov=noise_cov)
>>>
>>> # 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:
compute_metrics(histories)[source]

Compute the CartPole metrics, always reporting every declared name.

The shared aggregator omits a metric no episode reported, which happens for an episode with no recorded steps. This environment has always reported a zero-valued task_completion_rate in that case, so the declared names are filled rather than dropped.

Parameters:

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

Return type:

List[MetricValue]

Returns:

One MetricValue per declared metric name, in declaration order.

Raises:

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

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

CartPoleVisualizer

get_actions()[source]

Get all possible actions in the discrete action space.

Return type:

List[int]

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.

get_metric_specs()[source]

Declare the CartPole metric derived from the per-step channel.

Return type:

List[StepInfoMetric]

Returns:

A spec for task_completion_rate, which succeeds only if the pole stayed upright for the whole episode. ALL rather than ANY is what encodes that: a single crashed state fails the episode, and the crash is normally the last state, recorded on the terminal step.

hash_action(action)[source]

Return a hashable key consistent with action equality.

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

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

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

Parameters:

action (Any) – Action to hash.

Return type:

Hashable

Returns:

A hashable key derived from action.

initial_observation_dist()[source]

Get the initial observation distribution.

Return type:

Distribution

Returns:

Distribution over initial observations

Note

Subclasses must implement this method to define initial observations.

initial_state_dist()[source]

Get the initial state distribution.

Return type:

Distribution

Returns:

Distribution over initial states

Note

Subclasses must implement this method to define the starting distribution.

is_equal_observation(observation1, observation2)[source]

Check if two observations are equal.

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

  • observation2 (ndarray) – Second observation to compare

Return type:

bool

Returns:

True if observations are considered equal, False otherwise

Note

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

is_terminal(state)[source]

Check if a state is terminal.

Parameters:

state (ndarray) – State to check for terminal condition

Return type:

bool

Returns:

True if the state is terminal, False otherwise

Note

Subclasses must implement this method to define terminal conditions.

observation_log_probability(next_state, action, observations)[source]

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

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

Return type:

ndarray

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

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

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

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

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

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

  • observation (Any) – A single observation.

Return type:

ndarray

Returns:

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

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

Calculate the immediate reward for a state-action(-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 (int) – 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 (int) – 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[tuple[int, ...], dtype[double]]

Parameters:
sample_next_state_batch(states, action)[source]

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

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

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

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

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

Returns:

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

Return type:

ndarray

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

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

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

Returns:

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

Return type:

ndarray[tuple[int, ...], dtype[double]]

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

Random rollout via native C++.

Parameters:
  • state (Any) – Current 4-D cart-pole state [x, x_dot, theta, theta_dot].

  • action_sampler (Any) – Object with a sample() method (used only on the Python fallback path).

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

step_info(state, action, next_state)[source]

Report whether the pole is still upright in this step’s state.

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

  • action (Any) – Unused; balance is a property of the state alone.

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

Return type:

Dict[str, float]

Returns:

The upright indicator for this step’s state.

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