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
float32vector[robot_row, robot_col, rock_0, …, rock_{R-1}], each rock1.0good or0.0bad. Build one withcreate_rock_sample_state; read it withget_robot_posandget_rocks. Withis_dangerous_area_hit_terminal=Truea terminal-flag slot is appended.Actions (discrete) — integers:
0sample,1north,2east,3south,4west, and5 … 4+Rto check rock i. So the action set grows with the number of rocks; readable names are inenv.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:
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:
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
\(\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:
with \(f(\top, a) = \top\) and, for \(s = (x, c)\) where \(x = (r, k)\) (north is \(r - 1\)),
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:
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
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:
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:
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:
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 |
|
Sample a good rock |
|
Sample a bad rock |
|
Any check action |
|
Move east off the right edge |
|
Enter a dangerous area |
|
Key settings
Argument |
Default |
What it changes |
|---|---|---|
|
|
Grid size. |
|
|
Number and placement of rocks. This sets the action-space size. |
|
|
Distance in cells at which a check is 75% accurate. Larger means the sensor stays accurate further away, so the problem gets easier. |
|
|
Hazard cells. Adds a safety dimension on top of the information problem. |
|
|
Whether entering a hazard ends the episode. |
|
|
Also |
|
|
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?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
✔️ |
❌ |
Also supports |
|
|---|---|
Native C++ backend |
✔️ |
Vectorized (torch) model |
✔️ |
In the |
✔️ |
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:
DiscreteActionsEnvironmentRockSample 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)) / 2wheredis 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. Whendangerous_area_hit_probability < 1.0, the penalty is applied only with that probability perreward()/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 makesreward(state, action)non-deterministic given a state-action pair, so any external caching that assumes deterministic rewards must be aware of this.transition_log_probabilityis unaffected.
- Parameters:
sensor_efficiency (float)
bad_rock_penalty (float)
good_rock_reward (float)
step_penalty (float)
sensor_use_penalty (float)
exit_reward (float)
dangerous_area_radius (float)
dangerous_area_penalty (float)
dangerous_area_hit_probability (float)
reward_model_type (RewardModelType)
penalty_decay (float)
is_dangerous_area_hit_terminal (bool)
discount_factor (float)
name (str)
output_dir (Path | None)
debug (bool)
use_queue_logger (bool)
- 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:
- 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:
RockSampleVisualizer
- get_metric_specs()[source]
Declare the RockSample metrics derived from the per-step channels.
- Return type:
- Returns:
Specs for
average_rocks_sampled,task_completion_rateandaverage_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 thenp.array_equalsemantics used by the linear-scan fallback).
- 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.
- 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 immediate reward.
Uses the realised
next_statewhen supplied (e.g. byEnvironment.sample_next_step()) so the dangerous-area penalty fires against the same outcome as the trajectory instead of a fresh draw.
- reward_batch(states, action, next_states=None)[source]
Calculate rewards for a batch of states given a single action.
Threads caller-supplied
next_statesthrough to the dangerous-area position check so the batch path agrees with the scalarreward()wheneverEnvironment.sample_next_step(or any other caller) pre-samples next states. Whennext_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 fromsample_next_state(). The per-call Bernoulli refund for the dangerous-area penalty is preserved in both branches.
- property reward_requires_next_state: bool
Reward depends on the realised
next_stateiff the hazard flag is on.When
is_dangerous_area_hit_terminalis enabled the hazard penalty is deterministic given the terminal slot set during the transition, so drivers must sample the transition first and pass the realisednext_statetoreward().
- 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.
- 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++ 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 asample()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:
- 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, orNoneon the terminal step.next_state (
Any) – Unused; each state is scored when it is recorded.
- Return type:
- Returns:
The
sampled_rock,terminal_stateandin_dangerous_areaindicators for this step.
See also
POMDPPlanners.environments.rock_sample_pomdp.RockSamplePOMDPBatched torch model:
POMDPPlanners.environments.rock_sample_pomdp.rocksample_vectorized_model.RockSampleVectorizedModelBase Environment Class — the full catalog and the environment interface.