Mountain Car
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.
A car whose engine force (\(k = 0.001\)) is smaller than the largest pull of gravity on the slope (\(g = 0.0025\)), so it cannot climb the hill directly and must rock back and forth to build momentum, while reading position and velocity through noise.
The reward is -1 on every step until the goal, so it says nothing about progress, and reaching the goal takes many steps. That makes it hard for short-horizon search: a planner that cannot see past its horizon never discovers that reversing first is what wins.
What the agent sees and does
State —
[position, velocity], position in[-1.2, 0.6], velocity in[-0.07, 0.07], with process noisediag([2.5e-5, 1e-6]).Actions (discrete) —
-1,0,1.Observations (continuous) — noisy
[position, velocity], standard deviations 0.1 and 0.01.
Formal definition
The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\).
State space
with \(p\) the car’s position along the valley and \(v\) its velocity.
Action space
The actions mean:
\(-1\) pushes left;
\(0\) does not push;
\(1\) pushes right.
Observation space
A noisy reading of \((p, v)\), in that order.
Transition model. The deterministic part is the Mountain Car map, with power \(k = 0.001\) and gravity \(g = 0.0025\):
The left wall is inelastic: hitting it zeroes the velocity. Gaussian process noise is then added and the result projected back into \(S\) by the same clipping rule \(\mathrm{proj}\):
\(\Sigma_T\) is the state_transition_cov constructor argument.
Note
transition_log_probability returns the unprojected density
\(\log \mathcal{N}(s'; f(s,a), \Sigma_T)\). At the boundary that
density is not the density of the projected variable, which puts positive
mass on the walls. It matters only for beliefs with particles at a wall.
Observation model. The full state, read through independent noise:
The action does not enter. Position noise of \(0.1\) against a domain of width \(1.8\) is what makes this a POMDP rather than Mountain Car.
Reward function. One unit of cost per step until the goal:
so \(R \in [-1, 0]\).
Initial belief. Position uniform on a band around the valley floor, velocity exactly zero:
with the initial observation reported as \((0, 0)\) rather than sampled from \(O\).
Discount. \(\gamma\) = discount_factor, required.
Terminal set. \(S_T = \{(p, v) \in S : p \geq 0.5\}\).
Rewards
Event |
Reward |
|---|---|
Step before the goal |
-1.0 |
Step at the goal |
0.0 |
The goal is position >= 0.5. reward_range is (-1.0, 0.0), and the
episode ends at the goal.
Key settings
discount_factor is required; the class has no default.
state_transition_cov sets the process noise on [position, velocity].
It defaults to None, which means diag([2.5e-5, 1e-6]). The observation
noise (standard deviations 0.1 and 0.01) is fixed in the class, not an
argument.
Metrics
It reports a task_completion_rate metric.
Can I use?
|
Discrete |
Continuous |
|---|---|---|
State |
❌ |
✔️ |
Action |
✔️ |
❌ |
Observation |
❌ |
✔️ |
Also supports |
|
|---|---|
Native C++ backend |
✔️ |
Vectorized (torch) model |
✔️ |
In the |
✔️ |
Optional dependencies |
None |
Example
from POMDPPlanners.environments.mountain_car_pomdp.mountain_car_pomdp import (
MountainCarPOMDP,
)
env = MountainCarPOMDP(discount_factor=0.99)
state = env.initial_state_dist().sample(1)[0]
next_state = env.sample_next_state(state, 1)
print(state, next_state, env.sample_observation(next_state, 1))
Parameters
- class POMDPPlanners.environments.mountain_car_pomdp.mountain_car_pomdp.MountainCarPOMDP(discount_factor, state_transition_cov=None, name='MountainCarPOMDP', output_dir=None, debug=False, use_queue_logger=False)[source]
Bases:
DiscreteActionsEnvironmentMountain Car problem formulated as a POMDP.
This environment simulates an underpowered car trying to reach the top of a steep mountain. The car must build momentum by oscillating back and forth to gain enough energy to reach the goal, with noisy observations of its state.
Problem Structure: - State: [position, velocity] (continuous, position ∈ [-1.2, 0.6], velocity ∈ [-0.07, 0.07]) - Actions: [-1 (reverse), 0 (neutral), 1 (forward)] (discrete) - Observations: Noisy state measurements (continuous) - Rewards: 0 for reaching goal (position ≥ 0.5), -1 per time step otherwise - Goal: Drive car to position ≥ 0.5 (top of mountain)
Example
>>> import numpy as np >>> np.random.seed(42) # For reproducible results >>> >>> # Initialize environment >>> env = MountainCarPOMDP(discount_factor=0.99) >>> >>> # 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 Mountain Car 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:
MountainCarVisualizer
- 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 Mountain Car metric derived from the per-step channel.
- Return type:
- Returns:
A spec for
task_completion_rate.ANYreproduces the historical scan, which stopped at the first state past the goal.
- 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 (
Tuple[float,float]) – 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 2-D car state[position, velocity].action_sampler (
Any) – Object with asample()method (kept for API parity with the baseEnvironmentcontract; unused on the native rollout path which draws indices directly via NumPy).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 car has reached the goal position in this state.
- Parameters:
- Return type:
- Returns:
The
at_goalindicator for this step’s state.
See also
POMDPPlanners.environments.mountain_car_pomdp.mountain_car_pomdp.MountainCarPOMDPSanity — the two-state debugging environment.
Base Environment Class — the full catalog and the environment interface.