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 noise diag([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

\[S = [-1.2,\, 0.6] \times [-0.07,\, 0.07], \qquad s = (p, v)\]

with \(p\) the car’s position along the valley and \(v\) its velocity.

Action space

\[A = \{-1, 0, 1\}\]

The actions mean:

  • \(-1\) pushes left;

  • \(0\) does not push;

  • \(1\) pushes right.

Observation space

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

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\):

\[\begin{split}\tilde{v} &= \mathrm{clip}\big(v + ak - g\cos(3p),\; -0.07,\; 0.07\big) \\ \tilde{p} &= \mathrm{clip}(p + \tilde{v},\; -1.2,\; 0.6) \\ f(s, a) &= \begin{cases} (\tilde{p},\, 0) & \tilde{p} = -1.2 \text{ and } \tilde{v} < 0 \\ (\tilde{p},\, \tilde{v}) & \text{otherwise} \end{cases}\end{split}\]

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}\):

\[s' = \mathrm{proj}\big(f(s, a) + w\big), \qquad w \sim \mathcal{N}(0, \Sigma_T), \qquad \Sigma_T = \mathrm{diag}(2.5 \times 10^{-5},\; 10^{-6})\]

\(\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:

\[O(o \mid s', a) = \mathcal{N}(o;\, s',\, \Sigma_O), \qquad \Sigma_O = \mathrm{diag}(0.1^2,\; 0.01^2)\]

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:

\[R(s, a) = -\mathbb{1}[p < 0.5]\]

so \(R \in [-1, 0]\).

Initial belief. Position uniform on a band around the valley floor, velocity exactly zero:

\[b_0:\quad p \sim \mathrm{Unif}([-0.6,\, -0.4]), \qquad v = 0\]

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?

MountainCarPOMDP

Discrete

Continuous

State

❌

✔️

Action

✔️

❌

Observation

❌

✔️

Also supports

Native C++ backend

✔️

Vectorized (torch) model

✔️ MountainCarVectorizedModel

In the get_environment registry

✔️

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

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

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:

MountainCarVisualizer

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.

get_metric_specs()[source]

Declare the Mountain Car metric derived from the per-step channel.

Return type:

List[StepInfoMetric]

Returns:

A spec for task_completion_rate. ANY reproduces 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 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:
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 (Tuple[float, float]) – 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 (Tuple[float, float]) – 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 2-D car state [position, velocity].

  • action_sampler (Any) – Object with a sample() method (kept for API parity with the base Environment contract; 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:

float

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

  • action (Any) – Unused; reaching the goal 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 at_goal 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