API reference¶
Environments¶
gridhunt.make ¶
make(env_id, render_mode=None, trainable_prey=None, **kwargs)
Create a registered GridHunt environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env_id
|
str
|
a registered ID such as |
required |
render_mode
|
str | None
|
|
None
|
trainable_prey
|
ids of prey to control as agents instead of moving by rule. |
None
|
|
**kwargs
|
override any setting of the registered scenario (for example
|
{}
|
Returns:
| Type | Description |
|---|---|
|
A PettingZoo |
Example
env = gridhunt.make("GridHunt-ToxicStag-v0", max_steps=200, reward_mode="team") observations, infos = env.reset(seed=0)
gridhunt.core.GridHunt ¶
GridHunt(grid_size, predators, prey, max_steps, entities=None, render_mode=None, action_mode='single', observation_mode='coords', gui_config=None, trainable_prey=None, terrain_config=None, observation_encoders=None, use_action_mask=False, agent_role_map=None, encoder_order=None, reward_mode='individual', prey_motion='static', prey_move_probability=0.5)
Bases: ParallelEnv
Grid predator-prey environment with a PettingZoo ParallelEnv API.
Use gridhunt.make for the registered scenarios; construct this class (or a
scenario subclass) directly to build a custom one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_size
|
(width, height) of the grid. |
required | |
predators
|
list of |
required | |
prey
|
list of |
required | |
max_steps
|
episode length; agents are truncated after this many steps. |
required | |
entities
|
non-capturable objects, drawn by the renderer but never observed by agents (for example cues shown only to a human participant). |
None
|
|
render_mode
|
|
None
|
|
observation_mode
|
one of |
'coords'
|
|
gui_config
|
buttons, dropdowns and the information bar for |
None
|
|
trainable_prey
|
ids of prey that are controlled as agents instead of moving by rule. |
None
|
|
terrain_config
|
terrain types with passability, speed and generation settings. |
None
|
|
observation_encoders
|
list[str] | None
|
extra features appended to observations: |
None
|
use_action_mask
|
bool
|
report each agent's valid moves in |
False
|
agent_role_map
|
dict[str, list[str]] | None
|
|
None
|
encoder_order
|
list[str] | None
|
order in which the observation encoders are appended. |
None
|
reward_mode
|
str
|
|
'individual'
|
prey_motion
|
str
|
|
'static'
|
prey_move_probability
|
float
|
probability that a moving prey moves on a given step. |
0.5
|
state ¶
state()
Compact global state for centralised critics (PettingZoo ParallelEnv.state).
Layout, all values in [0, 1]: - per agent (possible_agents order): x, y normalized by the grid size - per prey (sorted ids): x, y, present (0 once removed), toxic - per terrain type (sorted): a flattened one-hot grid of its cells
action_mask ¶
action_mask(agent_id)
Which of the 5 actions move the agent (stay is always valid), as float32 0/1 values.
Uses the movement rules without randomness: a cell that can be entered with some probability counts as reachable.
render ¶
render()
Draw the current state.
Returns an RGB array of shape (height, width, 3) for render_mode="rgb_array",
prints the grid for "console" and updates the window for "gui".
set_entities ¶
set_entities(entities)
Replace the human-only entities; they appear at the next reset().
Entities are drawn by the renderer but are never part of observations, state() or the dynamics. Entities without a position are placed on a random cell at every reset.
set_prey ¶
set_prey(prey)
Replace the prey settings (for example a stag's toxic probability) from the next reset().
The new prey must have the same ids as the current ones, so observation and state spaces stay the same.
gridhunt.wrappers.CommunicationWrapper ¶
CommunicationWrapper(env, vocab_size)
Bases: ParallelEnv
Adds an explicit communication channel ("cheap talk") to a GridHunt env.
Each step every agent chooses a move and one of vocab_size message tokens,
encoded as a single action: action = move + num_moves * token. Every agent's
next observation ends with all agents' tokens from that step (one one-hot block
per agent, in possible_agents order; all zero after reset). The tokens are also
appended to state() so centralised critics see them, and are reported in every
agent's infos[agent_id]["messages"].
Tokens have no meaning to the environment: any meaning must be learned. Moves 0-4 are therefore still valid actions (token 0).
Agents and prey¶
gridhunt.agents.Predator ¶
Predator(predator_id, position=None, status=None, capture_power=1, limited_vision_radius=1, speed=1, render_sprite=MAGENTA_HUNTER_SPRITE, immune_to_terrain=False, restricted_terrains=None)
Controllable hunter agent.
gridhunt.agents.Prey ¶
Prey(prey_id, reward, position=None, prey_type=None, respawn=False, status=None, capture_power_required=1, console_sprite='T', render_sprite=STAG_SPRITE, overcrowding_penalty=0, speed=1, immune_to_terrain=False, restricted_terrains=None)
Capturable target.
gridhunt.agents.Stag ¶
Stag(prey_id, position=None, capture_power_required=2)
gridhunt.agents.Hare ¶
Hare(prey_id, render_sprite=HARE_SPRITE, speed=1, position=None)
gridhunt.agents.ToxicStag ¶
ToxicStag(prey_id, position=None, toxic_probability=0.5, toxic_render_sprite=TOXIC_STAG_SPRITE, toxic_lifetime=5)
Bases: Prey
Stag variant with toxic/healthy respawn state.
Each time it appears the stag is toxic with probability toxic_probability. A toxic stag
that nobody catches moves to a random cell after toxic_lifetime steps, with its toxicity
drawn again; a healthy one stays until it is caught.
steps a toxic stag stays put. An int (the benchmark uses 5), a (low, high)
pair to draw it uniformly from that range each time the stag turns toxic, or None for a
toxic stag that stays until it is caught. A fixed lifetime is a cue in itself: a stag that
has stayed longer than that must be healthy, so agents without the toxicity flag can infer it.
gridhunt.agents.Building ¶
Building(prey_id, position=None, reward=1, capture_power_required=1, trap_probability=0.0, trap_penalty=0, console_sprite='B', render_sprite=BUILDING_SPRITE)
gridhunt.agents.Pig ¶
Pig(prey_id, render_sprite=None, speed=1, position=None)
gridhunt.agents.Entity ¶
Entity(entity_id, position=None, console_sprite='E', render_sprite=PLANT_SPRITE)
Non-capturable world object.
Scripted policies¶
gridhunt.policies ¶
Scripted (non-learning) policies: baselines and ready-made teammates.
- RandomPolicy: uniform random actions.
- IdlePolicy: always STILL.
- GreedyPolicy: each predator walks the shortest path (BFS over the moves it can actually make, by the environment's movement rules) to the prey with the best reward per step of distance, and waits on it until captured. With its defaults it reads the true state, including whether a stag is toxic, so it is an informed heuristic, not an upper bound.
Every policy can be called two ways:
policy.act(env, agent_id), as the benchmark does;policy(observation, agent_id, env), the teammate interface used bygridhunt.hat.
Policies read the environment state (env.predators, env.prey, env.terrain_at) and never draw from the environment's random generators, so they do not change its trajectory.
RandomPolicy ¶
RandomPolicy(seed=0)
Bases: _Policy
Uniform random actions from its own seeded generator.
IdlePolicy ¶
Bases: _Policy
Always STILL.
GreedyPolicy ¶
GreedyPolicy(active_agents=None, prey_types=None, avoid_harmful=True)
Bases: _Policy
Scripted team: go to the best reward-per-distance prey and wait there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
active_agents
|
the predators actually playing (default: all). Prey needing more capture power than these agents have together are ignored, so a team that has lost a member re-plans instead of waiting for a partner who never comes. |
None
|
|
prey_types
|
only chase prey of these types (for example |
None
|
|
avoid_harmful
|
skip prey whose current reward is negative (a toxic stag). With
|
True
|
Human-agent teaming¶
gridhunt.hat.HumanSession ¶
HumanSession(env, humans=None, teammates=None, teams=None, initial_team=None, buttons=(), pause_button=True, info=None, log=None, step_interval=None, turn_timeout=None, gui_config=None, info_lines=2, fps=30, headless=False, event_source=None, pause_key=pygame.K_p, quit_key=pygame.K_ESCAPE, keys=None)
Run episodes of a GridHunt environment with human participants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
a GridHunt environment, created without a render mode; the session opens the window. |
required | |
humans
|
|
None
|
|
teammates
|
|
None
|
|
teams
|
|
None
|
|
buttons
|
extra |
()
|
|
pause_button
|
add a Pause button (the pause key works either way). |
True
|
|
info
|
text for the information bar, or |
None
|
|
log
|
a |
None
|
|
step_interval
|
seconds per step. None (default when there are humans) waits for every human to choose; a number advances on a timer, and humans who have not pressed a key by then stay still. |
None
|
|
turn_timeout
|
when waiting for humans, give up after this many seconds and let them
stay still (logged with the source |
None
|
|
gui_config
|
extra renderer settings. |
None
|
|
info_lines
|
lines reserved for the information text. |
2
|
|
fps
|
frames drawn per second while waiting. |
30
|
|
headless
|
draw to a hidden window instead of showing one (tests, dry runs). |
False
|
|
event_source
|
callable returning the pending pygame events (default
|
None
|
|
pause_key
|
key that pauses and resumes (default P). |
K_p
|
|
quit_key
|
key that ends the session (default Escape). |
K_ESCAPE
|
|
keys
|
|
None
|
run_episode ¶
run_episode(seed=None, max_steps=None, stop_when=None, start_paused=False, **fields)
Play one episode and return an EpisodeResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
passed to |
None
|
|
max_steps
|
end after this many steps (the environment's own limit still applies). |
None
|
|
stop_when
|
|
None
|
|
start_paused
|
show the episode but hold it until |
False
|
|
**fields
|
extra values stored in the episode's log records (for example a condition). |
{}
|
ask ¶
ask(questionnaire, responder=None)
Show a questionnaire in the window; returns {item_id: answer} (logged).
end_episode ¶
end_episode(reason='skipped')
End the current episode after this frame (for example from a Skip button).
log_event ¶
log_event(name, **data)
Write an event record (if logging) tagged with the current episode and step.
episode_t is the time in seconds since the episode started (None before the first
episode), so the time from an episode appearing to a button press can be read directly.
gridhunt.hat.Button
dataclass
¶
Button(label, on_press)
A button in the information bar. on_press(session) runs when it is clicked.
gridhunt.hat.EpisodeResult
dataclass
¶
EpisodeResult(episode, seed, steps, team_return, captures, end_reason, duration_s)
gridhunt.hat.SessionLog ¶
SessionLog(directory, participant='anonymous', condition=None, metadata=None, log_state=True, on_record=None)
Writes one participant's session to JSON Lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
folder for the log files (created if needed). |
required | |
participant
|
participant id, used in the file name. |
'anonymous'
|
|
condition
|
experimental condition, stored in every file. |
None
|
|
metadata
|
any extra information to store in the metadata file. |
None
|
|
log_state
|
also store |
True
|
|
on_record
|
called with every record after it is written, for example to forward events to a lab streaming or eye-tracking system. |
None
|
gridhunt.hat.Questionnaire ¶
Questionnaire(items, title=None, id=None, font_size=20, theme=None)
An ordered list of items: Message, Likert, Scale, Choice, Text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
the items, shown in order. |
required | |
title
|
shown above every item with the item number, and stored as the log's id. |
None
|
|
id
|
id stored in the log (default: the title). |
None
|
|
font_size
|
text size in pixels. |
20
|
|
theme
|
a pygame_gui theme (dict or path) to restyle the screens completely. |
None
|
gridhunt.hat.Message
dataclass
¶
Message(text, button='Continue', id=None)
A screen of text with a single button, for instructions and breaks.
gridhunt.hat.Likert
dataclass
¶
Likert(id, prompt, points=7, anchors=('Strongly disagree', 'Strongly agree'))
A rating on a scale of points (answer: 1..points).
gridhunt.hat.Choice
dataclass
¶
Choice(id, prompt, options=list())
One option out of several (answer: the option text).
gridhunt.hat.Text
dataclass
¶
Text(id, prompt, required=False, button='Next')
Free text (answer: the text entered).
Pretrained teams¶
gridhunt.zoo ¶
Pretrained teams from the GridHunt benchmark, runnable with numpy alone.
Each model is one trained team (IPPO, MAPPO or HAPPO) for one benchmark scenario, exported from the benchmark runs. Two runs per scenario and algorithm are published: the seed with the median final score (representative of the algorithm) and the best seed (the strongest teammates). Models are downloaded on first use, checked against their SHA-256 hash and cached.
from gridhunt import zoo
zoo.list_models(scenario="toxic_stag")
team = zoo.load("toxic_stag", "mappo", rank="best")
env = team.make_env() # the scenario exactly as it was trained
observations, _ = env.reset(seed=0)
while env.agents:
observations, *_ = env.step(team.act(observations))
A team is also a teammate for gridhunt.hat.HumanSession: it is called as
team(observation, agent_id, env), so teammates={"predator_1": team} lets a trained
agent play alongside a participant.
Downloads go to $GRIDHUNT_ZOO_DIR or ~/.cache/gridhunt/zoo; set $GRIDHUNT_ZOO_URL to
use a mirror.
ZooTeam ¶
ZooTeam(meta, arrays, rng=None)
A trained team: one actor per agent (IPPO, HAPPO) or one shared actor (MAPPO).
logits ¶
logits(agent, observation)
Action logits for one agent; observation may be one vector or a batch.
act_agent ¶
act_agent(agent, observation, greedy=False)
One agent's action. Sampled from the policy by default (as the benchmark evaluates).
act ¶
act(observations, greedy=False)
Actions for every agent in observations (a dict from env.reset/env.step).
__call__ ¶
__call__(observation, agent_id, env=None)
Teammate interface for gridhunt.hat.HumanSession.
make_env ¶
make_env(**overrides)
The environment the team was trained in (benchmark settings), with optional overrides.
Observation settings must stay as trained; overriding max_steps or render_mode
is fine.
list_models ¶
list_models(scenario=None, algo=None, rank=None)
Published models, optionally filtered: a list of dicts with scenario, algo,
rank, seed, env_id, file, sha256 and the final evaluation score.
load ¶
load(scenario, algo, rank='median', seed=None, rng=None)
Load a published team.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
a benchmark scenario name, for example |
required | |
algo
|
|
required | |
rank
|
|
'median'
|
|
seed
|
pick a specific training seed instead of a rank (only if that run is published). |
None
|
|
rng
|
seed or |
None
|
load_file ¶
load_file(path, rng=None)
Load a team from a local .npz file written by the benchmark's export script.