LaserTag
Grid variant, LaserTagPOMDP: 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.
Continuous variant, ContinuousLaserTagPOMDP: the same, in the
continuous world. Drag to orbit, scroll to zoom, and use the bar to play,
scrub and switch camera.
Chase an opponent through a walled arena and fire the tag action from its cell. The only sensor is eight noisy laser ranges, one per compass direction. A ray stops at a wall or at the opponent, so a ray that reaches the opponent gives its distance up to sensor noise, while a ray that ends at a wall only says the opponent is not on it.
So the robot learns where the opponent is only on steps when the two share a row, column or diagonal with no wall between them. Between sightings the belief spreads out under the opponent’s movement model, so a planner has to decide whether to manoeuvre for an unblocked ray to the opponent or to commit to a tag on evidence from earlier steps. There is a grid variant and a continuous one; see Variants.
What the agent sees and does
State —
np.ndarrayof shape(5,):[robot_row, robot_col, opponent_row, opponent_col, terminal_flag](grid), or the same layout in continuous coordinates.Actions (discrete in the grid, continuous otherwise) — grid: integers
0north,1south,2east,3west,4tag. Continuous:[dx, dy, tag_flag].Observations (continuous) — eight laser ranges with Gaussian noise
measurement_noise. The grid variant returns a tuple, the continuous one a length-8np.ndarray. Terminal grid states emit(-1.0,) * 8. Both variants sweep the same eight headings but number them differently: the grid order is N, NE, E, SE, S, SW, W, NW, while the continuous order starts two places later, at E. Continuous beam \(i\) is grid beam \((i + 2) \bmod 8\), so a planner must not carry a beam index from one variant to the other.
Formal definition
The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\). It is written for the grid variant.
State space. Let \(G\) be the free cells of an \(M \times N\) grid with wall set \(\mathcal{W}\); a cell is written (row, column). Both positions and an absorbing flag:
Here:
\(\mathbf{u}\) is the robot’s cell.
\(\mathbf{v}\) is the opponent’s cell.
\(\top = 1\) once the episode has ended.
Action space.
The actions are:
\(0\) moves one row up (row \(-1\)).
\(1\) moves one row down (row \(+1\)).
\(2\) moves one column right (column \(+1\)).
\(3\) moves one column left (column \(-1\)).
\(4\) (tag) stays and tries to tag the opponent on the robot’s cell.
The continuous variant uses \((\mathrm{d}x, \mathrm{d}y, \text{tag flag}) \in \mathbb{R}^3\) instead.
Observation space. Eight non-negative laser ranges, or the all \(-1\) vector a terminal state emits:
Component \(k\) is the range along heading N, NE, E, SE, S, SW, W, NW for \(k = 0..7\). The continuous variant returns the same eight ranges as a length-8 array starting at E: its beam \(i\) is grid beam \((i + 2) \bmod 8\).
Transition model. The robot’s move first. With \(p\) =
transition_error_prob, a movement action executes as commanded with
probability \(1 - p\) and as one of the other three otherwise, chosen
uniformly. Let \(a'\) be the executed move. Its (row, column) offset is:
\(\Delta_0 = (-1, 0)\)
\(\Delta_1 = (1, 0)\)
\(\Delta_2 = (0, 1)\)
\(\Delta_3 = (0, -1)\)
The robot’s new cell is:
\(\textsf{tag}\) does not move the robot. A tag on the opponent’s cell ends the episode immediately, \(\top' = 1\), with no opponent draw.
The opponent then moves under a stochastic policy with a fixed mass
schedule. Write \(\mathbf{w}\) for the robot cell it conditions on —
post-move under PURSUE, pre-move under EVADE and
EVADE_WHEN_SPOTTED (for a tag these coincide, since tagging does not
move). Per axis independently, the policy puts \(0.4\) on one neighbour:
plus \(0.2\) on staying put. Invalid neighbours are dropped and their mass falls back onto stay, so the distribution always normalizes and a cornered opponent stands still.
EVADE_WHEN_SPOTTED switches on visibility: while the opponent is not
on an unoccluded laser ray, it walks uniformly (\(0.2\) per valid
cardinal neighbour, remainder on stay); once spotted, it flees as
EVADE. That makes the robot’s own sensing change the opponent’s dynamics
— the reason this variant is harder than either fixed policy.
In short: the opponent moves with probability 0.4 along x, 0.4 along y and stays with
probability 0.2. Those are nominal weights: when the robot is aligned on an
axis the 0.4 splits 0.2/0.2 across both directions, and a blocked neighbour
folds its mass into “stay”, so 0.2 is a floor rather than the actual stay
probability. opponent_policy selects one of:
EVADE(default; away from the robot’s pre-move position).PURSUE.EVADE_WHEN_SPOTTED, which only runs from the robot once a laser has seen it.
Observation model. Eight laser ranges, one per compass direction \(\Delta_k\) (N, NE, E, SE, S, SW, W, NW). The true range is the number of free cells before the first blocker — a wall, the grid edge, or the opponent:
Each is read through independent noise and clipped at zero:
with \(\sigma\) = measurement_noise. This is the whole inference
problem: the opponent is visible only as a shortened ray, so a reading
short by one is ambiguous between an opponent and the sensor’s noise, and a
ray blocked by a wall carries no information about the opponent at all.
Terminal states emit \((-1, \dots, -1)\).
Reward function. Evaluated against the pre-transition positions for the tag, the realised position for the hazard:
The hazard term charges one penalty on a wall or a danger zone, not one for each:
where \(c\) ranges over the danger-zone centres dangerous_areas.
A mistimed tag costs tag_penalty rather than merely a step, which is what
makes guessing expensive and the belief worth maintaining.
Initial belief. Uniform over every pair of distinct free cells:
so the robot’s own position starts unknown too, and the first laser reading
must localize both. With initial_state supplied, \(b_0\) is a point
mass on it instead.
Note
The opening observation is a fixed mid-range placeholder
\((3, \dots, 3)\), not a draw from \(O\) under \(b_0\). A
filter that weights the first reading through
observation_log_probability is therefore scoring a reading the
observation model did not produce.
Discount. \(\gamma\) = discount_factor, required.
Terminal set. \(S_T = \{s : \top = 1\}\) — set by a successful tag,
or by a hazard hit when is_dangerous_area_hit_terminal.
Rewards
Event |
Reward |
|---|---|
Tag on the opponent’s cell |
|
Tag and miss |
|
Any move |
|
Inside a wall or a dangerous area |
|
Warning
As in PacMan, dangerous_area_penalty is a positive magnitude that is
subtracted, the opposite of the RockSample and Push convention.
Key settings
Argument |
Default |
What it changes |
|---|---|---|
|
|
Arena size as |
|
|
Arena size as |
|
8 fixed cells / box list |
Layout. Walls both block movement and shape the laser readings. |
|
|
Laser noise — the partial-observability knob. |
|
|
|
|
|
The impatience trade-off: raise |
|
|
|
|
|
An episode ends when the terminal flag is set — on a successful tag, or on a
hazard hit when is_dangerous_area_hit_terminal=True.
Variants
LaserTagPOMDP— a grid, five discrete actions.ContinuousLaserTagPOMDP— continuous positions, axis-aligned box walls, and a continuous[dx, dy, tag_flag]action.ContinuousLaserTagPOMDPDiscreteActionsgives that world a five-action set.
VOPP needs a finite action set, so only ContinuousLaserTagPOMDPDiscreteActions
of the two continuous classes has a torch model,
ContinuousLaserTagVectorizedModel. It models every configuration of that
class: all three opponent policies, any dangerous_area_hit_probability, and
is_dangerous_area_hit_terminal. It declines nothing.
Can I use?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
❌ |
✔️ |
|
Discrete |
Continuous |
|---|---|---|
State |
❌ |
✔️ |
Action |
❌ |
✔️ |
Observation |
❌ |
✔️ |
|
Discrete |
Continuous |
|---|---|---|
State |
❌ |
✔️ |
Action |
✔️ |
❌ |
Observation |
❌ |
✔️ |
Also supports |
|
|
|
|---|---|---|---|
Native C++ backend |
✔️ (loaded lazily; falls back to Python if the extension is missing) |
✔️ |
✔️ |
Vectorized (torch) model |
✔️ |
❌ (no finite action set) |
✔️ |
In the |
✔️ |
✔️ |
✔️ |
Optional dependencies |
None |
None |
None |
Example
from POMDPPlanners.environments.laser_tag_pomdp import LaserTagPOMDP
env = LaserTagPOMDP(discount_factor=0.95)
state = env.initial_state_dist().sample(1)[0]
north = 0
next_state = env.sample_next_state(state, north)
laser_ranges = env.sample_observation(next_state, north)
print(next_state, laser_ranges)
Parameters
- class POMDPPlanners.environments.laser_tag_pomdp.LaserTagPOMDP(discount_factor, name='LaserTagPOMDP', floor_shape=(11, 7), walls={(1, 2), (3, 0), (3, 4), (5, 0), (6, 4), (9, 1), (9, 4), (10, 6)}, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, dangerous_areas={(2, 5), (5, 3), (7, 1)}, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, transition_error_prob=0.0, reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, penalty_decay=1.0, is_dangerous_area_hit_terminal=False, opponent_policy=OpponentPolicy.EVADE)[source]
Bases:
DiscreteActionsEnvironmentLaserTag POMDP environment implementation.
This is a pursuit-evasion problem where a robot must navigate a grid to tag an opponent. The robot receives noisy observations of the opponent’s position and must decide when and where to attempt tagging.
Problem Structure: - States: numpy array [robot_row, robot_col, opp_row, opp_col, terminal] - Actions: North(0), South(1), East(2), West(3), Tag(4) - Observations: 8-directional laser measurements (N,NE,E,SE,S,SW,W,NW) - Rewards: Tag success(+10), Tag failure(-10), Movement(-1)
- Parameters:
discount_factor (float)
name (str)
tag_reward (float)
tag_penalty (float)
step_cost (float)
measurement_noise (float)
dangerous_area_radius (float)
dangerous_area_penalty (float)
output_dir (Path | None)
debug (bool)
use_queue_logger (bool)
initial_state (ndarray | None)
transition_error_prob (float)
reward_model_type (RewardModelType)
penalty_decay (float)
is_dangerous_area_hit_terminal (bool)
opponent_policy (OpponentPolicy)
- floor_shape
Grid dimensions as (rows, cols)
- walls
Set of wall positions as (row, col) tuples
- tag_reward
Reward for successful tagging
- tag_penalty
Penalty for unsuccessful tagging
- step_cost
Cost per movement action
- measurement_noise
Standard deviation of observation noise
Example
>>> import numpy as np >>> np.random.seed(42) # For reproducible results >>> >>> # Initialize environment >>> env = LaserTagPOMDP(discount_factor=0.95) >>> >>> # 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 LaserTag POMDP specific metrics from simulation histories.
- Parameters:
- Return type:
- Returns:
All seven metrics 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:
LaserTagVisualizer
- get_metric_specs()[source]
Declare the LaserTag metrics derived from the per-step channels.
- Return type:
- Returns:
Specs for the five state- and transition-derived metrics, in the same order the enum declares them. The two reward-derived metrics are absent here and produced by
compute_metrics().
- 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_equal_observation(observation1, observation2)[source]
Check if two observations are equal.
Observations are 8-dimensional laser measurements or terminal observations.
- 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 transition.
The wall / dangerous-area penalty is computed against the realised post-action robot position taken from
next_state. When the caller omitsnext_state(e.g., the open-loop scalar API path) the method resamples a transition viasample_next_state()so the penalty is always scored against an actual draw from the transition kernel — never against the open-loopstate + action_vectorintended position.Environment.sample_next_step()threads its samplednext_stateinto this method so trajectory and reward agree on the same realisation.
- reward_batch(states, action, next_states=None)[source]
Vectorised reward for a batch of states under a single action.
When
next_statesis supplied the danger-area / wall penalty is evaluated against the realised positions innext_states[:, :2](matching the contract honoured byEnvironment.sample_next_step()). When it isNonethe method resamples viasample_next_state_batch()whenever penalty terms exist, then delegates to the reward model so reward and trajectory remain consistent end-to-end.
- property reward_requires_next_state: bool
Reward depends on the realised
next_stateiff hazard-terminal is on.When enabled, the dangerous-area penalty is deterministic given the terminal slot set during the transition, so drivers sample the transition first and thread the realised
next_stateintoreward().
- 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.
- step_info(state, action, next_state)[source]
Report tag status, hazard exposure and wall collisions for this step.
- Parameters:
- Return type:
- Returns:
The per-step channels.
recorded_stepis a constant 1.0 so that summing it reproduceslen(history.history), including the terminal bookkeeping step, which the historical episode-length count included.
Note
Nothing here reads the realised reward, which
step_infois not given.tag_success_rateandaverage_failed_tag_attemptsare defined in terms of it, so they stay incompute_metrics(). Recomputing the reward here is not an option: two of the reward models draw fromnp.random, so it would both return a different number and shift the RNG stream for every later transition.
- class POMDPPlanners.environments.laser_tag_pomdp.ContinuousLaserTagPOMDP(discount_factor, name='ContinuousLaserTagPOMDP', grid_size=(11.0, 7.0), walls=None, robot_radius=0.3, opponent_radius=0.3, tag_radius=0.5, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, robot_transition_cov_matrix=array([[0.1, 0.], [0., 0.1]]), opponent_transition_cov_matrix=array([[0.05, 0.], [0., 0.05]]), evasion_speed=0.6, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, dangerous_area_hit_probability=1.0, is_dangerous_area_hit_terminal=False, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, opponent_policy=OpponentPolicy.EVADE)[source]
Bases:
EnvironmentContinuous LaserTag POMDP with continuous
[dx, dy, tag_flag]actions.A pursuit-evasion problem in continuous 2-D space where a robot must navigate to tag an opponent. The robot receives noisy 8-direction laser range observations.
- Stochasticity:
The dangerous-area penalty can be applied either deterministically (the default) or stochastically. When
dangerous_area_hit_probability == 1.0(default), the kernel’s deterministic deduction is preserved verbatim, matching legacy behavior. Whendangerous_area_hit_probability < 1.0, the accumulated dangerous-area deduction is applied to the reward only with that probability perreward()call, 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.
Example
>>> import numpy as np >>> np.random.seed(42) >>> >>> # Initialize environment >>> env = ContinuousLaserTagPOMDP(discount_factor=0.95) >>> >>> # Get initial state >>> initial_state = env.initial_state_dist().sample()[0] >>> >>> # Sample complete step >>> action = np.array([1.0, 0.0, 0.0]) >>> next_state, observation, reward = env.sample_next_step(initial_state, action) >>> >>> # Check terminal condition >>> env.is_terminal(initial_state) False
Example
Risk-sensitive evaluation – a 10%-tail-risk environment suitable for benchmarking ICVaR-aware planners against expected-value MCTS:
>>> env = ContinuousLaserTagPOMDP( ... discount_factor=0.95, ... dangerous_area_penalty=150.0, ... dangerous_area_hit_probability=0.1, ... )
- Parameters:
discount_factor (float)
name (str)
robot_radius (float)
opponent_radius (float)
tag_radius (float)
tag_reward (float)
tag_penalty (float)
step_cost (float)
measurement_noise (float)
robot_transition_cov_matrix (np.ndarray)
opponent_transition_cov_matrix (np.ndarray)
evasion_speed (float)
dangerous_area_radius (float)
dangerous_area_penalty (float)
dangerous_area_hit_probability (float)
is_dangerous_area_hit_terminal (bool)
output_dir (Optional[Path])
debug (bool)
use_queue_logger (bool)
initial_state (Optional[np.ndarray])
opponent_policy (OpponentPolicy)
- compute_metrics(histories)[source]
Compute all seven metrics, in declaration order.
- Parameters:
- Return type:
- Returns:
All seven metrics, 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:
ContinuousLaserTagVisualizer
- get_metric_names()[source]
Get names of environment-specific metrics.
This method returns the names of custom metrics that this environment computes in the compute_metrics() method. It enables users to discover what metrics are available for hyperparameter optimization.
- Return type:
- Returns:
List of metric names that this environment produces. Derived from
get_metric_specs(), so declaring a spec is enough; environments with a bespokecompute_metricsoverride this directly instead.
Note
Subclasses that override compute_metrics() should also override this method to return the names of metrics they produce. Use an Enum to ensure consistency between the names returned here and the names used in compute_metrics().
- get_metric_specs()[source]
Declare the metrics derived from the per-step channels.
- Return type:
- Returns:
Specs for the five state-derived metrics, in enum order. The two reward-derived metrics are produced by
compute_metrics().
- 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).
- hash_observation(observation)[source]
Return a hashable key consistent with
is_equal_observation().Used by tree-search planners to index belief children by observation in O(1). The returned key MUST satisfy the contract:
is_equal_observation(a, b) implies hash_observation(a) == hash_observation(b)
- Parameters:
observation (
Any) – Observation to hash.- Returns:
the observation itself when it is already hashable).
- Return type:
- Raises:
NotImplementedError – If the observation is not hashable and the subclass has not provided an override. Subclasses with non-hashable observations (e.g.
np.ndarray) MUST override.
- 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.
- observation_log_probability_single(next_state, action, observation)[source]
Scalar log-likelihood for one
(next_state, observation)pair.Per-state fast-path used by incremental belief updates (e.g. POMCPOW’s
WeightedParticleBeliefStateUpdate.inplace_update()) to skip the per-call numpy setup overhead of the batchedobservation_log_probability()path on a singleton input.The default falls back to the batched method with a one-element observations list. Envs with cheap scalar likelihoods (e.g. the 2-D Gaussian on Push or the cached-inverse-cov path on ContinuousLightDark) should override to skip array allocation.
- 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,).
- property reward_requires_next_state: bool
Reward depends on the realised
next_stateiff hazard-terminal is on.When enabled, the dangerous-area penalty is deterministic given the terminal slot set during the transition, so drivers must sample the transition first and thread the realised
next_stateintoreward().
- 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 dispatched to native C++ via
cont_simulate_rollout.Pre-samples actions from
action_sampler, packs them into a(N, 3)buffer, and runs the full discounted-return loop inside C++. Results are numerically identical to theEnvironment.simulate_random_rollout()Python fallback.When
dangerous_area_hit_probability < 1.0, falls back to the Python rollout: the native kernel applies the dangerous-area penalty deterministically per step, which contradicts the stochastic semantics; routing through Pythonreward()keeps the per-step Bernoulli intact.Also falls back when
dangerous_areasis non-empty: the C++cont_simulate_rolloutkernel scores the danger penalty against the pre-transition robot position, while the Pythonreward()path (post-fix) consumes the realised post-transition position. Until the C++ kernel is rebuilt this is the only correctness-preserving path for configs with danger areas.
- step_info(state, action, next_state)[source]
Report tag status and hazard exposure for this step.
- Parameters:
- Return type:
- Returns:
The per-step channels.
recorded_stepis a constant 1.0 so that summing it reproduceslen(history.history), terminal bookkeeping step included.
Note
tag_success_rateandaverage_failed_tag_attemptsare defined in terms of the realised reward, whichstep_infois not given, so they stay incompute_metrics().
- class POMDPPlanners.environments.laser_tag_pomdp.continuous_laser_tag_pomdp.ContinuousLaserTagPOMDPDiscreteActions(discount_factor, name='ContinuousLaserTagPOMDPDiscreteActions', grid_size=(11.0, 7.0), walls=None, robot_radius=0.3, opponent_radius=0.3, tag_radius=0.5, tag_reward=10.0, tag_penalty=10.0, step_cost=1.0, measurement_noise=1.0, robot_transition_cov_matrix=array([[0.1, 0.], [0., 0.1]]), opponent_transition_cov_matrix=array([[0.05, 0.], [0., 0.05]]), evasion_speed=0.6, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, dangerous_area_hit_probability=1.0, is_dangerous_area_hit_terminal=False, output_dir=None, debug=False, use_queue_logger=False, initial_state=None, opponent_policy=OpponentPolicy.EVADE)[source]
Bases:
ContinuousLaserTagPOMDP,DiscreteActionsEnvironmentContinuous LaserTag POMDP with discrete string actions.
Actions:
"up","down","right","left","tag".Example
>>> import numpy as np >>> np.random.seed(42) >>> >>> env = ContinuousLaserTagPOMDPDiscreteActions(discount_factor=0.95) >>> >>> initial_state = env.initial_state_dist().sample()[0] >>> actions = env.get_actions() >>> >>> action = actions[0] >>> next_state, observation, reward = env.sample_next_step(initial_state, action) >>> >>> env.is_terminal(initial_state) False
- Parameters:
discount_factor (float)
name (str)
robot_radius (float)
opponent_radius (float)
tag_radius (float)
tag_reward (float)
tag_penalty (float)
step_cost (float)
measurement_noise (float)
robot_transition_cov_matrix (np.ndarray)
opponent_transition_cov_matrix (np.ndarray)
evasion_speed (float)
dangerous_area_radius (float)
dangerous_area_penalty (float)
dangerous_area_hit_probability (float)
is_dangerous_area_hit_terminal (bool)
output_dir (Optional[Path])
debug (bool)
use_queue_logger (bool)
initial_state (Optional[np.ndarray])
opponent_policy (OpponentPolicy)
- 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).
- 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.
- observation_log_probability_single(next_state, action, observation)[source]
Scalar log-likelihood for one
(next_state, observation)pair.Per-state fast-path used by incremental belief updates (e.g. POMCPOW’s
WeightedParticleBeliefStateUpdate.inplace_update()) to skip the per-call numpy setup overhead of the batchedobservation_log_probability()path on a singleton input.The default falls back to the batched method with a one-element observations list. Envs with cheap scalar likelihoods (e.g. the 2-D Gaussian on Push or the cached-inverse-cov path on ContinuousLightDark) should override to skip array allocation.
- 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 dispatched to native C++ via
cont_simulate_rollout.Pre-samples actions from
action_sampler, packs them into a(N, 3)buffer, and runs the full discounted-return loop inside C++. Results are numerically identical to theEnvironment.simulate_random_rollout()Python fallback.When
dangerous_area_hit_probability < 1.0, falls back to the Python rollout: the native kernel applies the dangerous-area penalty deterministically per step, which contradicts the stochastic semantics; routing through Pythonreward()keeps the per-step Bernoulli intact.Also falls back when
dangerous_areasis non-empty: the C++cont_simulate_rolloutkernel scores the danger penalty against the pre-transition robot position, while the Pythonreward()path (post-fix) consumes the realised post-transition position. Until the C++ kernel is rebuilt this is the only correctness-preserving path for configs with danger areas.
See also
Batched torch model:
POMDPPlanners.environments.laser_tag_pomdp.laser_tag_vectorized_model.LaserTagVectorizedModel(grid variant) andPOMDPPlanners.environments.laser_tag_pomdp.ContinuousLaserTagVectorizedModel(ContinuousLaserTagPOMDPDiscreteActions).Base Environment Class — the full catalog and the environment interface.