Repository navigation
Add locations: composable agent locations in shared coordinates - #3940
Conversation
|
Especially curious what you think of the "follower" concept (maybe we should call it link since it works in both directions?) |
|
Performance benchmarks:
|
|
I like where this landed. It answers most of what came up on my RFC in March: I would argue to keep Per-class declaration instead of per-space is the real change. Where I'd push back is "no frame object, units are a convention": the relationship between two spaces belongs on the spaces, declared once, where it can be checked. That's also what #3458 did with One more thing, the birds-and-trees and election models are listed as not in this PR. I'd put one of them in before this leaves draft. It's the only thing that tells us whether |
|
Tried this out locally and it reads really nicely. A few things from poking at it: Open question 2 (copy vs view). I measured all three options on this branch, swapping only the getter (numbers from my machine):
So a read-only view is slower than the copy and breaks HexGrid drawing. Orthogonal grids now draw from Pickling commit. The |
|
Cool, thanks for both your feedback. Appreciated.
I’m willing to build (some of) this back in. I think the balance is here to find a low-overhead, simple implementation.
I will include (one of) them.
Maybe we can make copy the default, and use writable view as a more performant version for modelers that know what they are doing? @quaquel I would like you to weigh in also. |
|
Copy as the default with an opt-in view sounds good. One caveat for the opt-in: with a writable view, |
|
Thanks both, this was useful. Short version: I'll keep On the relationship between spaces, I've worked through the options and one of them seems worth exploring further. I'd like your views on it. I'm personally still in doubt about it. A
|
|
Updated the PR body: the open questions are now decisions. In short:
Feedback on any of these is welcome, of course. |
|
@mesa/maintainers ready for review! Would love everybody's thoughts. |
|
On the proposed There is a separate from mesa import Agent, Model
from mesa.discrete_space import OrthogonalMooreGrid
from mesa.experimental.locations import CellLocation
class Walker(Agent):
coarse = CellLocation("coarse_grid")
fine = CellLocation("fine_grid", follows="coarse")
model = Model(rng=42)
model.coarse_grid = OrthogonalMooreGrid(
(2, 2), cell_size=20.0, random=model.random
)
model.fine_grid = OrthogonalMooreGrid(
(20, 20), cell_size=2.0, random=model.random
)
agent = Walker(model)
agent.coarse = model.coarse_grid[1, 1]
target = model.fine_grid[2, 2]
agent.fine = target
print("requested:", target.coordinate)
print("actual:", agent.fine.coordinate)
print("retained:", agent.fine is target)Actual output: Both grids cover The locations remain synchronized; the question is what a successful follower assignment promises. Matching extents through Would it make sense to require that a successful A small implementation could preflight the proposed primary's canonical position and verify that it maps back to the requested follower cell before entering or committing cells. The comparison should be cell identity, not equality of cell centers, so the existing valid fine-primary/coarse-follower case still works. Regression coverage could include first placement, a target mapping to the current primary, shifted origins, and unchanged primary/other followers on rejection. If projection is intentional, documenting that assignment may select a different cell would also resolve the ambiguity. I have run the minimal reproduction and a representable-target control against this commit's source snapshot; I have not run the full test suite. |
|
Multiple inheritance: a location from the second base is missed by I reproduced an independent registration/cleanup issue on Minimal reproduction: from mesa import Agent, Model
from mesa.experimental.continuous_space import ContinuousSpace
from mesa.experimental.locations import ContinuousLocation
class LeftAgent(Agent):
left = ContinuousLocation("left_space")
class RightAgent(Agent):
right = ContinuousLocation("right_space")
class CombinedAgent(LeftAgent, RightAgent):
pass
model = Model(rng=42)
model.left_space = ContinuousSpace([[0, 10], [0, 10]], random=model.random)
model.right_space = ContinuousSpace([[0, 10], [0, 10]], random=model.random)
agent = CombinedAgent(model)
agent.left = [1, 1]
agent.right = [8, 8]
print("registered:", [loc.name for loc in CombinedAgent._mesa_locations])
print("before remove:", len(model.left_space.active_agents), len(model.right_space.active_agents))
agent.remove()
print("in model:", agent in model.agents)
print("after remove:", len(model.left_space.active_agents), len(model.right_space.active_agents))
print("left:", agent.left)
print("right:", agent.right)Actual output: I would expect both spaces to be empty and both locations to read The cause appears to be the registration code: A minimal fix could keep the public API unchanged:
Focused regression coverage could start with the example above and its reversed base order, then cover a subclass adding another location, diamond inheritance, overrides/shadowing, and mixed I ran this reproducer and the two controls against the commit's source snapshot. I have not modified the implementation or run the full test suite. |
|
Thanks, agree on
I'd try to review it in bit depth soon. Also, Should an agent be able to have more than one |
codebreaker32
left a comment
There was a problem hiding this comment.
Approving for the locations part. I haven't reviewed #4114 yet, so this doesn't cover the grid changes it builds on.
dfb541c to
460416b
Compare
@mesa/maintainers I would love some reviews and/or checkmarks! |
|
I realize that wolf-sheep is different now, but would love to see some analysis of what explains the massive increase in run time. |
|
Fixed a small bug I: Simultaneous followers bypass the one-cell-per-space check. Two followers targeting the same grid both pass on first placement, then both add the agent. I reproduced |
|
@quaquel very fair request. The published +1035% result is from the older radius-search version: each wolf searched every animal. In a large, seed-42 profile, that meant 35,910 queries and 169 million distance evaluations. The current version checks cell occupants instead. I reran the large benchmark with five paired seeds (42–46), best of two runs per seed, on the same CPU core with Python 3.14:
The remaining slowdown is ~2.3×. Animal activations increase only ~5%; continuous movement and synchronization explain most of the extra work. The manual control produces identical trajectories, but lacks atomic follower validation; declared locations add ~0.52 s over it. Reproduction also matters: the seed-42 run creates 20,914 offspring in 20 steps, each paying first-placement/alignment checks. Profiles point to movement and offspring creation; caching space-pair validation across newborns looks like a useful follow-up. |
|
Performance benchmarks:
|
A location is an attribute declared on an agent class. Assigning to it
places the agent in a space, so an agent can be in as many spaces as it
needs without inheriting from a space-specific agent class:
class Citizen(Agent):
home = CellLocation("city") # a cell of model.city
view = ContinuousLocation("opinion") # a point in model.opinion
- A location names the model attribute holding its space. CellLocation
is CellAgent.cell under any name, and refuses a cell of another space.
ContinuousLocation keeps the agent's row on a small handle, so one
agent can be in several continuous spaces, next to
ContinuousSpaceAgents. Reading a point returns a copy, so += moves the
agent through the bounds and torus checks.
- An agent has at most one cell per discrete space and one point per
continuous space, also next to CellAgent.cell or a
ContinuousSpaceAgent's position, so it never counts twice in a space.
- follows= declares that a cell is the cell at another location of the
agent, given as the location itself or Base.name:
position = ContinuousLocation("air")
cell = CellLocation("ground", follows=position)
Only the primary stores state: writing it updates the follower, and
writing the follower moves the primary to the cell's center, or raises
if that center leads to another cell. Moves are atomic: a full cell or
a point without a cell raises, and nothing has moved, not even the
order of a cell's occupants.
- A follower's space must line up with its primary's. A grid, hex or
Voronoi cell can follow a point, and a grid cell a grid cell that is
no finer. A Network can't follow or be followed, other pairs warn,
and torus mismatches raise, as does a torus HexGrid follower.
Declaration errors raise when the class is defined.
- Each location installs a plain property, so reads stay fast, and an
agent class collects the locations of all its bases, so Agent.remove
takes the agent out of every space, also for a CellAgent whose cell
follows another location.
- ContinuousSpace queries take exclude=, so an agent can leave itself
out of its neighbors.
- Renderers find an agent's cell or position through the space, so
agents draw whatever their locations are called.
Assisted-by: Claude Opus 5.5
Assisted-by: GPT-6
The wolf-sheep example now shows locations. The animals walk as in
NetLogo's Wolf Sheep Predation (rt random 50 lt random 50 fd 1) through
a ContinuousSpace over the same area as the grid, and their grid cell
follows their position:
position = ContinuousLocation("meadow")
cell = CellLocation("grid", follows=position)
Sheep eat the grass on their cell, and wolves eat a sheep on their cell,
as NetLogo's `one-of sheep-here`. This replaces the cell-to-cell moves in
which sheep avoided wolves and wolves sought sheep. Grass is unchanged.
On the benchmark configurations, the small run takes 0.17 s and the large
one 1.8 s, against 0.07 and 0.86 s for the grid version. With NetLogo's
defaults (51x51, 100 sheep, 50 wolves, 500 steps, 10 seeds), both species
survive in 10 of 10 runs, with on average 173 sheep and 72 wolves.
Assisted-by: Claude Opus 5.5
|
Merged, thanks everyone! Potential follow-ups:
|
Summary
Adds locations to
mesa.experimental: attributes declared on an agent class that place the agent in a space, so one agent can be in as many spaces as it needs.follows=declares that two locations of an agent are the same place, so they can't drift apart. The wolf–sheep example now uses them: the animals move through a continuous meadow, and their grid cell, where the grass grows, follows their position.Builds on #4114, which places grids in shared coordinates with
cell_sizeandorigin; review that one first.Motive
This implements the smaller direction proposed in #2585 (comment), after #3939 showed that frames cost more than they give. It covers composition, plus
follows=so stacked locations can't drift apart; shared coordinates are in #4114.Usage Examples
All examples use one model: birds in the air, trees on the ground, and a coarse grid of regions over the same area.
The spaces share coordinates through #4114:
Give an agent as many locations as it needs. A location is a declared attribute; assigning to it joins the space:
Declare that two locations are the same place. One more line on
Birdgives it the ground cell below it. A follower has no state of its own, so it can't drift:A move is atomic: if a follower's cell is full or a point has no cell (for a grid that covers part of the air), it raises
CellFullExceptionorValueError, and nothing has moved when you handle it.Commits
Two commits; the grid commit that used to come first is now #4114.
mesa.experimental.locationswithCellLocationandContinuousLocation,follows=,exclude=on the continuous space queries, and renderers that look agents up through the space, so an agent draws whatever its locations are called.rt random 50 lt random 50 fd 1). Sheep eat the grass on their cell, and wolves eat a sheep on their cell, as NetLogo'sone-of sheep-here, replacing Mesa's cell-to-cell moves.The review iterations are squashed into these. The original commits are on
archive/locations-iterations, the fixes from the latest review round onarchive/locations-review-fixes, a final trim before it was folded in onarchive/locations-before-fold, and the birds and trees example this PR first had is onarchive/birds-and-trees.Design notes
share_location=couldn't express.propertyon the class and records itself in the class's_mesa_declared_locations.Agent.__init_subclass__collects those of the class and all its bases into_mesa_locations, so multiple inheritance and mixins work. Reads then run at property speed, andAgent.removetakes the agent out of every space through a duck-typed loop. Stable code imports nothing from experimental.CellAgentandContinuousSpaceAgentare untouched. Porting them onto locations is a possible follow-up, not a requirement.Decisions
These were open questions, resolved after the first round of feedback.
ContinuousLocationfinds its space by model attribute name. Binding a space per agent would also cover spaces kept in a list or dict, but there's no use case for that yet. Replacing a space while agents are in it isn't supported: placed agents stay in the old space while followers move into the new one. Detecting it would cost on every move or every model attribute write, so the docs say so instead.Point reads return a copy, nothing else. A view saves about 60 ns per read, but then
+=and item writes change the position before any check: a rejected move still moves the bird, and its ground cell drifts.ContinuousSpaceAgentis unchanged and still returns a view.Followers can't leave. To leave some birds out of a ground query, for example those flying high, filter where you query. They still count toward the cell's capacity.
Names stay:
CellLocation,ContinuousLocationandfollows.followsis one-directional on purpose: only the primary stores state, and it must be the most detailed location (decision 7). Followers can't be followed, so nothing cascades.linkwould suggest a symmetry that isn't there.Cell centers change directly, without a deprecation cycle, since 4.0 is in alpha. That change is now in Place grids in shared coordinates with cell_size and origin #4114.
An agent has at most one point in a continuous space, and one cell in a discrete space. Placing it in a space it's already in, through a second location, as a
ContinuousSpaceAgentor as aCellAgent, raisesValueErrorand changes nothing. Two cells in one grid would list the agent twice in a shared cell and take two capacity slots, and a rejected move could reorder that cell's occupants, which changes seeded choices. A follower in its primary's own space is aTypeErrorwhen the class is defined. Supporting more would mean spaces track memberships per (agent, location) pair, which changesexclude=,space.agents, drawing and removal. Allowing it later won't break anything; forbidding it after allowing it would.The primary is the most detailed location. A cell that follows a coarser cell could only reach the cells at the centers of the coarse cells, so its extra detail would never be used. That declaration raises
ValueErrorwhen the agent first gets a cell there.More generally, writing a follower raises, before anything changes, if the point the primary would store for the cell's center leads to another cell, for example two grids with the same cell size offset by half a cell, or a hex cell whose center a torus wraps elsewhere. A successful follower write keeps the cell you wrote.
Torus mismatches are checked, other mismatches aren't. In a bounded space, a mismatch already raises on the first move that needs a missing cell, and partial grids are legitimate. A torus mismatch wraps silently: a 40×40 torus grid of 2×2 cells under a 100×100 torus air space gives a bird at (90, 90) the cell at (11, 11). So a torus grid must have the same bounds as its primary's space, and a grid in a torus space must lie within it. Hex and Voronoi grids aren't checked, since they don't place cells by
cell_sizeandorigin, so a torusHexGridcan't follow.Supported pairs of spaces are listed. A follower's space and its primary's are checked once per agent, when the follower first gets a cell:
TypeError: node positions are only where the network is drawnUserWarning, then it works as beforeThe warning keeps custom spaces (and Mesa-Geo later) usable without a registry; a pair can be listed later without breaking anything.
follows=takes the location, not its name. Typos and a follower declared before its primary are aNameError, and the other declaration errors raiseTypeErrorwhen the class is defined, not on the first move. A primary on a base class isBase.name; a subclass that overrides the primary must declare the follower again.A mixin can no longer declare a follower of a location it doesn't define itself. Spaces stay names, since a space doesn't exist yet when the class is defined.
Breaking change
None here. The change to
Cell.positionof orthogonal grid cells is in #4114.Performance
Hot paths on Python 3.14, best of 15 runs:
CellAgent.cell)ContinuousSpaceAgent.position)+=a stepA followed write (position plus ground cell) costs 5.5 µs in the same cell and 6.0 µs into a new one, against 4.4 and 4.9 µs for doing the same by hand on a
ContinuousSpaceAgent(set the position,find_nearest_cell, move the cell). Most of the cost of a point read is the copy; see decision 2. The checks from review run once per agent, on its first placement, except the check that a cell belongs to its space, which is included above.Existing models don't use locations, apart from wolf–sheep. Wolf–sheep is a benchmark model, and it gets slower because the animals now move in a continuous space as well as on the grid: on the benchmark configurations, the small run goes from 0.07 to 0.17 s and the large one from 0.86 to 1.8 s (same seeds, alternating runs). With NetLogo's defaults (51×51, 100 sheep, 50 wolves, 500 steps, 10 seeds), both species survive in 10/10 runs before and after, with on average 207 → 173 sheep and 56 → 72 wolves.
Not in this PR
ContinuousSpaceAgent.position(it's a property, not a location; it needs porting first).sizeforHexGrid.SpaceRendererusesmodel.grid, thenmodel.space, so wolf–sheep draws its grid, with each animal on the cell below it.OrthogonalMooreGrid.covering(space, cell_size=...), to derive a grid's extent, origin and torus from a continuous space. Planned as a follow-up.CellLocation(Forest.ground). Both can be added later without breaking anything.Tests
tests/experimental/test_locations.pycovers joining, moving and leaving; several locations per agent, and at most one per space; bounds and torus; agents in several continuous spaces next toContinuousSpaceAgents;exclude=; removal; multiple inheritance, diamonds and mixins; pickling; and drawing.follows=, it covers writes in both directions, full cells, points without a cell, several followers, follower writes that can't lead back to their cell, each rule in the decisions above, and the declaration errors.The full suite passes locally (1,172 tests), apart from three tests that need
pytest-mock'smockerfixture, which isn't installed here. The Playwright browser tests weren't run.