Stacked Spaces Registration API Design
Background
With the ongoing spatial overhaul in Mesa 4, we are moving towards "Stacked Spaces" (#2585, #3132). We've separated physical coordinates (Cell.position) from logical indices (Cell.coordinate) (#3268) and are introducing the Locatable protocol for agents (#3287).
The goal of Stacked Spaces is to allow multiple spaces (e.g., an OrthogonalGrid, a Network, and a PropertyLayer) to share the same physical domain. An agent's position would then dictate its presence across all these stacked spaces simultaneously.
Problem Statement
Currently, there is no established API for declaring stacked spaces, linking their physical domains, or registering them with the Model. Before we implement the underlying synchronization logic (e.g., emitting signals when an agent's position changes to update all spaces), we need to decide on the user-facing API.
Current Codebase State
How position works today across space types
There are three completely different position implementations in the codebase:
| Space Type | Who owns position? |
How it works |
|---|---|---|
Discrete (CellAgent) |
The Cell owns it. CellAgent has no position property; it accesses it via agent.cell.position. |
Cell.position returns np.ndarray (falls back to np.asarray(self.coordinate)) |
Continuous (ContinuousSpaceAgent) |
The Space owns position data in a shared numpy array. Agent reads/writes into space.agent_positions[index]. |
Tightly coupled to one ContinuousSpace instance |
Locatable PoC (HasPosition, PR #3287) |
The Agent owns _position directly as a simple stored attribute. |
No space awareness; purely a data holder |
Key architectural observations
-
DiscreteSpacehas no concept of physical bounds. It stores_cellskeyed bycoordinate(logical index). OnlyGridsubclasses know their physical size viaself.dimensions.NetworkandVoronoiGridderive their extent from node positions, not from any declared bounds. -
find_nearest_cell(position)already exists on every space type.Grid,Network,HexGrid, andVoronoiGridall implement this method. This is the natural bridge from a physical position to a logical cell and is exactly what stacked spaces would use to map an agent's position into each sub-space. -
Modelhas zero knowledge of spaces. There is noself.spaces, noregister_space(), nothing. Spaces are just arbitrary attributes users assign to the model instance. Any stacking mechanism must either (a) be built into the spaces themselves, or (b) add new infrastructure toModel. -
ContinuousSpaceAgentis tightly coupled to its space. It takesspacein__init__()and stores position data inside the space's numpy array. This storage pattern is fundamentally different from discrete spaces.
Dependency on Locatable protocol (#3287)
While the Stacked Spaces API can be designed independently of Locatable, implementation requires a unified agent.position so that a stacked space can read an agent's position and map it into each sub-space via find_nearest_cell(). Today:
CellAgenthas no.position(only.cell)ContinuousSpaceAgenthas.positionbut it reads from a space-owned arrayHasPosition(Locatable PoC) provides.positionas a simple stored attribute
The Locatable protocol is therefore a prerequisite for the synchronization layer, though not for the registration/declaration API discussed here.
Proposed API Options for Discussion
Option 1: share_dims Initialization Argument
Add a share_dims (or linked_to) argument to the initialization of standard Spaces.
class MyModel(Model):
def __init__(self):
super().__init__()
self.grid = OrthogonalGrid(width=10, height=10, torus=False)
self.network = Network(share_dims=self.grid)
self.heat_layer = PropertyLayer("heat", share_dims=self.grid)
Pros: Explicit on a per-space level. No new wrapper classes needed.
Cons: DiscreteSpace has no physical bounds concept, only Grid does. Which space is the "parent"? Chaining (B shares with A, C shares with B) creates ambiguity. Network and VoronoiGrid don't have intrinsic bounds, making share_dims semantically unclear for them.
Option 2: Dedicated StackedSpace Wrapper
Introduce a new class that groups spaces and enforces the shared physical domain.
class MyModel(Model):
def __init__(self):
super().__init__()
self.env = StackedSpace(
dimensions=(10, 10),
spaces={
"grid": OrthogonalGrid(),
"network": Network(),
"heat": PropertyLayer("heat"),
}
)
# Access: self.env["grid"], self.env["network"]
# Agent position update routed through self.env -> find_nearest_cell() on each child
Pros: Most viable given the code. Cleanly owns the shared physical extent and can route find_nearest_cell() calls across all child spaces. Natural place to hold the observable position sync logic.
Cons: Changes how users interact with spaces (self.env["grid"] vs self.grid). Adds a new abstraction layer.
Option 3: Model-Level Space Registration
Similar to model.register_agent(), introduce a space registration phase on Model.
class MyModel(Model):
def __init__(self):
super().__init__()
self.grid = OrthogonalGrid(width=10, height=10)
self.network = Network()
self.register_spaces(
shared_dims=(10, 10),
spaces=[self.grid, self.network]
)
Pros: Fits the existing model lifecycle pattern (register_agent / deregister_agent). Users keep direct space references (self.grid). Model becomes the single source of truth.
Cons: Adds more responsibility to Model (already 475 lines). Needs new internal data structures (_spaces, _stacked_groups, etc.).
Open Questions
- Should the physical domain (bounds) be declared explicitly, or inferred from the first space? Grids know their dimensions; Networks and VoronoiGrids do not.
PropertyLayeris being removed as a class (PR #3340 ). It is being replaced with raw NumPy arrays stored directly onGridas_property_layers: dict[str, np.ndarray]. This means property data will be grid-specific and should not be treated as a stackable space. Our API should focus on stackingDiscreteSpacesubclasses (Grid,Network,VoronoiGrid) andContinuousSpace.- What is the synchronization trigger? When an agent moves (
agent.position = new_pos), how does the stacked space get notified? Viamesa_signals/HasEmitters? Via an explicitagent.move_to(pos)call on the stacked space? - Can spaces belong to multiple stacks? Or is it strictly one stack per space?
Notes
- Land the
Locatableprotocol (#3287) as a prerequisite for the sync layer.
Hi @falloficarus22,
Really interesting design direction here.
One thing I’m trying to reason through: if we go with the StackedSpace wrapper, would it become the single owner of the physical domain, with all child spaces treated as purely logical projections? In that case, should individual spaces stop inferring any bounds themselves?
Also, regarding synchronization — are you envisioning position updates being signal-driven (e.g., via HasEmitters) or routed explicitly through a stack-level movement API? It feels like that decision could significantly shape the API surface.
Curious to hear your thoughts on those trade-offs.
One thing I’m trying to reason through: if we go with the StackedSpace wrapper, would it become the single owner of the physical domain, with all child spaces treated as purely logical projections? In that case, should individual spaces stop inferring any bounds themselves?
I think StackedSpace should indeed become the single source of truth for physical bounds. If we let individual spaces infer their own bounds, we risk "extent drift" where the Grid and Network disagree on the world size.
In this model, child spaces effectively become logical projections. For example, an OrthogonalGrid wouldn't need width/height in its constructor; it would just need shape (number of cells), and it would map those cells to the StackedSpace dimensions. This makes the API much cleaner: StackedSpace(dimensions=(100, 100), spaces=[Grid(shape=(10, 10))]).
Also, regarding synchronization — are you envisioning position updates being signal-driven (e.g., via HasEmitters) or routed explicitly through a stack-level movement API? It feels like that decision could significantly shape the API surface.
I'm leaning towards a Signal-driven approach as the primary mechanism. Since we are moving toward the Locatable protocol and HasEmitters, having StackedSpace observe agent.position changes feels like the most "Mesa 4" way to do it. It keeps the Agent decoupled from the Space.
However, for performance-heavy models (e.g., 10k+ agents), the overhead of signals is a concern.
Making StackedSpace the single source of truth for bounds makes a lot of sense to avoid drift.
On synchronization, I like the signal-driven direction, but given the performance concern, do you think there’s room for batching or step-level reconciliation internally rather than reacting to every position change immediately?
Also, I’d be happy to explore this further with you if that’s helpful — this design space is really interesting.
On synchronization, I like the signal-driven direction, but given the performance concern, do you think there’s room for batching or step-level reconciliation internally rather than reacting to every position change immediately?
I think batching is the right direction, yes.
Also, I’d be happy to explore this further with you if that’s helpful — this design space is really interesting.
I don't want to get into implementation before #3287 being merged also this has to be discussed with the maintainers but surely if possible I would explore this with you.
I like share_dims from an API perspective. It also shares a family resemblance to sharex,sharey as used in matplotlib. I do, however, also understand the point about ambiguity. So, at a minimum, we need to clarify which relationships between spaces, when stacking, we want to allow. In my own thinking, I have always seen a single continuous space as the parent, and all other spaces can share dimensions only with that parent. But this might be too restrictive a view.
I can see value in option 2, but it needs work on the API side. Basically, you could create all spaces first and assign them to attributes before forcing a stacking via a wrapper. I do think exploring this option in a bit more detail is worth it.
I am not a fan of option 3. Model is already quite complicated. Stacking spaces is an advanced use case that should be opt-in rather than always present, given its potential overhead. In this, it's fundamentally different from agent registration, which any model needs.
Should the physical domain (bounds) be declared explicitly, or inferred from the first space? Grids know their dimensions; Networks and VoronoiGrids do not.
It depends on the answers to some questions articulated above. In a wrapper setup (option 2), it might be part of the wrapping. In option 1, I would be inclined to have a single parent space and other children or "derived" spaces just "inherit" the dimensions of this parent space.
PropertyLayer is being removed as a class (PR Remove PropertyLayer and HasPropertyLayers mixin #3340 ). It is being replaced with raw NumPy arrays stored directly on Grid as _property_layers: dict[str, np.ndarray]. This means property data will be grid-specific and should not be treated as a stackable space. Our API should focus on stacking DiscreteSpace subclasses (Grid, Network, VoronoiGrid) and ContinuousSpace.
Yes, at least for now. I'm still open to exploring, down the line, the potential to add property layers to continuous spaces directly, but I don't want to overcomplicate things at this moment.
What is the synchronization trigger? When an agent moves (agent.position = new_pos), how does the stacked space get notified? Via mesa_signals / HasEmitters? Via an explicit agent.move_to(pos) call on the stacked space?
Signals are used for loose coupling, so they are not appropriate here. So. I would argue that there must be some propagation mechanisms built into the stacking API. A relevant consideration here is whether all agents are present in all spaces in the stack, or whether agents must opt in or out of being present. In the conversation between @ewoutH and I, we where not in favour of beign present allways in all spaces. We did not reach an agreement over opt-in versus opt-out.
Can spaces belong to multiple stacks? Or is it strictly one stack per space?
I don't think there is a reasonable use case for multiple stacks. Moreover, I don't think that can even be well-defined (depending on the agent's presence conversation...). So, 1 stack only.
I like
share_dimsfrom an API perspective. It also shares a family resemblance tosharex,shareyas used in matplotlib. I do, however, also understand the point about ambiguity. So, at a minimum, we need to clarify which relationships between spaces, when stacking, we want to allow. In my own thinking, I have always seen a single continuous space as the parent, and all other spaces can share dimensions only with that parent. But this might be too restrictive a view.I can see value in option 2, but it needs work on the API side. Basically, you could create all spaces first and assign them to attributes before forcing a stacking via a wrapper. I do think exploring this option in a bit more detail is worth it.
My preference is to push Option 2 first as the core design, because it gives one explicit place to define shared bounds and synchronization without ambiguity. Then we can add Option 1 (share_dims) later as lightweight API sugar on top for convenience, once the stacking rules are solid.
Yes, at least for now. I'm still open to exploring, down the line, the potential to add property layers to continuous spaces directly, but I don't want to overcomplicate things at this moment.
Makes sense to me. I agree we should keep the current scope tight: stack actual spaces first, not property data structures.
So for this phase I’d treat property layers as grid-local only, and keep stacking focused on Grid/Network/Voronoi/ContinuousSpace. If we later want property layers for continuous spaces, we can add that as a separate design track once the core stacking API is stable.
Signals are used for loose coupling, so they are not appropriate here. So. I would argue that there must be some propagation mechanisms built into the stacking API. A relevant consideration here is whether all agents are present in all spaces in the stack, or whether agents must opt in or out of being present. In the conversation between @EwoutH and I, we where not in favour of beign present allways in all spaces. We did not reach an agreement over opt-in versus opt-out.
I’d lean opt-in as the default.
It keeps behavior explicit, avoids hidden overhead, and fits better with stacking being an advanced feature. Then add ergonomic helpers so opting in is easy (e.g., stack-level defaults by agent type), but don’t make “present everywhere” the implicit baseline.
I want to clarify one practical aspect of stacking :
If we go with StackedSpace as the single source of truth, should agent membership in child spaces be managed centrally by the stack, or should each child space still maintain its own agent registry?
In other words, when an agent opts into a stack, does the stack “project” it into each child space automatically, or does the agent still explicitly register with individual spaces?
I’m asking because this seems like it affects how much autonomy child spaces retain, and how complex synchronization logic becomes.
If StackedSpace is going to own the physical bounds, I think it should also own agent membership. Otherwise we’re splitting responsibility between the stack and the child spaces, which makes the rules harder to follow.
If both the stack and individual spaces can register agents, it’s easy to end up in inconsistent states. For example, an agent showing up in the grid but not in the network. Keeping membership centralized avoids that kind of drift.
Child spaces would still manage their own internal data and logic, but they wouldn’t independently decide whether a stacked agent exists. Presence would flow through the stack.
That keeps stacking explicit and opt-in, without adding hidden synchronization paths or overlapping ownership.
There are some good points here, please post it in #3458 if anyone is willing to discuss it further. Closing this to avoid duplication and its more productive to keep ideas at one place for tracking purpose. Continued in #3458
This one was started before #3458 (which should be considered duplicate instead) but nevermind.
This one was started before #3458 (which should be considered duplicate instead) but nevermind.
Yes I know but this is an issue not a discussion. GitHub Discussion support multiple threads in the same discussion.
Thanks for working on this and discussing it.
API Design ideally takes place in the discussions. See our development process.
I see some potential in a StackedSpace Wrapper. But I do think that's moving a bit ahead of what fundamentals we need to build first. I tried to write up some of this here:
- https://github.com/mesa/mesa/discussions/3458#discussioncomment-16508056
We also recognize the fierce competition on GSoC slots. We recognize both efforts, thanks for it.