Skip to content

Add frames and locations for spaces that share coordinates - #3939

Closed
EwoutH wants to merge 1 commit into
mesa:mainfrom
EwoutH:frames-locations
Closed

EwoutH wants to merge 1 commit into
mesa:mainfrom
EwoutH:frames-locations

Conversation

@EwoutH

@EwoutH EwoutH commented Oct 14, 2026

Copy link
Copy Markdown
Member

A first implementation of the frames and locations design from #2585 (proposal). This is a pathfinding PR: it is meant to test the design with working code and numbers, not to be merged as is.

What it does

A Frame is a coordinate system that one or more spaces index. An agent has at most one location per frame. A write through any member space is converted to frame coordinates and applied to the agent's other spaces in that frame once, or to none of them if one rejects it.

physical = Frame("physical", ndim=2)
air = ContinuousSpace([[0, 100], [0, 100]], random=rng, frame=physical)
ground = OrthogonalMooreGrid((50, 50), random=rng, frame=physical, cell_size=2.0)

class Bird(Agent):
    position = Location("physical")

air.add(bird, [10.0, 20.0])
ground.add(bird)                # occupies ground cell (5, 10) too
bird.position = [12.0, 21.0]    # air and ground both update
ground.move(bird, ground[0, 0]) # position becomes the cell center; air sees it
  • mesa.experimental.frames holds Frame and the Location descriptor.
  • Every space takes frame=. Without it, a space gets a frame of its own, and CellAgent.cell and ContinuousSpaceAgent.position keep their existing code path with one extra is not None check.
  • Discrete spaces get add, remove, move and cell_of. ContinuousSpace gets add and remove for agents that are not ContinuousSpaceAgents.
  • Orthogonal grids get cell_size and origin. The mapping is a scale and offset behind two private functions, so it can become an affine transform.
  • A write resolves the target in every member space first, then enters the new cells (rolling back if one is full), then commits. Writes within the same cell skip the membership update.
  • Existing agents can join a shared frame: ground.add(boid) for a ContinuousSpaceAgent, air.add(agent) for a CellAgent.

Benchmarks

Single-space performance was the gate. benchmarks/global_benchmark.py, main against this branch, two runs each in ABBA order on an idle laptop (Windows 11, Python 3.14), pooled and bootstrapped as in compare_timings.py:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small -3.8% [-5.6%, -2.0%] -0.1% [-0.7%, +0.4%]
BoltzmannWealth large -1.5% [-4.3%, +0.3%] -0.4% [-2.6%, +1.5%]
Schelling small -0.6% [-1.3%, +0.3%] +0.2% [-0.5%, +0.8%]
Schelling large +0.1% [-0.8%, +1.0%] -4.2% [-7.2%, -1.2%]
WolfSheep small -0.0% [-1.7%, +1.6%] -2.2% [-5.2%, +0.7%]
WolfSheep large -1.7% [-3.6%, -0.5%] -5.0% [-7.2%, -2.6%]
SugarscapeG1mt small +0.8% [-0.7%, +2.2%] +2.1% [+0.7%, +3.6%]
SugarscapeG1mt large +1.5% [-0.8%, +3.7%] -0.8% [-1.7%, +0.3%]
BoidFlockers small +3.8% [-1.0%, +8.1%] +0.5% [-0.4%, +1.3%]
BoidFlockers large +6.1% [-0.6%, +12.4%] +0.1% [-0.7%, +1.0%]
MultiLevelAllianceModel small +1.7% [-2.1%, +5.7%] -1.2% [-2.6%, -0.1%]
MultiLevelAllianceModel large -5.2% [-10.7%, +0.2%] -0.6% [-1.4%, +0.2%]

Positive is slower. By the script's own rule (an interval entirely beyond 3%), no configuration changed in init or run time.

For scale, two runs of main against each other differ by this much on the same machine:

Model Size Init time [95% CI] Run time [95% CI]
Schelling large +0.1% [-1.1%, +1.0%] -8.8% [-10.7%, -6.9%]
WolfSheep large -0.1% [-0.6%, +0.6%] -4.6% [-7.1%, -2.1%]
BoltzmannWealth large -1.9% [-7.0%, +1.0%] -3.9% [-6.6%, -1.4%]
MultiLevelAllianceModel large -15.7% [-20.7%, -10.2%] -0.9% [-2.0%, +0.5%]

So the run-time differences above (-5.0% to +2.1%) are inside what this machine produces with no code change. The grid models are neither faster nor slower in any way I can resolve here; CI's benchmark run is the better instrument.

Hot paths, best of 25 repeats, alternating main and branch:

Operation main branch
agent.cell = cell 0.79 µs 0.80 µs
agent.cell 61 ns 61 ns
boid.position 190 ns 190 ns
boid.position = p 4.35 µs 4.34 µs
relative move (+= on main, = position + step on branch) 4.81 µs 5.08 µs
OrthogonalMooreGrid((40, 40)) 10.7 ms 10.8 ms
OrthogonalMooreGrid((3, 3)) 60 µs 65 µs
ContinuousSpace(...) 8.0 µs 9.9 µs

The one measurable cost on a hot path is the relative move: with a read-only position it allocates a new array, about 0.3 µs or 5% of that one statement. It does not show up in the Boids model. Constructing a space costs 2 to 5 µs more, for the frame.

A write that fans out over two spaces costs about the same as doing the same thing by hand:

Write µs
boid.position = p, continuous space only 4.5
boid.position = p, also in a grid, same cell 7.5
boid.position = p, also in a grid, new cell 8.5
By hand today: set position, find_nearest_cell, set cell 8.1
agent.cell = cell, grid only 0.8
agent.cell = cell, also in a continuous space 3.3

Where this differs from the proposal

  • Location("physical") takes a name. A frame holds its spaces, so it is a per-model object created in Model.__init__, while Location is declared on the class. A module-level Frame shared by a class would leak spaces across model instances and replications. The name is resolved when the agent joins a space; no model.frames registry is needed. Location(frame) also works and uses the frame's name.
  • Positions are read-only views. A writable view lets agent.position += v change the array before anything is validated, so the old value is gone when a move is rejected, and agent.position[0] = x skips the other spaces entirely. That cannot be combined with atomic writes. The cost is writing agent.position = agent.position + v; see the benchmark above.
  • Cell centers land directly, without a deprecation. The invariant needs them: a corner sits on a cell boundary, and with cell_size=1/3 the round trip find_nearest_cell(cell.position) lands in the neighbouring cell.
  • space.cell_of(agent) is the general way to ask for a cell. agent.cell stays, but it refers to one space.

What turned out awkward

  1. agent.cell does not generalize. An agent in a ground grid and a district grid has two cells in one frame. agent.cell now mirrors one "home" space, and assigning a cell of another space raises. Cell has no reference to its space, so finding the owner of a cell means asking each space in the frame.
  2. Torus and extent belong to the frame, not the space. They have to match across member spaces, so they are now taken from the first space that joins and validated for the rest. Declaring them on Frame would be cleaner.
  3. Spaces disagree on what "inside" means. ContinuousSpace.in_bounds includes the upper bound, grids are half-open, hex and Voronoi grids accept any point. A point exactly on the upper edge is valid in the continuous space and rejected by a grid of the same size.
  4. A grid that covers part of a frame traps its agents. A point outside it resolves to no cell, so the write fails. "A location in zero cells" is not expressible yet; it is the same gap as multi-cell membership.
  5. Networks make point writes fail for the whole frame. Per decision 8, a point write raises while the agent is in a Network. An agent in a network and a continuous space can therefore only move by node.
  6. A ContinuousSpaceAgent has no "not placed yet" state. Its row is uninitialized memory until the first assignment, so ground.add(boid) before that derives a cell from garbage.
  7. ContinuousSpace.agent_positions is still a writable array. Vectorized updates bypass the other spaces.
  8. Two pickling bugs surfaced and are fixed here because the new code depends on them: unpickling a Grid gave every cell its own class (property layers only worked on the first cell), and unpickling a ContinuousSpace detached agent_positions from its backing array.
  9. Visualization draws orthogonal grids in cell coordinates. With centers as positions, I pointed it at cell.coordinate so output is unchanged. Drawing a continuous space over a grid needs it to draw in frame coordinates.

Open questions

  • Should Frame own torus and the extent, with spaces inheriting them?
  • Outside a partial grid: fail the write (now), or drop the agent's membership of that grid?
  • Should a point write snap to the nearest node in a Network on request, instead of always raising?
  • Is the home-space rule for agent.cell acceptable, or should agent.cell be single-space only?
  • Is mesa.experimental.frames the right place, given that the stable mesa.discrete_space now imports it?
  • Names: add / remove / move / cell_of, Frame.location_of, Frame.move.
  • Axis convention (position = (x, y) against row-first movement in Grid2DMovingAgent) is untouched.

Not in this PR: multi-cell membership and geometry, cell_size for hex grids, FixedAgent in shared frames (raises TypeError), change notification through mesa_signals, multi-space visualization, and example models.

Breaking changes

Both are in docs/migration_guide.md:

  • Cell.position of an orthogonal grid cell is the cell center: (5, 5) reports [5.5, 5.5].
  • ContinuousSpaceAgent.position is read-only; += raises.

Tests

tests/experimental/test_frames.py checks the core invariant on random sequences of point writes, cell moves, joins, leaves and removals, across four space combinations (torus continuous + two grids; bounded continuous + grid + Voronoi + partial grid; discrete only; hex torus + continuous) and three agent kinds. After every operation each member space must agree with the agent's location, and a rejected operation must leave a full snapshot unchanged. Six deliberately injected bugs (no rollback, no torus wrap, old cell not left, and so on) are all caught by it.

Not run locally: the Playwright browser tests in tests/examples/test_examples_viz.py (no Chromium on my machine). CI will show them.

🤖 Generated with Claude Code

A Frame is a coordinate system that one or more spaces index. An agent
has at most one location per frame, and a write through any member
space updates the agent's other spaces in that frame once, or none of
them if one rejects the move. This is a first implementation of the
design in discussion mesa#2585.

- Add mesa.experimental.frames with Frame and the Location descriptor.
- Every space takes frame=; without it a space gets a frame of its own
  and single-space agents keep their existing code path.
- Discrete spaces get add, remove, move and cell_of; ContinuousSpace
  gets add and remove for agents that are not ContinuousSpaceAgents.
- Orthogonal grids get cell_size and origin to place them in a frame.

Breaking changes, documented in the migration guide:

- Cell.position of an orthogonal grid cell is the cell center.
- ContinuousSpaceAgent.position is a read-only view.

Also restore shared state after unpickling: grid cells get one cell
class again, and ContinuousSpace retakes its array views.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
@github-actions github-actions Bot added docs Release notes label example Changes the examples or adds to them. 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
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.4% [-1.0%, +0.3%] 🔵 -0.6% [-0.9%, -0.3%]
BoltzmannWealth large 🔵 +3.8% [+2.5%, +5.0%] 🔵 +5.6% [+2.4%, +8.7%]
Schelling small 🔵 +1.0% [+0.3%, +1.7%] 🔵 +1.1% [+0.2%, +2.1%]
Schelling large 🔵 +1.1% [+0.5%, +1.7%] 🔴 +7.0% [+3.8%, +10.8%]
WolfSheep small 🔵 -1.0% [-1.4%, -0.5%] 🔵 +1.1% [-3.3%, +5.5%]
WolfSheep large 🔵 +0.2% [-0.9%, +1.3%] 🔵 -0.7% [-3.4%, +1.9%]
SugarscapeG1mt small 🔵 -0.1% [-0.5%, +0.3%] 🔵 +2.2% [+0.8%, +3.7%]
SugarscapeG1mt large 🔵 +3.0% [+2.0%, +4.1%] 🔵 +0.8% [-0.8%, +2.6%]
BoidFlockers small 🔵 +0.0% [-0.4%, +0.5%] 🔵 +1.5% [+0.9%, +2.2%]
BoidFlockers large 🔵 +1.4% [+0.8%, +1.9%] 🔵 +1.1% [+0.8%, +1.5%]
MultiLevelAllianceModel small 🔵 -4.3% [-6.0%, -2.4%] 🟢 -3.6% [-3.9%, -3.2%]
MultiLevelAllianceModel large 🔵 -2.2% [-4.6%, +0.2%] 🔵 -0.3% [-1.7%, +1.3%]

@EwoutH

EwoutH commented Oct 14, 2026

Copy link
Copy Markdown
Member Author

Overcomplicated, not the direction I want to go. See #2585 (comment).

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant