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.ndarrayof shape(4,):[cart_position, cart_velocity, pole_angle, pole_angular_velocity]. The initial state is drawnUniform(-0.05, 0.05)in each coordinate.Actions (discrete) —
0push left,1push 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
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
Observation space
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
integrated by explicit Euler (the configured default):
Gaussian process noise is then added:
by default, overridable through state_transition_cov.
Observation model. The full state read through noise, with no dependence on the action:
\(\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:
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:
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:
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 |
|---|---|---|
|
required |
|
|
required |
Observation noise. This is the knob that sets how partially observable the problem is; at zero it degenerates to an MDP. |
|
|
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?
|
Discrete |
Continuous |
|---|---|---|
State |
❌ |
✔️ |
Action |
✔️ |
❌ |
Observation |
❌ |
✔️ |
Also supports |
|
|---|---|
Native C++ backend |
✔️ |
Vectorized (torch) model |
✔️ |
In the |
✔️ |
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:
DiscreteActionsEnvironmentCartPole 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:
- Return type:
- Returns:
One MetricValue per declared metric name, in declaration order.
- Raises:
ValueError – If
historiesis empty, or if an episode ran without being measured. Seecompute_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.
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:
- Returns:
A spec for
task_completion_rate, which succeeds only if the pole stayed upright for the whole episode.ALLrather thanANYis 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 thenp.array_equalsemantics used by the linear-scan fallback).
- 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.
- 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.
- 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.
- is_terminal(state)[source]
Check if a state is terminal.
- Parameters:
state (
ndarray) – 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.
- 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.
- 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,).
- 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 lengthn_samples(numeric envs returnnp.ndarrayof shape(n_samples, *dim); structured envs returnList[T]).- Return type:
- 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 exposesbatch_sample(states_array)) should override to avoid the loop.
- 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.
- 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 asample()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:
- 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:
- Return type:
- Returns:
The
uprightindicator for this step’s state.
See also
POMDPPlanners.environments.cartpole_pomdp.cartpole_pomdp.CartPolePOMDPBatched torch model:
POMDPPlanners.environments.cartpole_pomdp.cartpole_vectorized_model.CartPoleVectorizedModelBase Environment Class — the full catalog and the environment interface.