Safety Ant Velocity
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.
Move as fast as you can while keeping speed below a safety threshold, judging your own speed only through a noisy sensor. Reward grows with speed and a penalty (-100 by default) fires above the threshold, so the optimal behaviour sits just under a line whose position you cannot see exactly.
Use it for constrained and risk-aware planners: the quantity to control is not only the expected return but the probability that the speed is over the limit.
Note
Despite the name this is not a MuJoCo or Safety-Gymnasium wrapper. It is
a 2-D point mass simulated inside the class. Nothing in the package imports mujoco
or safety-gymnasium.
What the agent sees and does
State —
np.ndarrayof shape(4,):[position_x, position_y, velocity_x, velocity_y]. The initial position isUniform(-1, 1)in each axis with zero velocity.Actions (discrete) —
0–3, force magnitudes[0.0, 0.33, 0.67, 1.0] * max_force. The force direction is randomized by the transition kernel; the agent chooses only how hard to push.Observations (continuous) — the 4-vector with diagonal Gaussian noise,
position_noiseon position andvelocity_noiseon velocity.
Formal definition
The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\).
State space
with \(\mathbf{p} \in \mathbb{R}^2\) the agent’s position and \(\mathbf{v} \in \mathbb{R}^2\) its velocity.
Action space. Four force magnitudes:
Action \(a\) pushes with \(0\%\), \(33\%\), \(67\%\) or
\(100\%\) of max_force, for \(a = 0, 1, 2, 3\). The action sets
only the strength; the environment draws the direction.
Observation space
A noisy reading of \((\mathbf{p}, \mathbf{v})\), in that order.
Transition model. The agent chooses a force magnitude; the direction is drawn by the environment:
The damped point-mass dynamics are then integrated semi-implicitly:
The symbols map to constructor arguments:
\(m\) =
mass;\(c\) =
damping;\(\Delta t\) =
dt.
Position is updated with the new velocity, not the old one.
Note
The stochasticity here is in the force’s direction, not an additive Gaussian on the state. So \(T(\cdot \mid s, a)\) is supported on a circle in velocity space — a one-dimensional set in \(\mathbb{R}^4\) — rather than having a density over it. For \(a = 0\) the transition is deterministic, since \(u = 0\) makes \(q\) irrelevant.
Observation model. The full state with independent diagonal noise:
with \(\sigma_p\) = position_noise, \(\sigma_v\) =
velocity_noise. The action does not enter.
Reward function. Paid for speed, penalized for exceeding the limit — both read off the state the action is taken from:
with \(\lVert \mathbf{v} \rVert\) the speed and \(v_{\text{safe}}\) =
safe_velocity_threshold. This is the whole tension:
\(R\) grows linearly in speed right up to \(v_{\text{safe}}\), then drops by
\(100\) (the default penalty) just above it. Because the agent only ever sees
\(\lVert \mathbf{v} \rVert\) through noise of width \(\sigma_v\), it
cannot know which side of \(v_{\text{safe}}\) it is on — it can only trade expected
speed against the probability of having crossed.
Initial belief. Position uniform in a unit box, velocity exactly zero:
Note
initial_observation_dist returns the state distribution, not a draw
through \(O\). The opening “observation” is therefore a noiseless
state sample, which is not what the observation model would produce.
Discount. \(\gamma\) = discount_factor, required.
Terminal set. A 50 % margin above the penalty threshold:
so there is a band \(v_{\text{safe}} < \lVert \mathbf{v} \rVert \leq 1.5\,v_{\text{safe}}\) where the agent is being penalized every step but the episode continues — it can still brake back under the limit.
Rewards
reward = speed * movement_reward_scale
+ safety_violation_penalty if speed > safe_velocity_threshold
Defaults:
movement_reward_scale=1.0;safety_violation_penalty=-100.0;safe_velocity_threshold=2.0.
reward_range is
(safety_violation_penalty, safe_velocity_threshold * 1.5 * movement_reward_scale).
The reward is a function of the current state only — action and
next_state are ignored.
Key settings
Argument |
Default |
What it changes |
|---|---|---|
|
|
Where the penalty starts, and (at 1.5×) where the episode ends. |
|
|
How risk-averse the optimal policy is. |
|
|
How well the agent can tell it is speeding. This is what makes the problem a POMDP. |
|
|
|
|
|
Point-mass dynamics. |
An episode ends when speed exceeds safe_velocity_threshold * 1.5 — 3.0
at defaults, a 50 % margin above the penalty line.
Note
The default name is "SafeVelocityPOMDP", not
"SafeAntVelocityPOMDP". That string reaches result filenames and
config_id.
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.safety_ant_velocity_pomdp import SafeAntVelocityPOMDP
env = SafeAntVelocityPOMDP(discount_factor=0.95, safe_velocity_threshold=2.0)
state = env.initial_state_dist().sample(1)[0]
full_thrust = 3
next_state = env.sample_next_state(state, full_thrust)
observation = env.sample_observation(next_state, full_thrust)
print(next_state, observation, env.reward(next_state, full_thrust))
Parameters
- class POMDPPlanners.environments.safety_ant_velocity_pomdp.SafeAntVelocityPOMDP(discount_factor, safe_velocity_threshold=2.0, max_force=1.0, dt=0.1, mass=1.0, damping=0.1, position_noise=0.1, velocity_noise=0.2, safety_violation_penalty=-100.0, movement_reward_scale=1.0, name='SafeVelocityPOMDP', output_dir=None, debug=False, use_queue_logger=False)[source]
Bases:
DiscreteActionsEnvironmentSafety-critical velocity control task formulated as a POMDP.
This environment presents a safety-critical control problem where an agent must navigate while keeping velocity below a safety threshold. The challenge comes from balancing exploration rewards with safety constraints under noisy velocity observations.
Problem Structure: - State: [position_x, position_y, velocity_x, velocity_y] (continuous) - Actions: [0=no force, 1=small, 2=medium, 3=large force] (discrete) - Observations: Noisy position and velocity measurements (continuous) - Rewards: Movement reward - safety violation penalty (if unsafe) - Safety constraint: velocity magnitude ≤ safe_velocity_threshold - Termination: Velocity exceeds 1.5x safety threshold
Safety Features: - Tracks safety and critical violation rates - Heavy penalties for constraint violations - Configurable safety thresholds and penalties - Physics simulation with uncertainty in force direction
Example
>>> import numpy as np >>> np.random.seed(42) # For reproducible results >>> >>> # Initialize environment >>> env = SafeAntVelocityPOMDP(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 environment-specific metrics from episode histories.
The default implementation aggregates the per-step channels reported by
step_info()according toget_metric_specs(). Subclasses with metrics that are not expressible as a per-step channel (for example ones needing cross-step reasoning) override this instead.- Parameters:
histories (
List[History]) – List of episode histories to analyze- Return type:
- Returns:
List of computed metrics with confidence intervals
- Raises:
ValueError – If
historiesis empty — a metric over no episodes is an average over nothing, so any value reported for it is invented. Also if this environment declares metric specs and any episode recorded transition steps while carrying none of the declared channels — a history produced before the per-step channel existed, or by a runner that does not callstep_info(). Scoring those would report every metric as zero rather than as unmeasured.
- episode_visualizer()[source]
Return the visualizer that writes this environment’s traces.
- Return type:
SafeAntVelocityVisualizer
- 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.
- 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.
- 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++ physics and reward kernel.
Pre-draws action indices and runs the full rollout in a single C++ call, avoiding per-step Python dispatch.
- Parameters:
state (
Any) – Current 4-D state[px, py, vx, vy].action_sampler (
Any) – Accepted for interface compatibility with the basesimulate_random_rolloutsignature; the native rollout draws action indices vianp.random.randintdirectly and never invokes the sampler.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.
See also
POMDPPlanners.environments.safety_ant_velocity_pomdp.SafeAntVelocityPOMDPBatched torch model:
POMDPPlanners.environments.safety_ant_velocity_pomdp.safety_ant_velocity_vectorized_model.SafetyAntVelocityVectorizedModelBase Environment Class — the full catalog and the environment interface.