Chicheck Invaders

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.

ChicheckInvadersPOMDP is an arcade shooter written as a POMDP. A ship on row 0 of a grid has to clear a flock of chickens before one of them reaches it.

Each chicken is either patrolling or diving, and which it is stays hidden. Two noisy sensors each report only half of a chicken’s position, so the ship has to aim, move and decide when to shoot from a belief about where the flock is and which birds are about to dive.

What the agent sees and does

  • State — one float64 vector of length 4 + 5 * num_chickens: step, ship column, cooldown, ship-hit flag, then (column, row, direction, mode, alive) per chicken, with direction -1/+1 and mode 0 patrol or 1 dive. Length 24 at the defaults.

  • Actions (discrete) — the ints 0 stay, 1 left, 2 right, 3 fire.

  • Observations (discrete) — one float64 vector of length 1 + 5 * num_chickens: a noisy reading of the ship’s column, then (camera reported, camera offset, radar reported, radar rows, radar drop) per chicken. Every value is an integer; masked fields are 0.0. With observation_mode="full" the observation is the state.

Formal definition

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

State space. The field has \(W\) = num_columns columns and \(H\) = num_rows rows; row \(0\) is the ship’s row and rows count upward. There are \(N\) = num_chickens chickens. The state is the ship’s block, then one fixed slot per chicken — dead slots are carried for the whole episode, so the vector length never changes:

\[s = \big(t,\; x,\; \text{cool},\; \mathrm{hit},\; (u_i,\, v_i,\, d_i,\, \text{mode}_i,\, \text{alive}_i)_{i=1}^{N}\big)\]
\[\begin{split}S = \;&\mathbb{Z}_{\geq 0} \times \{0..W{-}1\} \times \mathbb{Z}_{\geq 0} \times \{0,1\} \\ &\times \big(\{0..W{-}1\} \times \{0..H{-}1\} \times \{-1, +1\} \times \{\textsf{patrol}, \textsf{dive}\} \times \{0,1\}\big)^{N}\end{split}\]

with:

  • \(t\) the step count;

  • \(x\) the ship column;

  • \(\text{cool}\) the steps left before the gun can fire again;

  • \(\mathrm{hit} = 1\) once the ship is destroyed;

  • \(u_i, v_i\) chicken \(i\)’s column and row;

  • \(d_i\) its patrol direction (\(-1\) toward lower columns, \(+1\) toward higher);

  • \(\text{mode}_i\) whether it patrols or dives;

  • \(\text{alive}_i = 1\) while it is alive.

Action space

\[A = \{\textsf{stay},\; \textsf{left},\; \textsf{right},\; \textsf{fire}\} = \{0, 1, 2, 3\}\]
  • \(0\) stay — the ship holds its column;

  • \(1\) left — the ship moves one column down, \(x - 1\), clamped at the wall;

  • \(2\) right — the ship moves one column up, \(x + 1\), clamped at the wall;

  • \(3\) fire — the ship shoots straight up its column if the gun is ready; otherwise it does what stay does.

Observation space. In ObservationMode.FULL the observation is the state, \(Z = S\), and the problem is an MDP. In the default ObservationMode.PARTIAL every reading is an integer, and a masked field reads \(0\):

\[Z = \mathbb{Z} \times \big(\{0,1\} \times \mathbb{Z} \times \{0,1\} \times \mathbb{Z} \times \{-1, 0\}\big)^{N}\]

with these components, in order:

  • \(\hat x\) — a noisy reading of the ship’s column;

  • per chicken \(i\):

    • \(c_i \in \{0,1\}\) — \(1\) if the camera reported it;

    • \(\hat e_i\) — a noisy reading of its column minus the ship’s column;

    • \(r_i \in \{0,1\}\) — \(1\) if the radar reported it;

    • \(\hat n_i\) — a noisy reading of its row;

    • \(\hat f_i \in \{-1, 0\}\) — \(-1\) if the radar reports it diving, \(0\) otherwise.

A field whose sensor did not report reads \(0\).

Transition model. One step resolves in this order:

  1. Ship moves. \(x' = \mathrm{clip}(x + \Delta_a,\, 0,\, W{-}1)\), with \(\Delta = -1, +1\) for left, right and \(0\) otherwise.

  2. Shot resolves. The gun discharges iff \(a = \textsf{fire}\) and \(\text{cool} \leq 0\); the cooldown is the only thing that can block it. A discharge is hitscan and kills

    \[i^\star(s) = \arg\min_{i} \{v_i : \text{alive}_i = 1,\; u_i = x',\; v_i \geq 1\}\]

    the lowest live chicken in the ship’s column (ties to the lower slot), setting \(\text{alive}_{i^\star} \leftarrow 0\); \(i^\star = \emptyset\) means the shot misses. Then \(\text{cool}' = \texttt{fire\_cooldown}\) if it fired, else \(\max(\text{cool} - 1, 0)\).

  3. Dive coins. One Bernoulli per slot, alive or not, so the number of random draws a step consumes never depends on how the episode is going:

    \[\Pr[\text{mode}'_i = \textsf{dive} \mid \text{mode}_i = \textsf{patrol},\, \text{alive}'_i = 1] = p_d = \texttt{dive\_probability}\]

    A dive is absorbing until the chicken pulls up. This is the only stochastic part of \(T\).

  4. Flock moves. A diving chicken descends, \(v'_i = v_i - 1\). A patrolling one walks sideways and bounces off the walls, reversing and then stepping, so it never stands still against a wall:

    \[\begin{split}d'_i = \begin{cases} -d_i & u_i + d_i \notin \{0..W{-}1\} \\ d_i & \text{otherwise} \end{cases}, \qquad u'_i = u_i + d'_i\end{split}\]
  5. Arrivals settle. A live chicken at \(v'_i = 0\) in the ship’s column destroys it (\(\mathrm{hit}' = 1\)); anywhere else it pulls up to \(v'_i = H - 1\) and returns to \(\textsf{patrol}\).

Finally \(t' = t + 1\).

Observation model. In the default ObservationMode.PARTIAL:

\[o = \big(\hat{x},\; (\,c_i,\, \hat{e}_i,\; r_i,\, \hat{n}_i,\, \hat{f}_i\,)_{i=1}^{N}\big)\]

with:

  • \(c_i, r_i \in \{0,1\}\) the camera and radar report flags;

  • \(e_i = u_i - x'\) the column offset;

  • \(n_i = v_i\) the row distance.

Every numeric channel is a rounded Gaussian,

\[G_\sigma(k; m) = F_{\mathcal{N}}\!\Big(\frac{k + \tfrac{1}{2} - m}{\sigma}\Big) - F_{\mathcal{N}}\!\Big(\frac{k - \tfrac{1}{2} - m}{\sigma}\Big)\]

with \(F_{\mathcal{N}}\) the standard normal CDF, so the readings are integers, not reals. The ship reads its own column as \(\hat{x} \sim G_{\sigma_x}(\cdot\,; x')\), \(\sigma_x\) = ship_column_noise_std — redundant evidence, since the ship’s column is decided by its own actions, present so the observation reports the ship as well as the chickens.

Each chicken is reported through two sensors with disjoint geometry. Dead chickens are inside neither reach, so a cleared slot is never reported and its silence has likelihood 1 rather than a sensor’s miss chance:

\[\begin{split}\text{camera reach}_i &\iff \text{alive}_i = 1 \;\wedge\; |e_i| \leq \texttt{camera\_slope} \cdot n_i \\ \text{radar reach}_i &\iff \text{alive}_i = 1 \;\wedge\; e_i^2 + n_i^2 \leq \texttt{radar\_radius}^2\end{split}\]

Inside reach, each sensor fires independently with its detection probability, and its reading has noise:

  • Camera. Detection probability \(p_{\text{cam}}\) = camera_detection_probability, noise \(\sigma_e\) = camera_offset_noise_std.

  • Radar. Detection probability \(p_{\text{rad}}\) = radar_detection_probability, noise \(\sigma_n\) = radar_range_noise_std.

\[\begin{split}\Pr[c_i = 1] &= p_{\text{cam}} \cdot \mathbb{1}[\text{camera reach}_i], &\hat{e}_i &\sim G_{\sigma_e}(\cdot\,; e_i) \\ \Pr[r_i = 1] &= p_{\text{rad}} \cdot \mathbb{1}[\text{radar reach}_i], &\hat{n}_i &\sim G_{\sigma_n}(\cdot\,; n_i)\end{split}\]

A firing radar also returns a dropping flag, the only channel that reports the hidden mode at all, inverted with probability \(p_f\) = drop_flag_error_probability:

\[\begin{split}\hat{f}_i = \begin{cases} f_i & \text{w.p. } 1 - p_f \\ -1 - f_i & \text{w.p. } p_f \end{cases}, \qquad f_i = -\mathbb{1}[\text{mode}_i = \textsf{dive}]\end{split}\]

A silent slot (\(c_i = r_i = 0\)) contributes its own likelihood factor — the probability of not being reported — so silence is evidence too. \(O\) depends on \(s'\) only, never on the action that produced it.

Reward function.

\[\begin{split}R(s, a, s') = \;&-\texttt{step\_cost} \;-\; \texttt{shot\_cost}\cdot\mathbb{1}[\text{gun discharged}] \\ &+\; \texttt{kill\_reward} \cdot (n_{\text{live}}(s) - n_{\text{live}}(s')) \\ &-\; \texttt{ship\_hit\_penalty} \cdot \mathbb{1}[\mathrm{hit}' = 1 \wedge \mathrm{hit} = 0] \\ &+\; \texttt{clear\_reward} \cdot \mathbb{1}[n_{\text{live}}(s') = 0 \wedge n_{\text{live}}(s) > 0]\end{split}\]

where \(n_{\text{live}}(s) = \sum_i \text{alive}_i\) is the number of live chickens and the gun discharges when \(a = \textsf{fire}\) and \(\text{cool} = 0\). A FIRE the cooldown blocks costs nothing — the gun never discharged. A shot into an empty column does discharge, misses, and is charged. The ship-hit penalty is billed on the step the ship is lost, not on every step after it: the flag stays set, and a driver that kept stepping a terminal state would otherwise charge it repeatedly.

Note

Called without \(s'\), every term except the ship-hit penalty is still exact, because a hitscan shot resolves before the dive coins are flipped. The missing term is deliberately not replaced by its expectation: a planner comparing actions at a belief node then sees the exact value of a shot that connects, and the risk it took is charged on the step the flock gets through.

Initial belief. The ship starts centred with an empty cooldown; the flock is drawn uniformly without replacement from the cells above row 0, with independent directions and modes:

\[\begin{split}(u_i, v_i)_{i=1}^{N} &\sim \mathrm{Unif}\big(\text{$N$-subsets of } \{0..W{-}1\} \times \{1..H{-}1\}\big) \\ d_i &\sim \mathrm{Unif}\{-1, +1\}, \qquad \Pr[\text{mode}_i = \textsf{dive}] = \texttt{initial\_dive\_probability}\end{split}\]

At the default \(\texttt{initial\_dive\_probability} = 0\) every episode opens with the whole flock patrolling. The opening observation is a sentinel — the ship’s known column, every chicken slot silent — taken before any sensor has run, and the belief never weights particles with it.

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

Terminal set. An episode ends when:

  • the ship is hit;

  • every chicken is dead (\(n_{\text{live}}(s) = \sum_i \text{alive}_i = 0\));

  • or the step count reaches max_steps:

\[S_T = \{s : \mathrm{hit} = 1\} \cup \{s : n_{\text{live}}(s) = 0\} \cup \{s : t \geq \texttt{max\_steps}\}\]

Dynamics

Actions are stay, left, right and fire, in that index order. A move is clamped at the walls. FIRE discharges only when the cooldown has expired; otherwise it behaves exactly like STAY and costs nothing, because nothing left the ship.

The gun is hitscan. A shot resolves inside the step that fired it, killing the lowest live chicken in the ship’s column over rows 1 to num_rows - 1, at unlimited range. A shot into a column with no live chicken misses and is charged the shot cost alone. fire_cooldown is the only rate limiter.

The shot is resolved before the dive coins are flipped and before the flock moves, for this reason. The ship picks its action from an observation of where the chickens are now, so it has to be able to hit what it aimed at. An earlier version fired a bolt that climbed one row per step; against chickens stepping sideways every step it was dodged by accident rather than by any decision the flock made, so aiming collapsed into waiting and most shots missed for reasons the ship could not have reasoned about.

One consequence: a chicken shot this step never gets to dive, so firing also removes a chicken that could have dived at the ship.

A chicken is either patrolling or diving, and which it is stays hidden. A patrolling chicken steps one column along its direction and reverses at a wall; a diving chicken drops one row. Each step every surviving patrolling chicken switches into a dive with probability dive_probability. The coin is flipped after the shot but before the chickens move, so a chicken that switches this step also drops this step.

A chicken that reaches row 0 in the ship’s column destroys it and ends the episode. One that reaches row 0 anywhere else pulls up: it goes back to patrolling at the top row, keeping its column and direction. That rule is an addition to the original design proposal, which left the case open. Without it a dive would either carry the chicken off the grid – letting the flock clear itself and making the completion bonus free – or park it on row 0, below the rows the gun covers, which is unwinnable.

State and observation contract

The state is [step, ship column, cooldown, ship hit, (column, row, direction, mode, alive) per chicken], so its length is 4 + 5 * num_chickens. A dead chicken keeps its slot. Nothing records a shot: a hitscan shot never survives the step that fired it, so there is nothing in flight for the state to carry and the only thing the gun leaves behind is the cooldown.

An observation is [own-column reading, (camera reported, camera offset, radar reported, radar rows, radar drop) per chicken], of length 1 + 5 * num_chickens. Every masked field is written as 0.0, so two readings that report the same things compare equal and hash alike; the two reported flags are what separate a masked zero from a sensor reading of zero.

The two sensors each give half an answer:

  • the camera covers a cone opening upward from the ship, with half-slope camera_slope. It reports a chicken’s column offset and says nothing about its row.

  • the radar covers a disc of radius radar_radius. It reports a chicken’s row distance and whether it is dropping, and says nothing about its column.

A chicken inside a sensor’s reach is reported with probability camera_detection_probability or radar_detection_probability; a dead one or one outside the reach is never reported. Every integer reading is drawn from a rounded Gaussian

\[G_\sigma(k; m) = F_{\mathcal{N}}\!\left(\frac{k + 1/2 - m}{\sigma}\right) - F_{\mathcal{N}}\!\left(\frac{k - 1/2 - m}{\sigma}\right), \qquad k \in \mathbb{Z},\]

which is the law of round(m + sigma * w). It is not truncated at the grid edge, so its masses sum to one over all integers and a reading may name a column that does not exist. Truncating would make the normaliser depend on the hidden quantity being inferred and would change every likelihood ratio in the belief update for no gain in realism. sigma = 0 collapses the law to a point mass.

The likelihood multiplies in one factor for every chicken slot, not only the reported ones:

\[O(o \mid s') = G_{\sigma_c}(\hat c; c') \prod_{i=1}^{N} q_i^{\text{cam}} \, q_i^{\text{rad}},\]

where a chicken:

  • in reach and reported contributes its detection probability times the noise mass;

  • in reach and silent contributes the miss chance;

  • out of reach and silent contributes 1;

  • out of reach but reported contributes 0.

Silence is therefore evidence: a chicken that a particle places well inside both sensors, on a step where neither reported it, costs that particle a factor of 0.1 * 0.1. Everything is computed in log space, with an impossible reading floored rather than set to negative infinity, because 0 * -inf becomes a NaN inside weight normalisation.

Rewards

The reward terms:

  • +10 per chicken killed;

  • -1 per shot fired (a FIRE the cooldown blocks is free);

  • -0.1 every step;

  • -50 when a chicken reaches the ship;

  • +50 when the last chicken dies.

A shot that connects therefore pays -0.1 - 1 + 10 on the step it was fired.

The declared reward range is enumerated rather than estimated. A step kills at most one chicken, and a kill can only happen on a step that fired, so the best step is the shot that takes the last chicken and collects the bonus with it: kill_reward + clear_reward - step_cost - shot_cost.

The declared minimum stacks the step cost, the shot cost and the ship-hit penalty, and that sum is deliberately not reachable. The gun kills the lowest chicken in the ship’s column, and a chicken can only reach the ship by diving down that same column, so any step that could be overrun gave the shot a target and the kill reward comes back; firing into an empty column cannot be overrun at all. The worst a run can score is being overrun without firing, exactly one shot cost above the bound. The wider bound is kept because it costs nothing and survives a change to the gun’s reach, where a tight one derived from that argument would not.

reward_requires_next_state is True, but only because of the ship hit. Under hitscan the kill and the completion bonus are functions of (state, action) alone – the shot resolves before anything random happens – so a call without a successor returns everything except the -50. That missing term is deliberately not replaced by its expectation: a planner comparing actions at a belief node sees the exact value of a shot that connects, and the risk it took is charged on the step the flock gets through.

An episode ends:

  • when the flock is cleared;

  • when a chicken reaches the ship;

  • or at max_steps.

Key settings

The default world is 8 columns by 7 rows with 4 chickens and a 60-step budget. The ship starts in the middle column with an empty sky.

observation_mode="full" makes the observation the state itself, for a fully observable control baseline on identical dynamics and reward. noiseless_preset() returns the constructor keywords that make every sensor always report, add no noise and never invert the drop flag, so the observation becomes a deterministic function of the successor. The transition is untouched: dives are still drawn, which is what keeps the preset a POMDP whose only certainty is the reading.

from POMDPPlanners.environments.chicheck_invaders_pomdp import (
    ChicheckInvadersPOMDP,
    noiseless_preset,
)

deterministic_sensors = ChicheckInvadersPOMDP(**noiseless_preset())
fully_observable = ChicheckInvadersPOMDP(observation_mode="full")

Metrics

  • task_completion_rate is the fraction of episodes that cleared the flock, reduced with ANY – clearing happens once and ends the episode.

  • ended_by_goal_rate, ended_by_failure_rate and ended_by_timeout_rate reduce with LAST and sum to one per episode.

  • average_episode_length, average_chickens_killed and average_shots_fired are per-episode sums.

The danger is a chicken getting close, reported both ways: average_hits_taken counts the times the flock got through, and max_chicken_encroachment_cells is the severity. The latter is reported as max(num_columns - 1, num_rows - 1) minus the smallest Chebyshev distance from the ship to a live chicken, so larger means closer and the distance itself is recoverable by subtraction. It is reported this way round because the episode reduction available for a severity is MAX and there is no MIN.

average_shot_accuracy is kills per shot, which under hitscan is hits per shot. It is the one metric that is not a channel reduction – a ratio of two per-episode sums cannot be expressed as a reduction over a single channel, and a mean of per-step ratios is not the episode’s ratio – so it is computed in compute_metrics from the same two channels the counts are built from. Episodes that never fired are left out of the average rather than scored as zero.

Visualization

Runs write a trace of each episode through the environment’s episode visualizer. The results site replays it in 3D, as the replay on this page does.

Limits

ChicheckInvadersVectorizedModel is the torch model that VOPP plans on. It reads the grid, flock, sensor, reward and step-budget arguments from the environment and supports both observation modes, so it declines no configuration. Like the scalar environment, it keeps stepping a terminal state: the step counter advances and the flock moves.

The model defaults to float32. In float32 a sensor reading whose rounded-Gaussian mass is below about 1e-45 (about 14 noise standard deviations off) scores the impossible floor -1e18, where the scalar environment returns a finite log-probability below -103. Build the model with dtype=torch.float64 when the belief must rank such far-off readings. Scalar PFT_DPW also runs on the environment directly, and the QA gate uses it.

The step, the sensor readings, their likelihood and the reward run in C++ (chicheck_invaders_pomdp/_native), which draws from its own random number generator: np.random.seed does not reach it, and _native.set_seed does.

Can I use?

ChicheckInvadersPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

Native C++ backend

✔️

Vectorized (torch) model

✔️ ChicheckInvadersVectorizedModel (both observation modes)

In the get_environment registry

✔️

Optional dependencies

None

Example

from POMDPPlanners.environments.chicheck_invaders_pomdp import ChicheckInvadersPOMDP
from POMDPPlanners.utils.belief_factory import create_environment_belief

env = ChicheckInvadersPOMDP()
belief = create_environment_belief(env, n_particles=200)

Parameters

class POMDPPlanners.environments.chicheck_invaders_pomdp.ChicheckInvadersPOMDP(num_columns=8, num_rows=7, num_chickens=4, fire_cooldown=1, dive_probability=0.15, initial_dive_probability=0.0, camera_detection_probability=0.9, radar_detection_probability=0.9, ship_column_noise_std=0.5, camera_offset_noise_std=1.0, radar_range_noise_std=1.0, drop_flag_error_probability=0.1, camera_slope=1.0, radar_radius=6.0, observation_mode=ObservationMode.PARTIAL, kill_reward=10.0, shot_cost=1.0, step_cost=0.1, ship_hit_penalty=50.0, clear_reward=50.0, max_steps=60, discount_factor=0.95, name='ChicheckInvaders', output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: DiscreteActionsEnvironment

Clear a flock of chickens from a grid before one of them reaches the ship.

The task is complete when every chicken slot is dead. It fails when a chicken reaches the ship’s cell, and times out at max_steps. Those three are the only ways an episode ends, and they are what the three ended_by_* metrics report.

Parameters:
  • num_columns (int)

  • num_rows (int)

  • num_chickens (int)

  • fire_cooldown (int)

  • dive_probability (float)

  • initial_dive_probability (float)

  • camera_detection_probability (float)

  • radar_detection_probability (float)

  • ship_column_noise_std (float)

  • camera_offset_noise_std (float)

  • radar_range_noise_std (float)

  • drop_flag_error_probability (float)

  • camera_slope (float)

  • radar_radius (float)

  • observation_mode (ObservationMode | str)

  • kill_reward (float)

  • shot_cost (float)

  • step_cost (float)

  • ship_hit_penalty (float)

  • clear_reward (float)

  • max_steps (int)

  • discount_factor (float)

  • name (str)

  • output_dir (Path | None)

  • debug (bool)

  • use_queue_logger (bool)

chickens(state)[source]

Return the (num_chickens, 5) chicken block of state as a view.

Parameters:

state (ndarray) – A state vector.

Return type:

ndarray

Returns:

Rows of (column, row, direction, mode, alive).

coin_eligible_slots(state, action)[source]

Which slots’ dive coins actually change the successor of (state, action).

A coin is drawn for every slot on every step, but _step_once() only applies it where the chicken is still alive and patrolling – and “still alive” is evaluated after the shot. A chicken the shot just killed therefore has its coin drawn and discarded, exactly like a chicken that was already dead.

That asymmetry is the whole reason this is a method rather than two lines repeated in the sampler and the scorer. Scoring against the pre-shot flock counted the victim’s coin as “held”, which put a spurious log(1 - dive_probability) into every FIRE that killed a patroller – so that action’s transition summed to less than one – and at dive_probability = 1 it made every candidate successor unscoreable, because the victim sat in the eligible set with its switch false.

Parameters:
  • state (ndarray) – The state the step is taken from.

  • action (Any) – The action taken.

Return type:

ndarray

Returns:

A boolean mask of length num_chickens.

compute_metrics(histories)[source]

Aggregate the declared channels, then add the one ratio among them.

average_shot_accuracy is kills per shot, and a ratio of two per-episode sums is the one shape StepInfoMetric cannot express: a reduction collapses a single channel, and a mean of per-step ratios is not the episode’s ratio. It is therefore computed here, from the same two channels the counts are built from, so the three numbers cannot disagree.

Episodes that never fired are left out of the average rather than scored as zero, because zero kills from zero shots says nothing about aim. When no episode fired the ratio is undefined for the batch as a whole; it is reported as 0.0 with an unbounded interval, which is what the shared aggregator reports for any metric it cannot put an interval on.

Parameters:

histories (List[History]) – Episode histories to analyse.

Return type:

List[MetricValue]

Returns:

The channel-derived metrics followed by average_shot_accuracy.

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

ChicheckInvadersVisualizer

fires(state, action)[source]

Whether action actually discharges the gun from state.

The cooldown is the only thing that can block it. A FIRE during cooldown does exactly what STAY does and is charged nothing. This is deterministic in (state, action), which is why the shot cost can be scored without a successor.

Parameters:
  • state (ndarray) – The state fired from.

  • action (Any) – The action taken.

Return type:

bool

Returns:

True if the gun discharges.

get_actions()[source]

Return the four actions: stay, left, right, fire.

Return type:

List[int]

get_metric_names()[source]

Every metric this environment produces, including average_shot_accuracy.

Return type:

List[str]

get_metric_specs()[source]

Declare the Chicheck Invaders metrics that a per-step channel can express.

Completion reduces with ANY: clearing the flock happens once and ends the episode, so it cannot be undone by a later step. The three ended_by_* channels reduce with LAST and sum to one per episode, because still_running is exactly the complement of the other two.

The danger here is a chicken getting close, and it is reported both ways the metrics skill asks for: average_hits_taken counts the times the flock actually got through (at most one, since it ends the episode), and max_chicken_encroachment_cells is the severity – how close the nearest one ever got, which separates a planner that was never threatened from one that survived by a cell.

Return type:

List[StepInfoMetric]

Returns:

One spec per metric that a channel reduction can produce. average_shot_accuracy is not among them; see compute_metrics().

hash_action(action)[source]

Return a hashable key for an action (already an int).

Return type:

Hashable

Parameters:

action (Any)

hash_observation(observation)[source]

Return a hashable key agreeing with is_equal_observation().

Parameters:

observation (Any) – A reading.

Return type:

Hashable

Returns:

Its raw float64 bytes, which is the standard surrogate here for an ndarray observation and matches array_equal. Masked fields are stored as zeros precisely so that two readings which report the same things hash alike.

initial_observation_dist()[source]

The pre-sensor reading: the ship’s known column and no chicken reports.

Return type:

DiscreteDistribution

Returns:

A point mass on a reading that names the ship’s start column and leaves every chicken slot silent. It is a sentinel taken before any sensor has run, not a claim that the sky is empty, and the belief never weights particles with it.

initial_state_dist()[source]

A fresh flock per episode, the ship in the middle with an empty sky.

Return type:

Distribution

is_equal_observation(observation1, observation2)[source]

Check whether two readings are the same vector of numbers.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Whether the flock is cleared, the ship is gone, or time is up.

Parameters:

state (Any) – A state vector.

Return type:

bool

Returns:

True in any of those three cases.

live_chicken_count(state)[source]

Return how many chicken slots in state are still alive.

Parameters:

state (ndarray) – A state vector.

Return type:

int

Returns:

The count, between 0 and num_chickens.

max_chicken_distance

Largest Chebyshev distance any chicken can be from the ship, which is what the encroachment channel is measured back from.

observation_log_probability(next_state, action, observations)[source]

Log-likelihood of each candidate reading under one successor.

Parameters:
  • next_state (Any) – The realised successor state.

  • action (Any) – Ignored; the reading does not depend on it.

  • observations (Any) – Candidate readings.

Return type:

ndarray

Returns:

One log-probability per candidate, shape (N,).

observation_log_probability_per_state(next_states, action, observation)[source]

Log-likelihood of one reading under each candidate successor.

Return type:

ndarray

Parameters:
  • next_states (Any)

  • action (Any)

  • observation (Any)

observation_log_probability_single(next_state, action, observation)[source]

Scalar log-likelihood for one (successor, reading) pair.

Return type:

float

Parameters:
  • next_state (Any)

  • action (Any)

  • observation (Any)

reward(state, action, next_state=None)[source]

Score one step: the kill and the clear bonus, less the shot and step costs.

Without a successor, everything except the ship hit is still exact, because a hitscan shot resolves before the dive coins are flipped: the step cost, the shot cost, the kill it scores and the bonus if that kill was the last one are all functions of (state, action) alone. Only the -ship_hit_penalty term is missing, and it is deliberately not replaced by its expectation – a planner comparing actions at a belief node sees the real value of a shot that connects, and the risk it took is charged on the step the flock actually gets through.

Parameters:
  • state (Any) – The state the step was taken from.

  • action (Any) – The action taken.

  • next_state (Any) – The realised successor, or None.

Return type:

float

Returns:

The immediate reward.

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

Reward of each row of states under action, as reward() scores it.

Parameters:
  • states (Any) – An (N, state_size) array or a sequence of state vectors.

  • action (Any) – The action taken from every row.

  • next_states (Any) – Matching successors, or None.

Return type:

ndarray

Returns:

An (N,) float64 array.

property reward_requires_next_state: bool

The ship hit is the one term the dive coins decide.

Under the hitscan gun the kill and the completion bonus are both determined by (state, action) – the shot resolves before anything random happens. The ship hit is not: whether a chicken reaches row 0 depends on the dive coins this step, so the realised successor is still what the penalty has to be scored against.

sample_next_state(state, action, n_samples=1)[source]

Sample one or more successors of (state, action).

Parameters:
  • state (Any) – The state to advance.

  • action (Any) – The action taken.

  • n_samples (int) – How many independent successors to draw. Defaults to 1.

Return type:

Any

Returns:

One float64 state vector, or an (n_samples, state_size) array.

sample_next_state_batch(states, action)[source]

Sample one successor per row of states, all under action.

Parameters:
  • states (Any) – An (N, state_size) array or a sequence of state vectors.

  • action (Any) – The action applied to every row.

Return type:

ndarray

Returns:

An (N, state_size) float64 array.

sample_next_step(state, action)[source]

Sample the successor, its reading and the reward in one native call.

Draws in the order Environment.sample_next_step() does – successor, then reading – and scores the reward against the sampled successor.

Parameters:
  • state (Any) – The state to advance.

  • action (Any) – The action taken.

Return type:

Tuple[Any, Any, float]

Returns:

(next_state, observation, reward).

sample_observation(next_state, action, n_samples=1)[source]

Draw one or more readings of next_state.

The reading depends on the successor only, never on the action that produced it.

Parameters:
  • next_state (Any) – The realised successor state.

  • action (Any) – Ignored; present for the API.

  • n_samples (int) – How many independent readings to draw. Defaults to 1.

Return type:

Any

Returns:

One float64 observation vector, or an (n_samples, observation_size) array.

sensor_reach(next_state)[source]

Which chickens each sensor could report from next_state.

A dead chicken is inside neither reach, which is what makes a cleared slot silent rather than merely unlucky.

Parameters:

next_state (Any) – The realised successor state.

Return type:

Tuple[ndarray, ndarray]

Returns:

(camera reach, radar reach), each a boolean array of length num_chickens.

ship_column(state)[source]

Return the ship’s column in state.

Parameters:

state (ndarray) – A state vector.

Return type:

int

Returns:

The column index.

ship_start_column

The ship starts in the middle, which is the only column from which both walls are the same distance away.

shot_target(state)[source]

Which chicken slot a shot fired from state would kill.

The lowest live chicken in the ship’s column, over rows 1 to H - 1. Lowest rather than nearest-by-slot so the outcome cannot depend on the order the flock happens to be stored in; ties between two chickens that have walked onto one cell go to the lower slot, which is arbitrary but deterministic and cannot be observed apart.

Parameters:

state (ndarray) – The state fired from, before the flock moves.

Return type:

int

Returns:

The slot index, or -1 when the column is empty and the shot misses.

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

Discounted return of a uniform random rollout, run in C++.

The actions are drawn up front from np.random, uniformly over the four, and the steps then run in C++. That is the same law as a DiscreteActionSampler over the four actions. Any other sampler gets python_random_rollout(), so a planner’s own rollout policy is still the one followed.

Parameters:
  • state (Any) – The state the rollout starts from.

  • action_sampler (Any) – The planner’s rollout action sampler.

  • max_depth (int) – Depth at which the rollout stops.

  • discount_factor (float) – Per-step discount.

  • depth (int) – Depth already used by the search tree. Defaults to 0.

Return type:

float

Returns:

The discounted sum of rewards along the rollout.

step_info(state, action, next_state)[source]

Report the per-step channels this environment’s metrics are built on.

Draws no randomness: every channel is a deterministic function of the arguments, and the one channel that would need the transition – whether a shot left the ship – is computed from (state, action), which is where firing is decided.

Outcome channels are read from next_state when there is one, for the reason Battleship documents: the episode runner checks its step budget before it checks terminality, so an episode whose final allowed step clears the flock records no terminal bookkeeping step, and reading the outcome from state alone would score that win as a timeout.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal bookkeeping step.

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

  • next_state (Any) – The realised successor, or None on the terminal step.

Return type:

Dict[str, float]

Returns:

The channels named by ChicheckInvadersStepChannel.

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate successor of (state, action).

Everything except the dive coins is deterministic, so a candidate is scored by rebuilding it from the coins it implies and checking that the rebuild is exactly the candidate. A candidate that no set of coins produces scores IMPOSSIBLE_LOG_PROBABILITY.

Parameters:
  • state (Any) – The state advanced from.

  • action (Any) – The action taken.

  • next_states (Any) – Candidate successors.

Return type:

ndarray

Returns:

One log-probability per candidate, shape (N,).

See also