RockSample

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 robot on a grid must sample the good rocks and skip the bad ones, then leave by walking east off the right-hand edge. Whether a rock is good is hidden. A long-range sensor answers, but it gets less accurate with distance: at the rock it is always right, and far away it is a coin flip, never worse.

RockSample is the long-horizon information-gathering benchmark of Smith & Simmons (2004). Getting a good score means walking towards a rock to raise the accuracy of its reading, which costs steps — the trade-off that separates planners that reason about future observations from ones that do not.

What the agent sees and does

  • State — a float32 vector [robot_row, robot_col, rock_0, …, rock_{R-1}], each rock 1.0 good or 0.0 bad. Build one with create_rock_sample_state; read it with get_robot_pos and get_rocks. With is_dangerous_area_hit_terminal=True a terminal-flag slot is appended.

  • Actions (discrete) — integers: 0 sample, 1 north, 2 east, 3 south, 4 west, and 5 … 4+R to check rock i. So the action set grows with the number of rocks; readable names are in env.action_names.

  • Observations (discrete) — "none", "good" or "bad".

Formal definition

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

State space. The state space uses:

  • Grid. A grid of \(M \times N\) cells.

  • Rocks. Rock positions \(y_1, \dots, y_R\).

  • Robot. The robot’s position \(x = (r, k)\), row \(r\) and column \(k\).

  • Qualities. Rock qualities \(c \in \{0, 1\}^R\) (\(c_i = 1\): rock \(i\) is good).

  • Exit. One more absorbing exit state \(\top\), stored as the sentinel position \((-1, -1)\).

A state is \(s = (x, c)\), or the exit state:

\[S = \big(\{0, \dots, M-1\} \times \{0, \dots, N-1\} \times \{0,1\}^R\big) \;\cup\; \{\top\}\]

so \(|S| = MN2^R + 1\). With is_dangerous_area_hit_terminal=True a further binary slot \(h\) is appended and \(S_T\) grows accordingly.

Action space. A sample, four moves, and one check per rock:

\[A = \underbrace{\{0\}}_{\textsf{sample}} \cup \underbrace{\{1,2,3,4\}}_{\textsf{N,E,S,W}} \cup \underbrace{\{5, \dots, 4+R\}}_{\textsf{check rock } i}\]
  • Action \(0\) samples the rock under the robot.

  • Actions \(1, 2, 3, 4\) move one cell north, east, south or west.

  • Action \(4 + i\) reads the noisy sensor on rock \(i\) without moving.

Observation space

\[Z = \{\textsf{none},\; \textsf{good},\; \textsf{bad}\}\]

\(\textsf{good}\) and \(\textsf{bad}\) are the sensor’s noisy verdict on a checked rock; \(\textsf{none}\) follows every other action.

Transition model. Deterministic. Moves clamp at the north, south and west walls; moving east off the last column exits:

\[T(s' \mid s, a) = \mathbb{1}[s' = f(s, a)]\]

with \(f(\top, a) = \top\) and, for \(s = (x, c)\) where \(x = (r, k)\) (north is \(r - 1\)),

\[\begin{split}f(s, 1) &= \big((\max(r-1, 0),\, k),\; c\big) \\ f(s, 3) &= \big((\min(r+1, M-1),\, k),\; c\big) \\ f(s, 4) &= \big((r,\, \max(k-1, 0)),\; c\big) \\ f(s, 2) &= \begin{cases} \top & k + 1 \geq N \\ \big((r,\, k+1),\; c\big) & \text{otherwise} \end{cases} \\ f(s, 0) &= \big(x,\; c \text{ with } c_i \leftarrow 0 \text{ if } y_i = x\big) \\ f(s, a) &= s \qquad a \geq 5\end{split}\]

Sampling a rock consumes it: a good rock becomes bad, so sampling twice pays the penalty the second time. Check actions never move the robot.

Observation model. Only a check returns information. For \(a = 4 + i\), let \(d = \lVert x' - y_i \rVert_2\) be the Euclidean distance from the robot to rock \(i\) and let \(w\) be sensor_efficiency. The accuracy is the law of Smith & Simmons, “Heuristic Search Value Iteration for POMDPs” (2004), in code (1 + 2 ** (-distance / sensor_efficiency)) / 2:

\[\mathrm{acc}(d) = \tfrac{1}{2}\big(1 + 2^{-d/w}\big)\]

which is \(1\) at the rock, \(0.75\) at \(d = w\), and decays to \(\tfrac{1}{2}\) — never below it, so a distant check is uninformative rather than misleading. Then

\[\begin{split}O(\textsf{good} \mid s', 4+i) &= \begin{cases} \mathrm{acc}(d) & c'_i = 1 \\ 1 - \mathrm{acc}(d) & c'_i = 0 \end{cases} \\ O(\textsf{bad} \mid s', 4+i) &= 1 - O(\textsf{good} \mid s', 4+i) \\ O(\textsf{none} \mid s', a) &= 1 \qquad a < 5\end{split}\]

Reward function. Terms are added, evaluated on the pre-transition state \(s = (x, c)\), \(x = (r, k)\), except the hazard term, which uses the realised \(x'\). Write:

  • \(t\) for step_penalty;

  • \(g\) for good_rock_reward;

  • \(\ell\) for bad_rock_penalty;

  • \(u\) for sensor_use_penalty;

  • \(e\) for exit_reward.

Then:

\[\begin{split}R(s, a, s') = t + \begin{cases} e & a = 2,\; k = N-1 \\ g\,c_i + \ell(1 - c_i) & a = 0,\; x = y_i \\ u & a \geq 5 \\ 0 & \text{otherwise} \end{cases} \;+\; D(x')\end{split}\]

The exit term short-circuits: an exiting step pays \(t + e\) and no hazard term. The hazard term \(D\) is where the three reward_model_type variants differ. Let:

  • \(\mathrm{dist}(x')\) be the distance from \(x'\) to the nearest hazard centre;

  • \(\mathrm{rad}\) the dangerous_area_radius;

  • \(P\) the dangerous_area_penalty;

  • \(q\) the dangerous_area_hit_probability.

Then:

\[\begin{split}D_{\text{constant}}(x') &= P \cdot \mathbb{1}[\mathrm{dist}(x') \leq \mathrm{rad}] \cdot \mathrm{Bern}(q) \\ D_{\text{decayed}}(x') &= P \cdot \mathrm{Bern}\big(\exp\big(-\mathrm{dist}(x') / v\big)\big) \\ D_{\text{shock}}(x') &= \pm |P| \text{ with probability } \tfrac{1}{2} \text{ each}, \quad \mathrm{dist}(x') \leq \mathrm{rad}\end{split}\]

where \(v\) is penalty_decay. The decayed variant has no radius cutoff — it draws on every step. The shock variant has zero mean and exists to separate risk-sensitive planners from risk-neutral ones, which cannot tell it from \(D \equiv 0\).

Warning

Under the constant and decayed variants with \(q < 1\), \(R\) draws a Bernoulli on every call, so reward(s, a) is not a deterministic function of its arguments. Pass the realised next_state to keep the reward on the same outcome as the trajectory. Setting is_dangerous_area_hit_terminal=True removes the problem by moving the draw into the transition: the hazard slot \(h\) is set there, and \(D\) becomes deterministic given \(h\).

Initial belief. Position known, every rock configuration equally likely:

\[b_0\big((x_0, c)\big) = 2^{-R}, \qquad c \in \{0,1\}^R\]

with \(x_0\) = init_pos and the initial observation fixed at \(\textsf{none}\). This is the point of the benchmark: \(2^R\) hidden configurations, and the only way to narrow them is to spend steps walking closer to the rocks.

Discount. \(\gamma\) = discount_factor, default \(0.95\).

Terminal set. \(S_T = \{\top\}\), plus \(\{s : h = 1\}\) when the hazard is terminal.

Rewards

Terms are added, so the hazard penalty is passed as a negative number:

Event

Reward

Every step

step_penalty (default 0.0)

Sample a good rock

good_rock_reward (+10.0)

Sample a bad rock

bad_rock_penalty (-10.0)

Any check action

sensor_use_penalty (0.0)

Move east off the right edge

exit_reward (+10.0)

Enter a dangerous area

dangerous_area_penalty (-5.0)

Key settings

Argument

Default

What it changes

map_size

(5, 5)

Grid size.

rock_positions

[(0,0), (2,2), (3,3)]

Number and placement of rocks. This sets the action-space size.

sensor_efficiency

10.0

Distance in cells at which a check is 75% accurate. Larger means the sensor stays accurate further away, so the problem gets easier.

dangerous_areas

None

Hazard cells. Adds a safety dimension on top of the information problem.

is_dangerous_area_hit_terminal

False

Whether entering a hazard ends the episode.

reward_model_type

CONSTANT_HAZARD_PENALTY

Also DISTANCE_DECAYED_HAZARD_PENALTY and ZERO_MEAN_HAZARD_SHOCK. The last one cannot be combined with is_dangerous_area_hit_terminal=True.

discount_factor

0.95

An episode ends when the robot exits east (its position becomes the sentinel (-1, -1)), or on a hazard hit if that was made terminal.

Can I use?

RockSamplePOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

Native C++ backend

✔️

Vectorized (torch) model

✔️ RockSampleVectorizedModel (some configurations; others raise NotImplementedError)

In the get_environment registry

✔️

Optional dependencies

None

Example

from POMDPPlanners.environments.rock_sample_pomdp import RockSamplePOMDP

env = RockSamplePOMDP(map_size=(5, 5), rock_positions=[(0, 0), (2, 2), (3, 3)])

state = env.initial_state_dist().sample(1)[0]
check_first_rock = 5
observation = env.sample_observation(state, check_first_rock)
print(env.action_names[check_first_rock], observation)

Parameters

class POMDPPlanners.environments.rock_sample_pomdp.RockSamplePOMDP(map_size=(5, 5), rock_positions=None, init_pos=(0, 0), sensor_efficiency=10.0, bad_rock_penalty=-10.0, good_rock_reward=10.0, step_penalty=0.0, sensor_use_penalty=0.0, exit_reward=10.0, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=-5.0, dangerous_area_hit_probability=1.0, reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, penalty_decay=1.0, is_dangerous_area_hit_terminal=False, discount_factor=0.95, name='RockSample', output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: DiscreteActionsEnvironment

RockSample POMDP environment

This environment implements the classic rock sampling problem where a robot must navigate a grid, use sensors to evaluate rocks, and decide which ones to sample while balancing exploration costs and sampling rewards.

Observation model:

A check action on rock i returns "good" or "bad", correct with probability (1 + 2 ** (-d / sensor_efficiency)) / 2 where d is the Euclidean distance from the robot to that rock. This is the accuracy of Smith & Simmons, “Heuristic Search Value Iteration for POMDPs” (2004). It is 1.0 at the rock and falls towards 0.5 with distance, never below it, so a check from far away is uninformative rather than misleading. Every other action returns "none".

Stochasticity:

The dangerous-area penalty can be applied either deterministically (the default) or stochastically. When dangerous_area_hit_probability == 1.0 (default), the penalty is applied every time the robot’s next position lies inside a dangerous area, matching legacy behavior. When dangerous_area_hit_probability < 1.0, the penalty is applied only with that probability per reward() / reward_batch() call (one Bernoulli draw per state), producing a heavy-tailed return distribution suitable for benchmarking risk-sensitive planners (e.g. ICVaR-aware MCTS) against expected-value MCTS on the same env. Note that this makes reward(state, action) non-deterministic given a state-action pair, so any external caching that assumes deterministic rewards must be aware of this. transition_log_probability is unaffected.

Parameters:
map_size

Grid dimensions as (rows, cols)

rock_positions

List of rock positions as (row, col) tuples

init_pos

Initial robot position

sensor_efficiency

Distance at which the check sensor is 75% accurate (Smith & Simmons’ d0); larger means accuracy holds up further from the rock

bad_rock_penalty

Penalty for sampling a bad rock

good_rock_reward

Reward for sampling a good rock

step_penalty

Cost for each action

sensor_use_penalty

Additional cost for using sensor

exit_reward

Reward for reaching the exit

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = RockSamplePOMDP(map_size=(5, 5), rock_positions=[(0, 0), (2, 2), (3, 3)])
>>>
>>> # 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
compute_metrics(histories)[source]

Compute the RockSample metrics, always reporting every declared name.

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:

RockSampleVisualizer

get_actions()[source]

Get all available actions.

Return type:

List[int]

get_metric_specs()[source]

Declare the RockSample metrics derived from the per-step channels.

Return type:

List[StepInfoMetric]

Returns:

Specs for average_rocks_sampled, task_completion_rate and average_dangerous_area_steps.

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 initial observation distribution.

Return type:

DiscreteDistribution

initial_state_dist()[source]

Get initial state distribution.

Return type:

DiscreteDistribution

is_equal_observation(observation1, observation2)[source]

Check if two observations are equal.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Check if state is terminal.

Terminal when the robot has exited east (the (-1, -1) sentinel) or, for a hazard-terminal env, when the trailing terminal slot is set.

Return type:

bool

Parameters:

state (ndarray)

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 immediate reward.

Uses the realised next_state when supplied (e.g. by Environment.sample_next_step()) so the dangerous-area penalty fires against the same outcome as the trajectory instead of a fresh draw.

Return type:

float

Parameters:
reward_batch(states, action, next_states=None)[source]

Calculate rewards for a batch of states given a single action.

Threads caller-supplied next_states through to the dangerous-area position check so the batch path agrees with the scalar reward() whenever Environment.sample_next_step (or any other caller) pre-samples next states. When next_states is None, we fall back to closed-form reconstruction of the next robot position from (state, action); RockSample transitions are deterministic, so this fallback matches a fresh draw from sample_next_state(). The per-call Bernoulli refund for the dangerous-area penalty is preserved in both branches.

Return type:

ndarray

Parameters:
  • states (Any)

  • action (int)

  • next_states (Any)

property reward_requires_next_state: bool

Reward depends on the realised next_state iff the hazard flag is on.

When is_dangerous_area_hit_terminal is enabled the hazard penalty is deterministic given the terminal slot set during the transition, so drivers must sample the transition first and pass the realised next_state to reward().

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:

Any

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_next_step(state, action)[source]

Override to avoid reward() recomputing next state.

Return type:

Tuple[ndarray, str, float]

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

Any

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

Random rollout via native C++ deterministic transition and reward kernel.

The C++ kernel applies the variant-aware dangerous-area reward term directly, so no Python fallback is required when danger zones are configured.

Parameters:
  • state (Any) – Current RockSample state array.

  • action_sampler (Any) – Object with a sample() method returning an integer action. Currently unused — actions are drawn uniformly by the native kernel.

  • 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 the sampling action, terminal status and hazard exposure.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal step. On the terminal step this carries the exit sentinel position, which the dangerous-area test is applied to exactly as it always was.

  • action (Any) – The action taken, or None on the terminal step.

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

Return type:

Dict[str, float]

Returns:

The sampled_rock, terminal_state and in_dangerous_area indicators for this step.

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