Experimental#

This namespace contains experimental features. These are under development, and their API is not necessarily stable.

Cell Space#

Cell spaces for active, property-rich spatial modeling in Mesa.

Cell spaces extend Mesa’s spatial modeling capabilities by making the space itself active - each position (cell) can have properties and behaviors rather than just containing agents. This enables more sophisticated environmental modeling and agent-environment interactions.

Key components: - Cells: Active positions that can have properties and contain agents - CellAgents: Agents that understand how to interact with cells - Spaces: Different cell organization patterns (grids, networks, etc.) - PropertyLayers: Efficient property storage and manipulation

This is particularly useful for models where the environment plays an active role, like resource growth, pollution diffusion, or infrastructure networks. The cell space system is experimental and under active development.

class Cell(coordinate: tuple[int, ...], capacity: int | None = None, random: Random | None = None)[source]#

The cell represents a position in a discrete space.

coordinate#

the position of the cell in the discrete space

Type:

Tuple[int, int]

agents#

the agents occupying the cell

Type:

List[Agent]

capacity#

the maximum number of agents that can simultaneously occupy the cell

Type:

int

random#

the random number generator

Type:

Random

Initialise the cell.

Parameters:
  • coordinate – coordinates of the cell

  • capacity (int) – the capacity of the cell. If None, the capacity is infinite

  • random (Random) – the random number generator to use

connect(other: Cell, key: tuple[int, ...] | None = None) None[source]#

Connects this cell to another cell.

Parameters:
  • other (Cell) – other cell to connect to

  • key (Tuple[int, ...]) – key for the connection. Should resemble a relative coordinate

disconnect(other: Cell) None[source]#

Disconnects this cell from another cell.

Parameters:

other (Cell) – other cell to remove from connections

add_agent(agent: CellAgent) None[source]#

Adds an agent to the cell.

Parameters:

agent (CellAgent) – agent to add to this Cell

remove_agent(agent: CellAgent) None[source]#

Removes an agent from the cell.

Parameters:

agent (CellAgent) – agent to remove from this cell

property is_empty: bool#

Returns a bool of the contents of a cell.

property is_full: bool#

Returns a bool of the contents of a cell.

property neighborhood: CellCollection[Cell][source]#

Returns the direct neighborhood of the cell.

This is equivalent to cell.get_neighborhood(radius=1)

get_neighborhood(radius: int = 1, include_center: bool = False) CellCollection[Cell][source]#

Returns a list of all neighboring cells for the given radius.

For getting the direct neighborhood (i.e., radius=1) you can also use the neighborhood property.

Parameters:
  • radius (int) – the radius of the neighborhood

  • include_center (bool) – include the center of the neighborhood

Returns:

a list of all neighboring cells

class CellAgent(model: Model, *args, **kwargs)[source]#

Cell Agent is an extension of the Agent class and adds behavior for moving in discrete spaces.

cell#

The cell the agent is currently in.

Type:

Cell

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

remove()[source]#

Remove the agent from the model.

class CellCollection(cells: Mapping[T, list[CellAgent]] | Iterable[T], random: Random | None = None)[source]#

An immutable collection of cells.

cells[source]#

The list of cells this collection represents

Type:

List[Cell]

agents#

List of agents occupying the cells in this collection

Type:

List[CellAgent]

random#

The random number generator

Type:

Random

Notes

A UserWarning is issued if random=None. You can resolve this warning by explicitly passing a random number generator. In most cases, this will be the seeded random number generator in the model. So, you would do random=self.random in a Model or Agent instance.

Initialize a CellCollection.

Parameters:
  • cells – cells to add to the collection

  • random – a seeded random number generator.

select_random_cell() T[source]#

Select a random cell.

select_random_agent() CellAgent[source]#

Select a random agent.

Returns:

CellAgent instance

select(filter_func: Callable[[T], bool] | None = None, at_most: int | float = inf)[source]#

Select cells based on filter function.

Parameters:
  • filter_func – filter function

  • at_most – The maximum amount of cells to select. Defaults to infinity. - If an integer, at most the first number of matching cells is selected. - If a float between 0 and 1, at most that fraction of original number of cells

Returns:

CellCollection

class DiscreteSpace(capacity: int | None = None, cell_klass: type[~mesa.experimental.cell_space.discrete_space.T] = <class 'mesa.experimental.cell_space.cell.Cell'>, random: ~random.Random | None = None)[source]#

Base class for all discrete spaces.

capacity#

The capacity of the cells in the discrete space

Type:

int

all_cells[source]#

The cells composing the discrete space

Type:

CellCollection

random#

The random number generator

Type:

Random

cell_klass#

the type of cell class

Type:

Type

empties#

collection of all cells that are empty

Type:

CellCollection

property_layers#

the property layers of the discrete space

Type:

dict[str, PropertyLayer]

Notes

A UserWarning is issued if random=None. You can resolve this warning by explicitly passing a random number generator. In most cases, this will be the seeded random number generator in the model. So, you would do random=self.random in a Model or Agent instance.

Instantiate a DiscreteSpace.

Parameters:
  • capacity – capacity of cells

  • cell_klass – base class for all cells

  • random – random number generator

property agents: AgentSet#

Return an AgentSet with the agents in the space.

property all_cells[source]#

Return all cells in space.

property empties: CellCollection[T]#

Return all empty in spaces.

select_random_empty_cell() T[source]#

Select random empty cell.

class FixedAgent(model: Model, *args, **kwargs)[source]#

A patch in a 2D grid.

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

remove()[source]#

Remove the agent from the model.

class Grid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Base class for all grid classes.

dimensions#

the dimensions of the grid

Type:

Sequence[int]

torus#

whether the grid is a torus

Type:

bool

capacity#

the capacity of a grid cell

Type:

int

random#

the random number generator

Type:

Random

_try_random#

whether to get empty cell be repeatedly trying random cell

Type:

bool

Notes

width and height are accessible via properties, higher dimensions can be retrieved via dimensions

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

property width: int#

Convenience access to the width of the grid.

property height: int#

Convenience access to the height of the grid.

select_random_empty_cell() T[source]#

Select random empty cell.

class Grid2DMovingAgent(model: Model, *args, **kwargs)[source]#

Mixin for moving agents in 2D grids.

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

move(direction: str, distance: int = 1)[source]#

Move the agent in a cardinal direction.

Parameters:
  • direction – The cardinal direction to move in.

  • distance – The distance to move.

class HexGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

A Grid with hexagonal tilling of the space.

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

class Network(G: ~typing.Any, capacity: int | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.cell.Cell] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

A networked discrete space.

A Networked grid.

Parameters:
  • G – a NetworkX Graph instance.

  • capacity (int) – the capacity of the cell

  • random (Random) – a random number generator

  • cell_klass (type[Cell]) – The base Cell class to use in the Network

class OrthogonalMooreGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Grid where cells are connected to their 8 neighbors.

Example for two dimensions: directions = [

(-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1),

]

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

class OrthogonalVonNeumannGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Grid where cells are connected to their 4 neighbors.

Example for two dimensions: directions = [

(0, -1),

(-1, 0), ( 1, 0),

(0, 1),

]

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

class PropertyLayer(name: str, dimensions: ~collections.abc.Sequence[int], default_value=0.0, dtype=<class 'float'>)[source]#

A class representing a layer of properties in a two-dimensional grid.

Each cell in the grid can store a value of a specified data type.

name#

The name of the property layer.

dimensions#

The width of the grid (number of columns).

data#

A NumPy array representing the grid data.

Initializes a new PropertyLayer instance.

Parameters:
  • name – The name of the property layer.

  • dimensions – the dimensions of the property layer.

  • default_value – The default value to initialize each cell in the grid. Should ideally be of the same type as specified by the dtype parameter.

  • dtype (data-type, optional) – The desired data-type for the grid’s elements. Default is float.

Notes

A UserWarning is raised if the default_value is not of a type compatible with dtype. The dtype parameter can accept both Python data types (like bool, int or float) and NumPy data types (like np.int64 or np.float64).

classmethod from_data(name: str, data: ndarray)[source]#

Create a property layer from a NumPy array.

Parameters:
  • name – The name of the property layer.

  • data – A NumPy array representing the grid data.

set_cells(value, condition: Callable | None = None)[source]#

Perform a batch update either on the entire grid or conditionally, in-place.

Parameters:
  • value – The value to be used for the update.

  • condition – (Optional) A callable that returns a boolean array when applied to the data.

modify_cells(operation: Callable, value=None, condition: Callable | None = None)[source]#

Modify cells using an operation, which can be a lambda function or a NumPy ufunc.

If a NumPy ufunc is used, an additional value should be provided.

Parameters:
  • operation – A function to apply. Can be a lambda function or a NumPy ufunc.

  • value – The value to be used if the operation is a NumPy ufunc. Ignored for lambda functions.

  • condition – (Optional) A callable that returns a boolean array when applied to the data.

select_cells(condition: Callable, return_list=True)[source]#

Find cells that meet a specified condition using NumPy’s boolean indexing, in-place.

Parameters:
  • condition – A callable that returns a boolean array when applied to the data.

  • return_list – (Optional) If True, return a list of (x, y) tuples. Otherwise, return a boolean array.

Returns:

A list of (x, y) tuples or a boolean array.

aggregate(operation: Callable)[source]#

Perform an aggregate operation (e.g., sum, mean) on a property across all cells.

Parameters:

operation – A function to apply. Can be a lambda function or a NumPy ufunc.

class VoronoiGrid(centroids_coordinates: ~collections.abc.Sequence[~collections.abc.Sequence[float]], capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.cell.Cell] = <class 'mesa.experimental.cell_space.cell.Cell'>, capacity_function: callable = <function round_float>)[source]#

Voronoi meshed GridSpace.

A Voronoi Tessellation Grid.

Given a set of points, this class creates a grid where a cell is centered in each point, its neighbors are given by Voronoi Tessellation cells neighbors and the capacity by the polygon area.

Parameters:
  • centroids_coordinates – coordinates of centroids to build the tessellation space

  • capacity (int) – capacity of the cells in the discrete space

  • random (Random) – random number generator

  • cell_klass (type[Cell]) – type of cell class

  • capacity_function (Callable) – function to compute (int) capacity according to (float) area

Cells are positions in space that can have properties and contain agents.

A cell represents a location that can: - Have properties (like temperature or resources) - Track and limit the agents it contains - Connect to neighboring cells - Provide neighborhood information

Cells form the foundation of the cell space system, enabling rich spatial environments where both location properties and agent behaviors matter. They’re useful for modeling things like varying terrain, infrastructure capacity, or environmental conditions.

class Cell(coordinate: tuple[int, ...], capacity: int | None = None, random: Random | None = None)[source]#

The cell represents a position in a discrete space.

coordinate#

the position of the cell in the discrete space

Type:

Tuple[int, int]

agents#

the agents occupying the cell

Type:

List[Agent]

capacity#

the maximum number of agents that can simultaneously occupy the cell

Type:

int

random#

the random number generator

Type:

Random

Initialise the cell.

Parameters:
  • coordinate – coordinates of the cell

  • capacity (int) – the capacity of the cell. If None, the capacity is infinite

  • random (Random) – the random number generator to use

connect(other: Cell, key: tuple[int, ...] | None = None) None[source]#

Connects this cell to another cell.

Parameters:
  • other (Cell) – other cell to connect to

  • key (Tuple[int, ...]) – key for the connection. Should resemble a relative coordinate

disconnect(other: Cell) None[source]#

Disconnects this cell from another cell.

Parameters:

other (Cell) – other cell to remove from connections

add_agent(agent: CellAgent) None[source]#

Adds an agent to the cell.

Parameters:

agent (CellAgent) – agent to add to this Cell

remove_agent(agent: CellAgent) None[source]#

Removes an agent from the cell.

Parameters:

agent (CellAgent) – agent to remove from this cell

property is_empty: bool#

Returns a bool of the contents of a cell.

property is_full: bool#

Returns a bool of the contents of a cell.

property neighborhood: CellCollection[Cell][source]#

Returns the direct neighborhood of the cell.

This is equivalent to cell.get_neighborhood(radius=1)

get_neighborhood(radius: int = 1, include_center: bool = False) CellCollection[Cell][source]#

Returns a list of all neighboring cells for the given radius.

For getting the direct neighborhood (i.e., radius=1) you can also use the neighborhood property.

Parameters:
  • radius (int) – the radius of the neighborhood

  • include_center (bool) – include the center of the neighborhood

Returns:

a list of all neighboring cells

Agents that understand how to exist in and move through cell spaces.

Provides specialized agent classes that handle cell occupation, movement, and proper registration: - CellAgent: Mobile agents that can move between cells - FixedAgent: Immobile agents permanently fixed to cells - Grid2DMovingAgent: Agents with grid-specific movement capabilities

These classes ensure consistent agent-cell relationships and proper state management as agents move through the space. They can be used directly or as examples for creating custom cell-aware agents.

class HasCellProtocol(*args, **kwargs)[source]#

Protocol for discrete space cell holders.

class HasCell[source]#

Descriptor for cell movement behavior.

class BasicMovement[source]#

Mixin for moving agents in discrete space.

move_to(cell: Cell) None[source]#

Move to a new cell.

move_relative(direction: tuple[int, ...])[source]#

Move to a cell relative to the current cell.

Parameters:

direction – The direction to move in.

class FixedCell[source]#

Mixin for agents that are fixed to a cell.

class CellAgent(model: Model, *args, **kwargs)[source]#

Cell Agent is an extension of the Agent class and adds behavior for moving in discrete spaces.

cell#

The cell the agent is currently in.

Type:

Cell

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

remove()[source]#

Remove the agent from the model.

class FixedAgent(model: Model, *args, **kwargs)[source]#

A patch in a 2D grid.

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

remove()[source]#

Remove the agent from the model.

class Grid2DMovingAgent(model: Model, *args, **kwargs)[source]#

Mixin for moving agents in 2D grids.

Create a new agent.

Parameters:
  • model (Model) – The model instance in which the agent exists.

  • args – passed on to super

  • kwargs – passed on to super

Notes

to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super

move(direction: str, distance: int = 1)[source]#

Move the agent in a cardinal direction.

Parameters:
  • direction – The cardinal direction to move in.

  • distance – The distance to move.

Collection class for managing and querying groups of cells.

The CellCollection class provides a consistent interface for operating on multiple cells, supporting: - Filtering and selecting cells based on conditions - Random cell and agent selection - Access to contained agents - Group operations

This is useful for implementing area effects, zones, or any operation that needs to work with multiple cells as a unit. The collection handles efficient iteration and agent access across cells. The class is used throughout the cell space implementation to represent neighborhoods, selections, and other cell groupings.

class CellCollection(cells: Mapping[T, list[CellAgent]] | Iterable[T], random: Random | None = None)[source]#

An immutable collection of cells.

cells[source]#

The list of cells this collection represents

Type:

List[Cell]

agents#

List of agents occupying the cells in this collection

Type:

List[CellAgent]

random#

The random number generator

Type:

Random

Notes

A UserWarning is issued if random=None. You can resolve this warning by explicitly passing a random number generator. In most cases, this will be the seeded random number generator in the model. So, you would do random=self.random in a Model or Agent instance.

Initialize a CellCollection.

Parameters:
  • cells – cells to add to the collection

  • random – a seeded random number generator.

select_random_cell() T[source]#

Select a random cell.

select_random_agent() CellAgent[source]#

Select a random agent.

Returns:

CellAgent instance

select(filter_func: Callable[[T], bool] | None = None, at_most: int | float = inf)[source]#

Select cells based on filter function.

Parameters:
  • filter_func – filter function

  • at_most – The maximum amount of cells to select. Defaults to infinity. - If an integer, at most the first number of matching cells is selected. - If a float between 0 and 1, at most that fraction of original number of cells

Returns:

CellCollection

Base class for building cell-based spatial environments.

DiscreteSpace provides the core functionality needed by all cell-based spaces: - Cell creation and tracking - Agent-cell relationship management - Property layer support - Random selection capabilities - Capacity management

This serves as the foundation for specific space implementations like grids and networks, ensuring consistent behavior and shared functionality across different space types. All concrete cell space implementations (grids, networks, etc.) inherit from this class.

class DiscreteSpace(capacity: int | None = None, cell_klass: type[~experimental.cell_space.discrete_space.T] = <class 'mesa.experimental.cell_space.cell.Cell'>, random: ~random.Random | None = None)[source]#

Base class for all discrete spaces.

capacity#

The capacity of the cells in the discrete space

Type:

int

all_cells[source]#

The cells composing the discrete space

Type:

CellCollection

random#

The random number generator

Type:

Random

cell_klass#

the type of cell class

Type:

Type

empties#

collection of all cells that are empty

Type:

CellCollection

property_layers#

the property layers of the discrete space

Type:

dict[str, PropertyLayer]

Notes

A UserWarning is issued if random=None. You can resolve this warning by explicitly passing a random number generator. In most cases, this will be the seeded random number generator in the model. So, you would do random=self.random in a Model or Agent instance.

Instantiate a DiscreteSpace.

Parameters:
  • capacity – capacity of cells

  • cell_klass – base class for all cells

  • random – random number generator

property agents: AgentSet#

Return an AgentSet with the agents in the space.

property all_cells[source]#

Return all cells in space.

property empties: CellCollection[T]#

Return all empty in spaces.

select_random_empty_cell() T[source]#

Select random empty cell.

Grid-based cell space implementations with different connection patterns.

Provides several grid types for organizing cells: - OrthogonalMooreGrid: 8 neighbors in 2D, (3^n)-1 in nD - OrthogonalVonNeumannGrid: 4 neighbors in 2D, 2n in nD - HexGrid: 6 neighbors in hexagonal pattern (2D only)

Each grid type supports optional wrapping (torus) and cell capacity limits. Choose based on how movement and connectivity should work in your model - Moore for unrestricted movement, Von Neumann for orthogonal-only movement, or Hex for more uniform distances.

pickle_gridcell(obj)[source]#

Helper function for pickling GridCell instances.

unpickle_gridcell(parent, fields)[source]#

Helper function for unpickling GridCell instances.

class Grid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Base class for all grid classes.

dimensions#

the dimensions of the grid

Type:

Sequence[int]

torus#

whether the grid is a torus

Type:

bool

capacity#

the capacity of a grid cell

Type:

int

random#

the random number generator

Type:

Random

_try_random#

whether to get empty cell be repeatedly trying random cell

Type:

bool

Notes

width and height are accessible via properties, higher dimensions can be retrieved via dimensions

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

property width: int#

Convenience access to the width of the grid.

property height: int#

Convenience access to the height of the grid.

select_random_empty_cell() T[source]#

Select random empty cell.

class OrthogonalMooreGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Grid where cells are connected to their 8 neighbors.

Example for two dimensions: directions = [

(-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1),

]

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

class OrthogonalVonNeumannGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

Grid where cells are connected to their 4 neighbors.

Example for two dimensions: directions = [

(0, -1),

(-1, 0), ( 1, 0),

(0, 1),

]

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

class HexGrid(dimensions: ~collections.abc.Sequence[int], torus: bool = False, capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~experimental.cell_space.grid.T] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

A Grid with hexagonal tilling of the space.

Initialise the grid class.

Parameters:
  • dimensions – the dimensions of the space

  • torus – whether the space wraps

  • capacity – capacity of the grid cell

  • random – a random number generator

  • cell_klass – the base class to use for the cells

Network-based cell space using arbitrary connection patterns.

Creates spaces where cells connect based on network relationships rather than spatial proximity. Built on NetworkX graphs, this enables: - Arbitrary connectivity patterns between cells - Graph-based neighborhood definitions - Logical rather than physical distances - Dynamic connectivity changes - Integration with NetworkX’s graph algorithms

Useful for modeling systems like social networks, transportation systems, or any environment where connectivity matters more than physical location.

class Network(G: ~typing.Any, capacity: int | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.cell.Cell] = <class 'mesa.experimental.cell_space.cell.Cell'>)[source]#

A networked discrete space.

A Networked grid.

Parameters:
  • G – a NetworkX Graph instance.

  • capacity (int) – the capacity of the cell

  • random (Random) – a random number generator

  • cell_klass (type[Cell]) – The base Cell class to use in the Network

Cell spaces based on Voronoi tessellation around seed points.

Creates irregular spatial divisions by building cells around seed points, where each cell contains the area closer to its seed than any other. Features: - Organic-looking spaces from point sets - Automatic neighbor determination - Area-based cell capacities - Natural regional divisions

Useful for models requiring irregular but mathematically meaningful spatial divisions, like territories, service areas, or natural regions.

class Delaunay(center: tuple = (0, 0), radius: int = 9999)[source]#

Class to compute a Delaunay triangulation in 2D.

ref: jmespadero/pyDelaunay2D

Init and create a new frame to contain the triangulation.

Parameters:
  • center – Optional position for the center of the frame. Default (0,0)

  • radius – Optional distance from corners to the center.

add_point(point: Sequence) None[source]#

Add a point to the current DT, and refine it using Bowyer-Watson.

export_triangles() list[source]#

Export the current list of Delaunay triangles.

export_voronoi_regions()[source]#

Export coordinates and regions of Voronoi diagram as indexed data.

class VoronoiGrid(centroids_coordinates: ~collections.abc.Sequence[~collections.abc.Sequence[float]], capacity: float | None = None, random: ~random.Random | None = None, cell_klass: type[~mesa.experimental.cell_space.cell.Cell] = <class 'mesa.experimental.cell_space.cell.Cell'>, capacity_function: callable = <function round_float>)[source]#

Voronoi meshed GridSpace.

A Voronoi Tessellation Grid.

Given a set of points, this class creates a grid where a cell is centered in each point, its neighbors are given by Voronoi Tessellation cells neighbors and the capacity by the polygon area.

Parameters:
  • centroids_coordinates – coordinates of centroids to build the tessellation space

  • capacity (int) – capacity of the cells in the discrete space

  • random (Random) – random number generator

  • cell_klass (type[Cell]) – type of cell class

  • capacity_function (Callable) – function to compute (int) capacity according to (float) area

Devs#

Core event management functionality for Mesa’s discrete event simulation system.

This module provides the foundational data structures and classes needed for event-based simulation in Mesa. The EventList class is a priority queue implementation that maintains simulation events in chronological order while respecting event priorities. Key features:

  • Priority-based event ordering

  • Weak references to prevent memory leaks from canceled events

  • Efficient event insertion and removal using a heap queue

  • Support for event cancellation without breaking the heap structure

The module contains three main components: - Priority: An enumeration defining event priority levels (HIGH, DEFAULT, LOW) - SimulationEvent: A class representing individual events with timing and execution details - EventList: A heap-based priority queue managing the chronological ordering of events

The implementation supports both pure discrete event simulation and hybrid approaches combining agent-based modeling with event scheduling.

class Priority(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Enumeration of priority levels.

class SimulationEvent(time: int | float, function: Callable, priority: Priority = Priority.DEFAULT, function_args: list[Any] | None = None, function_kwargs: dict[str, Any] | None = None)[source]#

A simulation event.

The callable is wrapped using weakref, so there is no need to explicitly cancel event if e.g., an agent is removed from the simulation.

time#

The simulation time of the event

Type:

float

fn#

The function to execute for this event

Type:

Callable

priority#

The priority of the event

Type:

Priority

unique_id#
Type:

int

function_args#

Argument for the function

Type:

list[Any]

function_kwargs#

Keyword arguments for the function

Type:

Dict[str, Any]

Notes

simulation events use a weak reference to the callable. Therefore, you cannot pass a lambda function in fn. A simulation event where the callable no longer exists (e.g., because the agent has been removed from the model) will fail silently.

Initialize a simulation event.

Parameters:
  • time – the instant of time of the simulation event

  • function – the callable to invoke

  • priority – the priority of the event

  • function_args – arguments for callable

  • function_kwargs – keyword arguments for the callable

execute()[source]#

Execute this event.

cancel() None[source]#

Cancel this event.

class EventList[source]#

An event list.

This is a heap queue sorted list of events. Events are always removed from the left, so heapq is a performant and appropriate data structure. Events are sorted based on their time stamp, their priority, and their unique_id as a tie-breaker, guaranteeing a complete ordering.

Initialize an event list.

add_event(event: SimulationEvent)[source]#

Add the event to the event list.

Parameters:

event (SimulationEvent) – The event to be added

peak_ahead(n: int = 1) list[SimulationEvent][source]#

Look at the first n non-canceled event in the event list.

Parameters:

n (int) – The number of events to look ahead

Returns:

list[SimulationEvent]

Raises:

IndexError – If the eventlist is empty

Notes

this method can return a list shorted then n if the number of non-canceled events on the event list is less than n.

pop_event() SimulationEvent[source]#

Pop the first element from the event list.

is_empty() bool[source]#

Return whether the event list is empty.

remove(event: SimulationEvent) None[source]#

Remove an event from the event list.

Parameters:

event (SimulationEvent) – The event to be removed

clear()[source]#

Clear the event list.

Simulator implementations for different time advancement approaches in Mesa.

This module provides simulator classes that control how simulation time advances and how events are executed. It supports both discrete-time and continuous-time simulations through three main classes:

  • Simulator: Base class defining the core simulation control interface

  • ABMSimulator: A simulator for agent-based models that combines fixed time steps with event scheduling. Uses integer time units and automatically schedules model.step()

  • DEVSimulator: A pure discrete event simulator using floating-point time units for continuous time simulation

Key features: - Flexible time units (integer or float) - Event scheduling using absolute or relative times - Priority-based event execution - Support for running simulations for specific durations or until specific end times

The simulators enable Mesa models to use traditional time-step based approaches, pure event-driven approaches, or hybrid combinations of both.

class Simulator(time_unit: type, start_time: int | float)[source]#

The Simulator controls the time advancement of the model.

The simulator uses next event time progression to advance the simulation time, and execute the next event

event_list#

The list of events to execute

Type:

EventList

time#

The current simulation time

Type:

float | int

time_unit#

The unit of the simulation time

Type:

type

model#

The model to simulate

Type:

Model

Initialize a Simulator instance.

Parameters:
  • time_unit – type of the smulaiton time

  • start_time – the starttime of the simulator

setup(model: Model) None[source]#

Set up the simulator with the model to simulate.

Parameters:

model (Model) – The model to simulate

Raises:
  • Exception if simulator.time is not equal to simulator.starttime

  • Exception if event list is not empty

reset()[source]#

Reset the simulator by clearing the event list and removing the model to simulate.

run_until(end_time: int | float) None[source]#

Run the simulator until the end time.

Parameters:

end_time (int | float) – The end time for stopping the simulator

Raises:

Exception if simulator.setup() has not yet been called

run_next_event()[source]#

Execute the next event.

Raises:

Exception if simulator.setup() has not yet been called

run_for(time_delta: int | float)[source]#

Run the simulator for the specified time delta.

Parameters:

time_delta (float| int) – The time delta. The simulator is run from the current time to the current time plus the time delta

schedule_event_now(function: Callable, priority: Priority = Priority.DEFAULT, function_args: list[Any] | None = None, function_kwargs: dict[str, Any] | None = None) SimulationEvent[source]#

Schedule event for the current time instant.

Parameters:
  • function (Callable) – The callable to execute for this event

  • priority (Priority) – the priority of the event, optional

  • function_args (List[Any]) – list of arguments for function

  • function_kwargs (Dict[str, Any]) – dict of keyword arguments for function

Returns:

the simulation event that is scheduled

Return type:

SimulationEvent

schedule_event_absolute(function: Callable, time: int | float, priority: Priority = Priority.DEFAULT, function_args: list[Any] | None = None, function_kwargs: dict[str, Any] | None = None) SimulationEvent[source]#

Schedule event for the specified time instant.

Parameters:
  • function (Callable) – The callable to execute for this event

  • time (int | float) – the time for which to schedule the event

  • priority (Priority) – the priority of the event, optional

  • function_args (List[Any]) – list of arguments for function

  • function_kwargs (Dict[str, Any]) – dict of keyword arguments for function

Returns:

the simulation event that is scheduled

Return type:

SimulationEvent

schedule_event_relative(function: Callable, time_delta: int | float, priority: Priority = Priority.DEFAULT, function_args: list[Any] | None = None, function_kwargs: dict[str, Any] | None = None) SimulationEvent[source]#

Schedule event for the current time plus the time delta.

Parameters:
  • function (Callable) – The callable to execute for this event

  • time_delta (int | float) – the time delta

  • priority (Priority) – the priority of the event, optional

  • function_args (List[Any]) – list of arguments for function

  • function_kwargs (Dict[str, Any]) – dict of keyword arguments for function

Returns:

the simulation event that is scheduled

Return type:

SimulationEvent

cancel_event(event: SimulationEvent) None[source]#

Remove the event from the event list.

Parameters:

event (SimulationEvent) – The simulation event to remove

class ABMSimulator[source]#

This simulator uses incremental time progression, while allowing for additional event scheduling.

The basic time unit of this simulator is an integer. It schedules model.step for each tick with the highest priority. This implies that by default, model.step is the first event executed at a specific tick. In addition, discrete event scheduling, using integer as the time unit is fully supported, paving the way for hybrid ABM-DEVS simulations.

Initialize a ABM simulator.

setup(model)[source]#

Set up the simulator with the model to simulate.

Parameters:

model (Model) – The model to simulate

check_time_unit(time) bool[source]#

Check whether the time is of the correct unit.

Parameters:

time (int | float) – the time

Returns:

whether the time is of the correct unit

Return type:

bool

schedule_event_next_tick(function: Callable, priority: Priority = Priority.DEFAULT, function_args: list[Any] | None = None, function_kwargs: dict[str, Any] | None = None) SimulationEvent[source]#

Schedule a SimulationEvent for the next tick.

Parameters:
  • function (Callable) – the callable to execute

  • priority (Priority) – the priority of the event

  • function_args (List[Any]) – List of arguments to pass to the callable

  • function_kwargs (Dict[str, Any]) – List of keyword arguments to pass to the callable

run_until(end_time: int) None[source]#

Run the simulator up to and included the specified end time.

Parameters:

end_time (float| int) – The end_time delta. The simulator is until the specified end time

Raises:

Exception if simulator.setup() has not yet been called

class DEVSimulator[source]#

A simulator where the unit of time is a float.

Can be used for full-blown discrete event simulating using event scheduling.

Initialize a DEVS simulator.

check_time_unit(time) bool[source]#

Check whether the time is of the correct unit.

Parameters:

time (float) – the time

Returns: bool: whether the time is of the correct unit

Continuous Space#

A Continuous Space class.

class ContinuousSpace(dimensions: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], torus: bool = False, random: Random | None = None, n_agents: int = 100)[source]#

Continuous space where each agent can have an arbitrary position.

Create a new continuous space.

Parameters:
  • dimensions – a numpy array like object where each row specifies the minimum and maximum value of that dimension.

  • torus – boolean for whether the space wraps around or not

  • random – a seeded stdlib random.Random instance

  • n_agents – the expected number of agents in the space

Internally, a numpy array is used to store the positions of all agents. This is resized if needed, but you can control the initial size explicitly by passing n_agents.

property agents: AgentSet#

Return an AgentSet with the agents in the space.

calculate_difference_vector(point: ndarray, agents=None) ndarray[source]#

Calculate the difference vector between the point and all agenents.

Parameters:
  • point – the point to calculate the difference vector for

  • agents – the agents to calculate the difference vector of point with. By default, all agents are considered.

calculate_distances(point: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], agents: Iterable[Agent] | None = None, **kwargs) tuple[ndarray, list][source]#

Calculate the distance between the point and all agents.

Parameters:
  • point – the point to calculate the difference vector for

  • agents – the agents to calculate the difference vector of point with. By default, all agents are considered.

  • kwargs – any additional keyword arguments are passed to scipy’s cdist, which is used only if torus is False. This allows for non-Euclidian distance measures.

get_agents_in_radius(point: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], radius: float | int = 1) tuple[list, ndarray][source]#

Return the agents and their distances within a radius for the point.

get_k_nearest_agents(point: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], k: int = 1) tuple[list, ndarray][source]#

Return the k nearest agents and their distances to the point.

Notes

This method returns exactly k agents, ignoring ties. In case of ties, the earlier an agent is inserted the higher it will rank.

in_bounds(point: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) bool[source]#

Check if point is inside the bounds of the space.

torus_correct(point: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) ndarray[source]#

Apply a torus correction to the point.

Continuous space agents.

class HasPositionProtocol(*args, **kwargs)[source]#

Protocol for continuous space position holders.

class ContinuousSpaceAgent(space: ContinuousSpace, model)[source]#

A continuous space agent.

space#

the continuous space in which the agent is located

Type:

ContinuousSpace

position#

the position of the agent

Type:

np.ndarray

Initialize a continuous space agent.

Parameters:
  • space – the continuous space in which the agent is located

  • model – the model to which the agent belongs

property position: ndarray#

Position of the agent.

remove() None[source]#

Remove and delete the agent from the model and continuous space.

get_neighbors_in_radius(radius: float | int = 1) tuple[list, ndarray][source]#

Get neighbors within radius.

Parameters:

radius – radius within which to look for neighbors

get_nearest_neighbors(k: int = 1) tuple[list, ndarray][source]#

Get neighbors within radius.

Parameters:

k – the number of nearest neighbors to return