Skip to content

Add locations: composable agent locations in shared coordinates - #3940

Merged
EwoutH merged 2 commits into
mesa:mainfrom
EwoutH:locations
Nov 16, 2026
Merged

EwoutH merged 2 commits into
mesa:mainfrom
EwoutH:locations

Conversation

@EwoutH

@EwoutH EwoutH commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

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_size and origin; 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:

model.air = ContinuousSpace([[0, 100], [0, 100]], random=model.random)
model.ground = OrthogonalMooreGrid((50, 50), cell_size=2.0, random=model.random)   # same area, 2 by 2 cells
model.regions = OrthogonalMooreGrid((5, 5), cell_size=20.0, random=model.random)   # same area, coarse

Give an agent as many locations as it needs. A location is a declared attribute; assigning to it joins the space:

class Tree(Agent):
    cell = CellLocation("ground")          # a cell of model.ground

class Bird(Agent):
    position = ContinuousLocation("air")   # a point in model.air
    territory = CellLocation("regions")    # a second, independent location

tree.cell = model.ground[10, 20]           # joins model.ground
bird.position = [21.3, 40.2]               # joins model.air
bird.territory = model.regions[1, 2]       # joins model.regions; stays there wherever the bird flies
bird.position += [2.0, 0.0]                # moves; bounds and torus are checked
nearby, _ = model.air.get_agents_in_radius(bird.position, 5, exclude=bird)
bird.remove()                              # leaves model.air and model.regions

Declare that two locations are the same place. One more line on Bird gives it the ground cell below it. A follower has no state of its own, so it can't drift:

class Bird(Agent):
    position = ContinuousLocation("air")
    cell = CellLocation("ground", follows=position)     # the ground cell below
    territory = CellLocation("regions")

bird.position = [21.3, 40.2]                             # bird.cell is model.ground[10, 20]
bird.position += [2.0, 0.0]                              # bird.cell is now model.ground[11, 20]
bird.cell = bird.cell.neighborhood.select_random_cell()  # position moves to that cell's center

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 CellFullException or ValueError, and nothing has moved when you handle it.

Commits

Two commits; the grid commit that used to come first is now #4114.

  1. Locations. mesa.experimental.locations with CellLocation and ContinuousLocation, 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.
  2. Wolf–sheep shows locations. The animals walk as in NetLogo (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's one-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 on archive/locations-review-fixes, a final trim before it was folded in on archive/locations-before-fold, and the birds and trees example this PR first had is on archive/birds-and-trees.

Design notes

  • Declared per agent class, not per space. Birds follow the air into the ground grid while trees on that grid don't, which a space-level share_location= couldn't express.
  • Each location installs a plain property on 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, and Agent.remove takes the agent out of every space through a duck-typed loop. Stable code imports nothing from experimental.
  • CellAgent and ContinuousSpaceAgent are 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.

  1. ContinuousLocation finds 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.

  2. 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. ContinuousSpaceAgent is unchanged and still returns a view.

    before = bird.position
    bird.position += [2.0, 0.0]   # goes through the setter: bounds, torus, the ground cell
    before                        # still the old position
    bird.position[0] = 50.0       # changes a copy; the bird doesn't move
    model.air.agent_positions     # all positions at once, for vectorized reads
  3. 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.

    bird.cell = None   # ValueError: set position to None to leave both
    low = [a for a in bird.cell.agents if isinstance(a, Bird) and a.altitude < 10]
  4. Names stay: CellLocation, ContinuousLocation and follows. follows is 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. link would suggest a symmetry that isn't there.

  5. 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.

  6. 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 ContinuousSpaceAgent or as a CellAgent, raises ValueError and 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 a TypeError when the class is defined. Supporting more would mean spaces track memberships per (agent, location) pair, which changes exclude=, space.agents, drawing and removal. Allowing it later won't break anything; forbidding it after allowing it would.

    class Voter(Agent):
        view = ContinuousLocation("opinion")
        ideal = ContinuousLocation("opinion")
    
    voter.view = [0.2, -0.4]
    voter.ideal = [0.5, 0.1]   # ValueError: already in model.opinion
  7. 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 ValueError when the agent first gets a cell there.

    class Walker(Agent):
        coarse = CellLocation("coarse_grid")
        fine = CellLocation("fine_grid", follows=coarse)
    
    walker.coarse = model.coarse_grid[1, 1]   # ValueError: model.coarse_grid has larger cells than model.fine_grid

    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.

  8. 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_size and origin, so a torus HexGrid can't follow.

  9. 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:

    Primary Follower
    point orthogonal grid, hex grid (not a torus), Voronoi grid supported
    orthogonal grid orthogonal grid with equal or larger cells supported
    anything Network, or a Network primary TypeError: node positions are only where the network is drawn
    any other pair UserWarning, then it works as before

    The warning keeps custom spaces (and Mesa-Geo later) usable without a registry; a pair can be listed later without breaking anything.

  10. follows= takes the location, not its name. Typos and a follower declared before its primary are a NameError, and the other declaration errors raise TypeError when the class is defined, not on the first move. A primary on a base class is Base.name; a subclass that overrides the primary must declare the follower again.

class Bird(Agent):
    position = ContinuousLocation("air")
    cell = CellLocation("ground", follows=position)

class Lander(Flyer):
    cell = CellLocation("ground", follows=Flyer.position)

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.position of orthogonal grid cells is in #4114.

Performance

Hot paths on Python 3.14, best of 15 runs:

Operation Existing class Location
Read a cell 26 ns (CellAgent.cell) 38 ns
Move to another cell 0.51 µs 0.73 µs
Read a point 0.11 µs (ContinuousSpaceAgent.position) 0.37 µs
Write a point 2.8 µs 3.4 µs
+= a step 3.2 µs 4.2 µs

A 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

  • Following a ContinuousSpaceAgent.position (it's a property, not a location; it needs porting first).
  • size for HexGrid.
  • Drawing a continuous space and a grid in one plot: SpaceRenderer uses model.grid, then model.space, so wolf–sheep draws its grid, with each animal on the cell below it.
  • A second example (the election model).
  • OrthogonalMooreGrid.covering(space, cell_size=...), to derive a grid's extent, origin and torus from a continuous space. Planned as a follow-up.
  • Where examples on experimental APIs should live; discussed in Add examples/experimental group and move alliance_formation into it #3785.
  • A "did you mean" hint for a misspelled space name, and typed space references such as CellLocation(Forest.ground). Both can be added later without breaking anything.

Tests

  • tests/experimental/test_locations.py covers joining, moving and leaving; several locations per agent, and at most one per space; bounds and torus; agents in several continuous spaces next to ContinuousSpaceAgents; exclude=; removal; multiple inheritance, diamonds and mixins; pickling; and drawing.
  • For 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.
  • A randomized test runs 2,000 moves (some rejected) on agents with two followers. After each move it checks that every follower is the cell at its primary, that rejected moves change nothing, including the order of every cell's occupants, and that every agent occupies its cells exactly once. It catches a removed rollback and a removed old-cell cleanup.

The full suite passes locally (1,172 tests), apart from three tests that need pytest-mock's mocker fixture, which isn't installed here. The Playwright browser tests weren't run.

@github-actions github-actions Bot added docs Release notes label experimental Release notes label testing Release notes label visualization labels Oct 14, 2026
@EwoutH EwoutH added the feature Release notes label label Oct 14, 2026
@EwoutH

EwoutH commented Oct 14, 2026

Copy link
Copy Markdown
Member Author

Especially curious what you think of the "follower" concept (maybe we should call it link since it works in both directions?)

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔴 +10.5% [+8.8%, +12.5%] 🔵 +1.5% [-0.3%, +3.2%]
BoltzmannWealth large 🔴 +8.4% [+6.5%, +10.4%] 🔴 +10.8% [+9.6%, +11.9%]
Schelling small 🔴 +4.8% [+3.3%, +6.4%] 🔵 +4.3% [+2.6%, +6.1%]
Schelling large 🔵 +2.5% [+0.5%, +5.3%] 🔵 +1.1% [-0.7%, +2.4%]
WolfSheep small 🔵 -1.3% [-2.2%, -0.4%] 🔵 +2.2% [-2.1%, +6.5%]
WolfSheep large 🔵 +2.9% [+0.1%, +5.8%] 🔴 +9.9% [+7.3%, +13.0%]
SugarscapeG1mt small 🔵 +1.1% [-0.1%, +2.2%] 🔵 +1.5% [-0.5%, +3.5%]
SugarscapeG1mt large 🔵 -3.8% [-7.4%, -0.2%] 🔵 -7.2% [-14.0%, -0.6%]
BoidFlockers small 🔵 -0.3% [-1.7%, +0.9%] 🔵 -0.5% [-1.5%, +0.7%]
BoidFlockers large 🔵 +1.0% [-2.5%, +3.4%] 🔵 +0.1% [-1.7%, +1.9%]
MultiLevelAllianceModel small 🔵 +4.3% [+0.8%, +7.9%] 🔵 +0.2% [-1.2%, +1.6%]
MultiLevelAllianceModel large 🔵 -2.6% [-6.0%, +0.5%] 🟢 -9.7% [-13.7%, -5.2%]

@codebreaker32

Copy link
Copy Markdown
Collaborator

Great to see this moving again! I'll take a look at this along with #2585 and #3939 by tomorrow evening. Please point me to any other context I should check out.

@codebreaker32

Copy link
Copy Markdown
Collaborator

I like where this landed. It answers most of what came up on my RFC in March: cell_size/origin is what shared_dims should have been (explicit instead of auto-fit, which @wang-boyu rightly warned about).

I would argue to keep follows. It's one-directional on purpose (a follower can't leave alone, can't be followed), and link would promise a symmetry that isn't there.

Per-class declaration instead of per-space is the real change. SpatialAgent in #3678 ended up carrying its own space set for exactly the birds-vs-trees reason, and I never hit a case that needed membership declared at the space level.

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 shared_dims. Right now a torus mismatch between a grid and the air space is never caught, and a grid that only covers part of the air only shows up when a follower move fails at runtime. Something like OrthogonalMooreGrid((50, 50), shared_coordinates=model.air) would derive the scale, validate torus and extent, and give follows= a space to check against. I don't think this conflicts with per-agent follows; the space declares the coordinate relation, the agent declares membership. Birds and trees still work.

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 follows is enough.

@AshNicolus

Copy link
Copy Markdown
Contributor

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):

point reads return read p += step out-of-bounds += saved value kept
copy (current) 149 ns works rejected, position unchanged yes
writable view 91 ns works rejected, but position already changed no
read-only view 225 ns raises n/a no

So a read-only view is slower than the copy and breaks += completely. The writable view saves about 60 ns, but the in-place add lands before the setter's bounds check, so a rejected move still corrupts the position. I'd keep the copy.

HexGrid drawing. Orthogonal grids now draw from cell.coordinate, but HexGrid still goes through cell.position and then gets the hex spacing applied a second time, so hex agents land off their hexagon (#3949). #3952 fixes that. I checked it applies cleanly on top of this branch and the viz, locations and discrete_space tests pass together.

Pickling commit. The Grid unpickling fix looks like the same bug as #3914 by @amanbn8, in case you want to land one of them.

@EwoutH

EwoutH commented Oct 19, 2026

Copy link
Copy Markdown
Member Author

Cool, thanks for both your feedback. Appreciated.

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.

I’m willing to build (some of) this back in. I think the balance is here to find a low-overhead, simple implementation.

the birds-and-trees and election models are listed as not in this PR.

I will include (one of) them.

I'd keep the copy.

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.

@AshNicolus

Copy link
Copy Markdown
Contributor

Copy as the default with an opt-in view sounds good. One caveat for the opt-in: with a writable view, p += step changes the stored array before the setter runs, so a move the setter rejects (I checked this with an out-of-bounds step) still leaves the position changed. That's fine for people who know they're doing it, but it's worth either disallowing the view on locations that have followers, or saying in the docs that atomic moves only hold with the copy.

@EwoutH

EwoutH commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

Thanks both, this was useful. Short version: I'll keep follows, keep the copy as the default for point reads, and update/add an example.

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 covering constructor

model.air = ContinuousSpace([[-50, 50], [0, 100]], torus=True, random=rng)
model.ground = OrthogonalMooreGrid.covering(model.air, cell_size=2.0, random=rng)
# same as: OrthogonalMooreGrid((50, 50), cell_size=2.0, origin=(-50, 0), torus=True, random=rng)

The grid takes its extent and torus setting from the space; you choose only the resolution. Some API questions:

  • Resolution or shape? cell_size= (pick the resolution, the grid size follows) or shape=(50, 50) (pick the grid size, the resolution follows). cell_size seems more natural, and it can be a sequence for cells with different sizes per axis.
  • Torus: copied from the space by default. Overriding it is possible, but I'm not sure it should be, since a mismatch is almost always a bug.
  • Divisibility: raise if the extent isn't a whole number of cells, with a tolerance for floats like 100 / 3.
  • Scope: orthogonal grids only for now. HexGrid has no cell_size yet.

Benefits:

  • Alignment is correct by construction: no forgotten origin or torus, and no silent int(width / resolution) truncation when the world size is a model parameter.
  • The continuous space is the only place the world's size is defined, so changing it updates every grid.
  • No runtime cost, and no reference between the spaces, so pickling and garbage collection stay simple.
  • Purely additive: the plain constructor stays as it is.

Downsides:

  • It only covers the whole space. A grid covering part of the space still uses the plain constructor, unless we add something like region= later.
  • The continuous space has to exist first, and it works in one direction only (grid onto continuous space).
  • It aligns spaces at construction but checks nothing afterwards. If someone builds a mismatched grid by hand, nothing catches it.
  • It's another constructor to document, and it needs an extent property on grids (which plotting a grid and a continuous space together needs anyway).

@codebreaker32, does this cover what you had in mind with shared_coordinates=? Do you think it's worth the additional API surface?

What I'd leave out for now

  • An argument on the grid, shared_coordinates=model.air. It does what covering does, but in __init__, where it's unclear how it combines with explicit cell_size/origin for a grid covering part of the space. If the grid keeps the reference, spaces become linked, and pickling and garbage collection have to deal with that.
  • A check in follows= on the first move between two spaces. I prototyped it. It works, but it costs about 0.5 µs on every followed move to re-check a setup fixed at construction. The rule is also subtler than it looks: a bounded island on a torus world is fine, while a torus grid on bounded air is not. Where such a check belongs depends on open question 1. If locations bind their space when an agent joins, it fits there at no cost per move; if they keep looking spaces up by name, it fits on the space side. I'd rather settle that first.
  • A shared frame object. Same reasoning as Add frames and locations for spaces that share coordinates #3939: it costs more than it gives today. It could come back as a value object if Mesa-Geo needs a CRS.

All three are purely additive, so none of them is blocked by leaving them out now.

Other notes

@quaquel still would love your review.

@EwoutH

EwoutH commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

Updated the PR body: the open questions are now decisions. In short:

  1. Spaces by model attribute name. I don't see a use case yet for spaces kept in lists or dicts, so I'm leaving per-agent binding out for now.
  2. Point reads return a copy, and that's it. No opt-in view: keep it simple. space.agent_positions is already there when you need speed.
  3. Followers can't leave. Filtering agents where you query them covers the cases I can think of (birds flying high, for example).
  4. Names stay: CellLocation, ContinuousLocation, follows.
  5. Cell centers change directly. We're in alpha, so no deprecation cycle.

Feedback on any of these is welcome, of course.

@EwoutH

EwoutH commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

@mesa/maintainers ready for review! Would love everybody's thoughts.

@KaguraTart

Copy link
Copy Markdown
Contributor

On the proposed covering constructor, I'd start with cell_size= for orthogonal grids, inherit the lower bounds and torus setting without overrides, and reject non-integral cell counts with a documented floating-point tolerance. It should be a construction-time snapshot: changing or replacing the source space later would not update an existing grid. This seems small enough to keep as an additive follow-up.

There is a separate follows contract worth settling even when the grids have exactly matching extents and origins. I reproduced the following on the current head, 82d538e87378f2e812cea5fda2f012e0448935f5: assigning a follower of a cell-based primary can succeed but leave the agent in a different cell from the one assigned.

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:

requested: (2, 2)
actual: (5, 5)
retained: False

Both grids cover [0, 40] × [0, 40], with the same origin and torus setting. The target's center is (5, 5). _set_follower() sends that point through the primary, which resolves it to coarse cell (0, 0). That cell's center is (10, 10), so recomputing the follower selects fine cell (5, 5). Repeating the assignment then silently leaves it there.

The locations remain synchronized; the question is what a successful follower assignment promises. Matching extents through covering(...) would not make this conversion invertible.

Would it make sense to require that a successful agent.fine = target preserves agent.fine is target, and otherwise raise ValueError before changing any location or membership? I would favor that over silently projecting to another cell.

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.

@KaguraTart

Copy link
Copy Markdown
Contributor

Multiple inheritance: a location from the second base is missed by Agent.remove()

I reproduced an independent registration/cleanup issue on 82d538e87378f2e812cea5fda2f012e0448935f5. Both inherited location properties work, but the combined class only sees the first base's _mesa_locations, so removing the agent leaves it in the other space.

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:

registered: ['left']
before remove: 1 1
in model: False
after remove: 0 1
left: None
right: [8. 8.]

I would expect both spaces to be empty and both locations to read None after removal. Reversing the base-class order leaves the agent in the other space; the single-inheritance control cleans up correctly.

The cause appears to be the registration code: getattr(owner, "_mesa_locations", ()) reads one inherited registry. In this example, CombinedAgent introduces no new location, so __set_name__ does not run for it and its registry is simply inherited from LeftAgent. Agent.remove() iterates that incomplete registry. _declarations() reads the same registry for resolving follows, so fixing only the removal loop would leave the underlying inconsistency.

A minimal fix could keep the public API unchanged:

  • Build and cache the effective location registry for each concrete subclass, including subclasses that declare no new locations.
  • Resolve names according to Python's MRO, deduplicate diamond inheritance, and respect overrides or shadowing by non-location attributes; simply concatenating inherited registries would not cover those cases.
  • Have cleanup and follows resolution use that same effective registry, with declaration/follower caches kept per concrete class. Preserve the current separation between stable Agent code and the experimental location implementation.

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 CellLocation/ContinuousLocation bases.

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.

@codebreaker32

codebreaker32 commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks, agree on follows and the example

covering covers two of the three things I was after: deriving the grid from the space, and inheriting torus/extent. I'd add it. It doesn't help a grid built by hand or one covering part of the space, though. Would a check in follows that runs once per pair of spaces (and is cached after that) address the cost concern, or does it run into the same pickling issues as linking the spaces?

I'd try to review it in bit depth soon. Also, Should an agent be able to have more than one ContinuousLocations in the same space? (@quaquel's sketch in #2585 had position_a/position_b in one space)

@EwoutH EwoutH added trigger-benchmarks Special label that triggers the benchmarking CI and removed trigger-benchmarks Special label that triggers the benchmarking CI labels Nov 15, 2026
@github-actions github-actions Bot added docs Release notes label testing Release notes label visualization labels Nov 15, 2026

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving for the locations part. I haven't reviewed #4114 yet, so this doesn't cover the grid changes it builds on.

@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
@EwoutH
EwoutH changed the base branch from grid-coordinates to main November 15, 2026 20:40
@EwoutH

EwoutH commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

I would like to move forward with this PR. If you have any open points, please let me know, and otherwise, an approval would be greatly appreciated.

@mesa/maintainers I would love some reviews and/or checkmarks!

@quaquel

quaquel commented Nov 16, 2026

Copy link
Copy Markdown
Member

I realize that wolf-sheep is different now, but would love to see some analysis of what explains the massive increase in run time.

@EwoutH

EwoutH commented Nov 16, 2026 •

Copy link
Copy Markdown
Member Author

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 cell.agents == [bird, bird], including through differently named model attributes pointing to the same grid.

@EwoutH EwoutH added trigger-benchmarks Special label that triggers the benchmarking CI and removed trigger-benchmarks Special label that triggers the benchmarking CI labels Nov 16, 2026
@EwoutH

EwoutH commented Nov 16, 2026 •

Copy link
Copy Markdown
Member Author

@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:

Version Runtime
Original grid model 0.78 s
Original model with locations library added 0.78 s
Continuous model, synchronized manually 1.29 s
Current locations version 1.80 s
Historical radius-search version 6.25 s

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.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -2.6% [-3.3%, -1.9%] 🔵 -0.1% [-0.3%, +0.1%]
BoltzmannWealth large 🔵 -1.9% [-3.0%, -0.8%] 🔵 -0.2% [-4.4%, +4.0%]
Schelling small 🔵 +0.3% [-0.1%, +0.8%] 🔵 -1.2% [-2.1%, -0.4%]
Schelling large 🔵 +0.2% [-0.5%, +0.9%] 🔵 +4.4% [+0.7%, +8.3%]
WolfSheep small 🔴 +34.2% [+33.7%, +34.6%] 🔴 +223.7% [+213.8%, +233.3%]
WolfSheep large 🔴 +28.6% [+27.8%, +29.5%] 🔴 +162.1% [+156.3%, +167.9%]
SugarscapeG1mt small 🔵 -2.5% [-2.8%, -2.2%] 🔵 -2.4% [-4.0%, -0.8%]
SugarscapeG1mt large 🔵 -1.8% [-2.6%, -0.9%] 🟢 -4.9% [-6.4%, -3.3%]
BoidFlockers small 🔵 -0.1% [-0.7%, +0.4%] 🔵 -0.5% [-1.1%, -0.1%]
BoidFlockers large 🔵 -1.1% [-1.7%, -0.4%] 🔵 +0.2% [+0.1%, +0.4%]
MultiLevelAllianceModel small 🟢 -5.2% [-6.3%, -4.1%] 🔵 -0.5% [-1.0%, +0.1%]
MultiLevelAllianceModel large 🔵 -2.9% [-3.9%, -1.9%] 🟢 -5.8% [-6.7%, -4.9%]

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
@EwoutH
EwoutH merged commit 5118d89 into mesa:main Nov 16, 2026
@EwoutH

EwoutH commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Merged, thanks everyone!

Potential follow-ups:

  • Wolf–sheep performance: the model got slower now that animals move through a continuous space (small run 0.07 → 0.17 s, large run 0.86 → 1.8 s). Reusing successful torus-bounds checks across agents takes about 5% off that; it will come as a separate PR.
  • OrthogonalMooreGrid.covering(space, cell_size=...): derive a grid's extent, origin and torus from a continuous space.
  • Port CellAgent and ContinuousSpaceAgent onto locations, so that ContinuousSpaceAgent.position can be followed.
  • size for HexGrid.
  • Draw a continuous space and a grid in one plot (SpaceRenderer now picks only one of them).
  • A second example using locations (the election model). Where examples on experimental APIs should live is being discussed in Add examples/experimental group and move alliance_formation into it #3785.
  • Small extras: a "did you mean" hint for misspelled space names, and typed space references like CellLocation(Forest.ground).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Release notes label example Changes the examples or adds to them. experimental Release notes label feature Release notes label testing Release notes label visualization

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants