mesa package#
Submodules#
mesa.agent module#
Agent related classes.
Core Objects: Agent.
- class Agent(model: M, *args, **kwargs)[source]#
Bases:
GenericBase class for a model agent in Mesa.
- pos#
A reference to the position where this agent is located.
- Type:
Position
Notes
Agents must be hashable to be used in an AgentSet. In Python 3, defining __eq__ without __hash__ makes an object unhashable, which will break AgentSet usage. unique_id is unique relative to a model instance and starts from 1
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() None[source]#
Remove and delete the agent from the model.
Notes
If you need to do additional cleanup when removing an agent by for example removing it from a space, consider extending this method in your own agent class.
- classmethod create_agents(model: Model, n: int, *args, **kwargs) AgentSet[T][source]#
Create N agents.
- Parameters:
model – the model to which the agents belong
args – arguments to pass onto agent instances each arg is either a single object or a sequence of length n
n – the number of agents to create
kwargs – keyword arguments to pass onto agent instances each keyword arg is either a single object or a sequence of length n
- Returns:
AgentSet containing the agents created.
- classmethod from_dataframe(model: Model, df: pd.DataFrame, **kwargs) AgentSet[T][source]#
Create agents from a pandas DataFrame.
Each row of the DataFrame represents one agent. The DataFrame columns are mapped to the agent’s constructor as keyword arguments. Additional keyword arguments (**kwargs) can be used to set constant attributes for all agents.
- Parameters:
model – The model instance.
df – The pandas DataFrame. Each row represents an agent.
**kwargs – Constant values to pass to every agent’s constructor. Only non-sequence data is allowed in kwargs to avoid ambiguity with DataFrame columns.
- Returns:
AgentSet containing the agents created.
Note
If you need to pass variable data or sequences, add them as columns to the DataFrame before calling this method.
- property rng: Generator#
Return a seeded np.random rng.
- property scenario#
Return the scenario associated with the model.
mesa.batchrunner module#
batchrunner for running a factorial experiment design over a model.
To take advantage of parallel execution of experiments, batch_run uses
multiprocessing if number_processes is larger than 1. It is strongly advised
to only run in parallel using a normal python file (so don’t try to do it in a
jupyter notebook). This is because Jupyter notebooks have a different execution
model that can cause issues with Python’s multiprocessing module, especially on
Windows. The main problems include the lack of a traditional __main__ entry
point, serialization issues, and potential deadlocks.
Moreover, best practice when using multiprocessing is to
put the code inside an if __name__ == '__main__': code black as shown below:
from mesa.batchrunner import batch_run
params = {"width": 10, "height": 10, "N": range(10, 500, 10)}
if __name__ == '__main__':
results = batch_run(
MoneyModel,
parameters=params,
iterations=5,
max_steps=100,
number_processes=None,
data_collection_period=1,
display_progress=True,
)
- batch_run(model_cls: type[Model], parameters: Mapping[str, Any | Iterable[Any]], number_processes: int | None = 1, iterations: int | None = None, data_collection_period: int = -1, max_steps: int = 1000, display_progress: bool = True, rng: int | integer | Sequence[int] | SeedSequence | Iterable[int | integer | Sequence[int] | SeedSequence] | None = None) list[dict[str, Any]][source]#
Batch run a mesa model with a set of parameter values.
- Parameters:
model_cls (Type[Model]) – The model class to batch-run
parameters (Mapping[str, Union[Any, Iterable[Any]]]) – Dictionary with model parameters over which to run the model. You can either pass single values or iterables.
number_processes (int, optional) – Number of processes used, by default 1. Set this to None if you want to use all CPUs.
iterations (int, optional) – Number of iterations for each parameter combination, by default 1
data_collection_period (int, optional) – Number of steps after which data gets collected, by default -1 (end of episode)
max_steps (int, optional) – Maximum number of model steps after which the model halts, by default 1000
display_progress (bool, optional) – Display batch run process, by default True
rng – a valid value or iterable of values for seeding the random number generator in the model
- Returns:
List[Dict[str, Any]]
Notes
batch_run assumes the model has a datacollector attribute that has a DataCollector object initialized.
mesa.datacollection module#
Mesa Data Collection Module.
DataCollector is meant to provide a simple, standard way to collect data generated by a Mesa model. It collects four types of data: model-level data, agent-level data, agent-type-level data, and tables.
A DataCollector is instantiated with three dictionaries of reporter names and associated variable names or functions for each, one for model-level data, one for agent-level data, and one for agent-type-level data; a fourth dictionary provides table names and columns. Variable names are converted into functions which retrieve attributes of that name.
When the collect() method is called, each model-level function is called, with the model as the argument, and the results associated with the relevant variable. Then the agent-level functions are called on each agent, and the agent-type-level functions are called on each agent of the specified type.
Additionally, other objects can write directly to tables by passing in an appropriate dictionary object for a table row.
- The DataCollector then stores the data it collects in dictionaries:
model_vars maps each reporter to a list of its values
tables maps each table to a dictionary, with each column as a key with a list as its value.
_agent_records maps each model step to a list of each agent’s id and its values.
_agenttype_records maps each model step to a dictionary of agent types, each containing a list of each agent’s id and its values.
Finally, DataCollector can create a pandas DataFrame from each collection.
- class DataCollector(model_reporters=None, agent_reporters=None, agenttype_reporters=None, tables=None)[source]#
Bases:
objectClass for collecting data generated by a Mesa model.
A DataCollector is instantiated with dictionaries of names of model-, agent-, and agent-type-level variables to collect, associated with attribute names or functions which actually collect them. When the collect(…) method is called, it collects these attributes and executes these functions one by one and stores the results.
Instantiate a DataCollector with lists of model, agent, and agent-type reporters.
Both model_reporters, agent_reporters, and agenttype_reporters accept a dictionary mapping a variable name to either an attribute name, a function, a method of a class/instance, a partial function, or a function with parameters placed in a list.
Model reporters can take five types of arguments: 1. Lambda function:
{“agent_count”: lambda m: len(m.agents)}
Method of a class/instance: {“agent_count”: self.get_agent_count} # self here is a class instance {“agent_count”: Model.get_agent_count} # Model here is a class
Class attributes of a model: {“model_attribute”: “model_attribute”}
Partial function: {“agent_count”: functools.partial(count_agents, multiplier=2)}
Functions with parameters that have been placed in a list: {“Model_Function”: [function, [param_1, param_2]]}
Agent reporters can similarly take: 1. Attribute name (string) referring to agent’s attribute:
{“energy”: “energy”}
Lambda function: {“energy”: lambda a: a.energy}
Method of an agent class/instance: {“agent_action”: self.do_action} # self here is an agent class instance {“agent_action”: Agent.do_action} # Agent here is a class
Partial function: {“energy”: functools.partial(get_energy, scale=2)}
Functions with parameters placed in a list: {“Agent_Function”: [function, [param_1, param_2]]}
Agenttype reporters take a dictionary mapping agent types to dictionaries of reporter names and attributes/funcs/methods, similar to agent_reporters:
{Wolf: {“energy”: lambda a: a.energy}}
The tables arg accepts a dictionary mapping names of tables to lists of columns. For example, if we want to allow agents to write their age when they are destroyed (to keep track of lifespans), it might look like:
{“Lifespan”: [“unique_id”, “age”]}
- Parameters:
model_reporters – Dictionary of reporter names and attributes/funcs/methods.
agent_reporters – Dictionary of reporter names and attributes/funcs/methods.
agenttype_reporters – Dictionary of agent types to dictionaries of reporter names and attributes/funcs/methods.
tables – Dictionary of table names to lists of column names.
Notes
If you want to pickle your model you must not use lambda functions.
If your model includes a large number of agents, it is recommended to use attribute names for the agent reporter, as it will be faster.
- add_table_row(table_name, row, ignore_missing=False)[source]#
Add a row dictionary to a specific table.
- Parameters:
table_name – Name of the table to append a row to.
row – A dictionary of the form {column_name: value…}
ignore_missing – If True, fill any missing columns with Nones; if False, throw an error if any columns are missing
- get_model_vars_dataframe()[source]#
Create a pandas DataFrame from the model variables.
The DataFrame has one column for each model variable, and the index is (implicitly) the model tick.
- get_agent_vars_dataframe()[source]#
Create a pandas DataFrame from the agent variables.
The DataFrame has one column for each variable, with two additional columns for tick and agent_id.
mesa.main module#
mesa.model module#
The model class for Mesa framework.
Core Objects: Model
- class Model(*args: Any, seed: float | None = None, rng: RNGLike | SeedLike | None = None, scenario: S | None = None, **kwargs: Any)[source]#
Bases:
HasObservables,GenericBase class for models in the Mesa ABM library.
This class serves as a foundational structure for creating agent-based models. It includes the basic attributes and methods necessary for initializing and running a simulation model.
- Type Parameters:
A: The agent type used in this model S: The scenario type used in this model
- running#
A boolean indicating if the model should continue running.
- steps#
the number of times model.step() has been called.
- time#
the current simulation time. Automatically increments by 1.0 with each step unless controlled by a discrete event simulator.
- random#
a seeded python.random number generator.
- rng#
a seeded numpy.random.Generator
- scenario#
the scenario instance containing model parameters
Notes
Model.agents returns the AgentSet containing all agents registered with the model. Changing the content of the AgentSet directly can result in strange behavior. If you want change the composition of this AgentSet, ensure you operate on a copy.
Create a new model.
Overload this method with the actual code to initialize the model. Always start with super().__init__() to initialize the model object properly.
- Parameters:
args – arguments to pass onto super
seed – the seed for the random number generator
rng – Pseudorandom number generator state. When rng is None, a new numpy.random.Generator is created using entropy from the operating system. Types other than numpy.random.Generator are passed to numpy.random.default_rng to instantiate a Generator.
scenario – the scenario specifying the computational experiment to run
kwargs – keyword arguments to pass onto super
Notes
you have to pass either seed or rng, but not both.
- time: float#
Observable descriptor.
An observable is an attribute that emits ObservableSignals.CHANGED whenever it is changed to a different value.
- property scenario: S#
Return scenario instance.
- property agents: _HardKeyAgentSet[A]#
Provides a _HardKeyAgentSet of all agents in the model, combining agents from all types.
- Returns:
The agent set containing all agents with strong references.
- Return type:
_HardKeyAgentSet
Warning
This returns the actual internal _HardKeyAgentSet used by Mesa for agent registration and tracking. It uses strong references to prevent premature garbage collection and reduce performance overhead caused by weak reference management.
Do not modify this AgentSet directly (e.g., by adding or removing agents manually). Direct modifications can break the model’s agent tracking system and cause unexpected behavior. Instead:
Use
Agent()to create new agents (automatically registers them)Use
agent.remove()to remove agents (automatically deregisters them)For read-only operations or transformations, work on a copy:
model.agents.copy()
Notes
This is Mesa’s core agent registration system. All agents created via
Agent.__init__are automatically registered here.
- property agent_types: list[type]#
Return a list of all unique agent types registered with the model.
- property agents_by_type: dict[type[A], _HardKeyAgentSet[A]]#
A dictionary where keys are agent types and values are the corresponding _HardKeyAgentSets.
- Returns:
Dictionary mapping agent types to their AgentSets.
- Return type:
Warning
Each AgentSet in this dictionary is a _HardKeyAgentSet with strong references, forming part of Mesa’s core agent registration system.
Do not modify these AgentSets directly. Direct modifications can break agent tracking and cause unexpected behavior. Instead:
Use
Agent()to create new agents (automatically registers them)Use
agent.remove()to remove agents (automatically deregisters them)For read-only operations, work on copies:
model.agents_by_type[AgentType].copy()
Notes
This is part of Mesa’s core agent registration system. All agents are automatically registered in the appropriate type-specific AgentSet when created via
Agent.__init__.
- register_agent(agent: A)[source]#
Register the agent with the model.
- Parameters:
agent – The agent to register.
Notes
This method is called automatically by
Agent.__init__, so there is no need to use this if you are subclassing Agent and calling its super in the__init__method.
- deregister_agent(agent: A)[source]#
Deregister the agent with the model.
- Parameters:
agent – The agent to deregister.
Notes
This method is called automatically by
Agent.remove
- observables = {'agents': frozenset({ModelSignals.AGENT_ADDED, ModelSignals.AGENT_REMOVED}), 'time': <enum 'ObservableSignals'>}#
- reset_randomizer(seed: int | None = None) None[source]#
Reset the model random number generator.
- Parameters:
seed – A new seed for the RNG; if None, reset using the current seed
- reset_rng(rng: Generator | BitGenerator | int | integer | Sequence[int] | SeedSequence | None = None) None[source]#
Reset the model random number generator.
- Parameters:
rng – A new seed for the RNG; if None, reset using the current seed
- remove_all_agents()[source]#
Remove all agents from the model.
Notes
This method calls agent.remove for all agents in the model. If you need to remove agents from e.g., a SingleGrid, you can either explicitly implement your own agent.remove method or clean this up near where you are calling this method.
- schedule_event(function: Callable, *, at: float | None = None, after: float | None = None, priority: Priority = Priority.DEFAULT) Event[source]#
Schedule a one-off event.
- Parameters:
function – The callable to execute
at – Absolute time to execute (mutually exclusive with after)
after – Relative time from now to execute (mutually exclusive with at)
priority – Priority level for the event
- Returns:
The scheduled Event (can be used to cancel)
- Raises:
ValueError – If both or neither of at/after are specified
ValueError – If both or neither of at/after are specified, or if the scheduled time is in the past.
- schedule_recurring(function: Callable, schedule: Schedule, priority: Priority = Priority.DEFAULT) EventGenerator[source]#
Schedule a recurring event based on a Schedule.
- Parameters:
function – The callable to execute repeatedly
schedule – The Schedule defining when events occur
priority – Priority level for generated events
- Returns:
The EventGenerator (can be used to stop)
- Raises:
ValueError – If the schedule start time is in the past.
mesa.space module#
Mesa Space Module.
Objects used to add a spatial component to a model.
Note
mesa.space now in maintenance-only mode. While these classes remain
fully supported, new development occurs in the discrete space module
(mesa.discrete_space) and the experimental ContinuousSpace module
Classes#
PropertyLayer: A data layer that can be added to Grids to store cell properties
SingleGrid: a Grid which strictly enforces one agent per cell.
MultiGrid: a Grid where each cell can contain a set of agents.
HexGrid: a Grid to handle hexagonal neighbors.
ContinuousSpace: a two-dimensional space where each agent has an arbitrary position of float’s.
NetworkGrid: a network where each node contains zero or more agents.
- accept_tuple_argument(wrapped_function: F) F[source]#
Decorator to allow grid methods that take a list of (x, y) coord tuples to also handle a single position.
Tuples are wrapped in a single-item list rather than forcing user to do it.
- warn_if_agent_has_position_already(placement_func)[source]#
Decorator to give warning if agent has position already set.
- class PropertyLayer(name: str, width: int, height: int, default_value, dtype=<class 'numpy.float64'>)[source]#
Bases:
objectA 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.
- data#
A NumPy array representing the grid data.
- Type:
numpy.ndarray
Initializes a new PropertyLayer instance.
- Parameters:
name (str) – The name of the property layer.
width (int) – The width of the grid (number of columns). Must be a positive integer.
height (int) – The height of the grid (number of rows). Must be a positive integer.
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 np.float64.
- Raises:
ValueError – If width or height is not a positive integer.
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). Using NumPy data types is recommended (except for bool) for better control over the precision and efficiency of data storage and computations, especially in cases of large data volumes or specialized numerical operations.
- set_cells(value, condition=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 (like a lambda function or a NumPy ufunc) that returns a boolean array when applied to the data.
- modify_cell(position: tuple[int, int], operation, value=None)[source]#
Modify a single cell 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:
position – The grid coordinates of the cell to modify.
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.
- modify_cells(operation, value=None, condition_function=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_function – (Optional) A callable that returns a boolean array when applied to the data.
- select_cells(condition, 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.
- class SingleGrid(width: int, height: int, torus: bool, property_layers: None | PropertyLayer | list[PropertyLayer] = None)[source]#
Bases:
_PropertyGridRectangular grid where each cell contains exactly at most one agent.
Grid cells are indexed by [x, y], where [0, 0] is assumed to be the bottom-left and [width-1, height-1] is the top-right. If a grid is toroidal, the top and bottom, and left and right, edges wrap to each other.
This class provides a property empties that returns a set of coordinates for all empty cells in the grid. It is automatically updated whenever agents are added or removed from the grid. The empties property should be used for efficient access to current empty cells rather than manually iterating over the grid to check for emptiness.
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus. empties: Returns a set of (x, y) tuples for all empty cells. This set is
maintained internally and provides a performant way to query the grid for empty spaces.
Initializes a new _PropertyGrid instance with specified dimensions and optional property layers.
- Parameters:
width (int) – The width of the grid (number of columns).
height (int) – The height of the grid (number of rows).
torus (bool) – A boolean indicating if the grid should behave like a torus.
property_layers (None | PropertyLayer | list[PropertyLayer], optional) – A single PropertyLayer instance, a list of PropertyLayer instances, or None to initialize without any property layers.
- Raises:
ValueError – If a property layer’s dimensions do not match the grid dimensions.
- class MultiGrid(width: int, height: int, torus: bool, property_layers: None | PropertyLayer | list[PropertyLayer] = None)[source]#
Bases:
_PropertyGridRectangular grid where each cell can contain more than one agent.
Grid cells are indexed by [x, y], where [0, 0] is assumed to be at bottom-left and [width-1, height-1] is the top-right. If a grid is toroidal, the top and bottom, and left and right, edges wrap to each other.
This class maintains an empties property, which is a set of coordinates for all cells that currently contain no agents. This property is updated automatically as agents are added to or removed from the grid.
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus. empties: Returns a set of (x, y) tuples for all empty cells.
Initializes a new _PropertyGrid instance with specified dimensions and optional property layers.
- Parameters:
width (int) – The width of the grid (number of columns).
height (int) – The height of the grid (number of rows).
torus (bool) – A boolean indicating if the grid should behave like a torus.
property_layers (None | PropertyLayer | list[PropertyLayer], optional) – A single PropertyLayer instance, a list of PropertyLayer instances, or None to initialize without any property layers.
- Raises:
ValueError – If a property layer’s dimensions do not match the grid dimensions.
- remove_agent(agent: Agent) None[source]#
Remove the agent from the given location and set its pos attribute to None.
- iter_neighbors(pos: tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) Iterator[Agent][source]#
Return an iterator over neighbors to a certain point.
- Parameters:
pos – Coordinates for the neighborhood to get.
moore –
- If True, return Moore neighborhood
(including diagonals)
- If False, return Von Neumann neighborhood
(exclude diagonals)
include_center – If True, return the (x, y) cell as well. Otherwise, return surrounding cells only.
radius – radius, in cells, of neighborhood to get.
- Returns:
An iterator of non-None objects in the given neighborhood; at most 9 if Moore, 5 if Von-Neumann (8 and 4 if not including the center).
- class HexSingleGrid(width: int, height: int, torus: bool, property_layers: None | PropertyLayer | list[PropertyLayer] = None)[source]#
Bases:
_HexGrid,SingleGridHexagonal SingleGrid: a SingleGrid where neighbors are computed according to a hexagonal tiling of the grid.
Functions according to odd-q rules. See http://www.redblobgames.com/grids/hexagons/#coordinates for more.
This class also maintains an empties property, similar to SingleGrid, which provides a set of coordinates for all empty hexagonal cells.
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus. empties: Returns a set of hexagonal coordinates for all empty cells.
Initializes a new _PropertyGrid instance with specified dimensions and optional property layers.
- Parameters:
width (int) – The width of the grid (number of columns).
height (int) – The height of the grid (number of rows).
torus (bool) – A boolean indicating if the grid should behave like a torus.
property_layers (None | PropertyLayer | list[PropertyLayer], optional) – A single PropertyLayer instance, a list of PropertyLayer instances, or None to initialize without any property layers.
- Raises:
ValueError – If a property layer’s dimensions do not match the grid dimensions.
- class HexMultiGrid(width: int, height: int, torus: bool, property_layers: None | PropertyLayer | list[PropertyLayer] = None)[source]#
Bases:
_HexGrid,MultiGridHexagonal MultiGrid: a MultiGrid where neighbors are computed according to a hexagonal tiling of the grid.
Functions according to odd-q rules. See http://www.redblobgames.com/grids/hexagons/#coordinates for more.
Similar to the standard MultiGrid, this class maintains an empties property, which is a set of coordinates for all hexagonal cells that currently contain no agents. This property is updated automatically as agents are added to or removed from the grid.
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus. empties: Returns a set of hexagonal coordinates for all empty cells.
Initializes a new _PropertyGrid instance with specified dimensions and optional property layers.
- Parameters:
width (int) – The width of the grid (number of columns).
height (int) – The height of the grid (number of rows).
torus (bool) – A boolean indicating if the grid should behave like a torus.
property_layers (None | PropertyLayer | list[PropertyLayer], optional) – A single PropertyLayer instance, a list of PropertyLayer instances, or None to initialize without any property layers.
- Raises:
ValueError – If a property layer’s dimensions do not match the grid dimensions.
- class ContinuousSpace(x_max: float, y_max: float, torus: bool, x_min: float = 0, y_min: float = 0)[source]#
Bases:
objectContinuous space where each agent can have an arbitrary position.
Assumes that all agents have a pos property storing their position as an (x, y) tuple.
This class uses a numpy array internally to store agents in order to speed up neighborhood lookups. This array is calculated on the first neighborhood lookup, and is updated if agents are added or removed.
The concept of ‘empty cells’ is not directly applicable in continuous space, as positions are not discretized.
Create a new continuous space.
- Parameters:
x_max – the maximum x-coordinate
y_max – the maximum y-coordinate.
torus – Boolean for whether the edges loop around.
x_min – (default 0) If provided, set the minimum x -coordinate for the space. Below them, values loop to the other edge (if torus=True) or raise an exception.
y_min – (default 0) If provided, set the minimum y -coordinate for the space. Below them, values loop to the other edge (if torus=True) or raise an exception.
- move_agent(agent: Agent, pos: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]]) None[source]#
Move an agent from its current position to a new position.
- Parameters:
agent – The agent object to move.
pos – Coordinate tuple to move the agent to.
- remove_agent(agent: Agent) None[source]#
Remove an agent from the space.
- Parameters:
agent – The agent object to remove
- get_neighbors(pos: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]], radius: float, include_center: bool = True) list[Agent][source]#
Get all agents within a certain radius.
- Parameters:
pos – (x,y) coordinate tuple to center the search at.
radius – Get all the objects within this distance of the center.
include_center – If True, include an object at the exact provided coordinates. i.e. if you are searching for the neighbors of a given agent, True will include that agent in the results.
Notes
If 1 or more agents are located on pos, include_center=False will remove all these agents from the results. So, if you really want to get the neighbors of a given agent, you should set include_center=True, and then filter the list of agents to remove the given agent (i.e., self when calling it from an agent).
- get_heading(pos_1: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]], pos_2: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]]) tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]][source]#
Get the heading vector between two points, accounting for toroidal space.
It is possible to calculate the heading angle by applying the atan2 function to the result.
- Parameters:
pos_1 – Coordinate tuples for both points.
pos_2 – Coordinate tuples for both points.
- get_distance(pos_1: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]], pos_2: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]]) float[source]#
Get the distance between two point, accounting for toroidal space.
- Parameters:
pos_1 – Coordinate tuples for point1.
pos_2 – Coordinate tuples for point2.
- torus_adj(pos: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]]) tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]][source]#
Adjust coordinates to handle torus looping.
If the coordinate is out-of-bounds and the space is toroidal, return the corresponding point within the space. If the space is not toroidal, raise an exception.
- Parameters:
pos – Coordinate tuple to convert.
- class NetworkGrid(g: Any)[source]#
Bases:
objectNetwork Grid where each node contains zero or more agents.
Create a new network.
- Parameters:
g – a NetworkX graph instance.
- get_neighborhood(node_id: int, include_center: bool = False, radius: int = 1) list[int][source]#
Get all adjacent nodes within a certain radius.
- Parameters:
node_id – node id for which to get neighborhood
include_center – boolean to include node itself or not
radius – size of neighborhood
- Returns:
a list
- get_neighbors(node_id: int, include_center: bool = False, radius: int = 1) list[Agent][source]#
Get all agents in adjacent nodes (within a certain radius).
- Parameters:
node_id – node id for which to get neighbors
include_center – whether to include node itself or not
radius – size of neighborhood in which to find neighbors
- Returns:
list of agents in neighborhood.
- move_agent(agent: Agent, node_id: int) None[source]#
Move an agent from its current node to a new node.
- Parameters:
agent – agent instance
node_id – id of node
- remove_agent(agent: Agent) None[source]#
Remove the agent from the network and set its pos attribute to None.
- Parameters:
agent – agent instance
- is_cell_empty(node_id: int) bool[source]#
Returns a bool of the contents of a cell.
- Parameters:
node_id – id of node
- get_cell_list_contents(cell_list: list[int]) list[Agent][source]#
Returns a list of the agents contained in the nodes identified in cell_list.
Nodes with empty content are excluded.
- Parameters:
cell_list – list of cell ids.
- Returns:
list of the agents contained in the nodes identified in cell_list.
- iter_cell_list_contents(cell_list: list[int]) Iterator[Agent][source]#
Returns an iterator of the agents contained in the nodes identified in cell_list.
Nodes with empty content are excluded.
- Parameters:
cell_list – list of cell ids.
- Returns:
iterator of the agents contained in the nodes identified in cell_list.
Module contents#
Mesa Agent-Based Modeling Framework.
Core Objects: Model, and Agent.
- class Agent(model: M, *args, **kwargs)[source]#
Bases:
GenericBase class for a model agent in Mesa.
- pos#
A reference to the position where this agent is located.
- Type:
Position
Notes
Agents must be hashable to be used in an AgentSet. In Python 3, defining __eq__ without __hash__ makes an object unhashable, which will break AgentSet usage. unique_id is unique relative to a model instance and starts from 1
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() None[source]#
Remove and delete the agent from the model.
Notes
If you need to do additional cleanup when removing an agent by for example removing it from a space, consider extending this method in your own agent class.
- classmethod create_agents(model: Model, n: int, *args, **kwargs) AgentSet[T][source]#
Create N agents.
- Parameters:
model – the model to which the agents belong
args – arguments to pass onto agent instances each arg is either a single object or a sequence of length n
n – the number of agents to create
kwargs – keyword arguments to pass onto agent instances each keyword arg is either a single object or a sequence of length n
- Returns:
AgentSet containing the agents created.
- classmethod from_dataframe(model: Model, df: pd.DataFrame, **kwargs) AgentSet[T][source]#
Create agents from a pandas DataFrame.
Each row of the DataFrame represents one agent. The DataFrame columns are mapped to the agent’s constructor as keyword arguments. Additional keyword arguments (**kwargs) can be used to set constant attributes for all agents.
- Parameters:
model – The model instance.
df – The pandas DataFrame. Each row represents an agent.
**kwargs – Constant values to pass to every agent’s constructor. Only non-sequence data is allowed in kwargs to avoid ambiguity with DataFrame columns.
- Returns:
AgentSet containing the agents created.
Note
If you need to pass variable data or sequences, add them as columns to the DataFrame before calling this method.
- property rng: Generator#
Return a seeded np.random rng.
- property scenario#
Return the scenario associated with the model.
- class DataCollector(model_reporters=None, agent_reporters=None, agenttype_reporters=None, tables=None)[source]#
Bases:
objectClass for collecting data generated by a Mesa model.
A DataCollector is instantiated with dictionaries of names of model-, agent-, and agent-type-level variables to collect, associated with attribute names or functions which actually collect them. When the collect(…) method is called, it collects these attributes and executes these functions one by one and stores the results.
Instantiate a DataCollector with lists of model, agent, and agent-type reporters.
Both model_reporters, agent_reporters, and agenttype_reporters accept a dictionary mapping a variable name to either an attribute name, a function, a method of a class/instance, a partial function, or a function with parameters placed in a list.
Model reporters can take five types of arguments: 1. Lambda function:
{“agent_count”: lambda m: len(m.agents)}
Method of a class/instance: {“agent_count”: self.get_agent_count} # self here is a class instance {“agent_count”: Model.get_agent_count} # Model here is a class
Class attributes of a model: {“model_attribute”: “model_attribute”}
Partial function: {“agent_count”: functools.partial(count_agents, multiplier=2)}
Functions with parameters that have been placed in a list: {“Model_Function”: [function, [param_1, param_2]]}
Agent reporters can similarly take: 1. Attribute name (string) referring to agent’s attribute:
{“energy”: “energy”}
Lambda function: {“energy”: lambda a: a.energy}
Method of an agent class/instance: {“agent_action”: self.do_action} # self here is an agent class instance {“agent_action”: Agent.do_action} # Agent here is a class
Partial function: {“energy”: functools.partial(get_energy, scale=2)}
Functions with parameters placed in a list: {“Agent_Function”: [function, [param_1, param_2]]}
Agenttype reporters take a dictionary mapping agent types to dictionaries of reporter names and attributes/funcs/methods, similar to agent_reporters:
{Wolf: {“energy”: lambda a: a.energy}}
The tables arg accepts a dictionary mapping names of tables to lists of columns. For example, if we want to allow agents to write their age when they are destroyed (to keep track of lifespans), it might look like:
{“Lifespan”: [“unique_id”, “age”]}
- Parameters:
model_reporters – Dictionary of reporter names and attributes/funcs/methods.
agent_reporters – Dictionary of reporter names and attributes/funcs/methods.
agenttype_reporters – Dictionary of agent types to dictionaries of reporter names and attributes/funcs/methods.
tables – Dictionary of table names to lists of column names.
Notes
If you want to pickle your model you must not use lambda functions.
If your model includes a large number of agents, it is recommended to use attribute names for the agent reporter, as it will be faster.
- add_table_row(table_name, row, ignore_missing=False)[source]#
Add a row dictionary to a specific table.
- Parameters:
table_name – Name of the table to append a row to.
row – A dictionary of the form {column_name: value…}
ignore_missing – If True, fill any missing columns with Nones; if False, throw an error if any columns are missing
- get_model_vars_dataframe()[source]#
Create a pandas DataFrame from the model variables.
The DataFrame has one column for each model variable, and the index is (implicitly) the model tick.
- get_agent_vars_dataframe()[source]#
Create a pandas DataFrame from the agent variables.
The DataFrame has one column for each variable, with two additional columns for tick and agent_id.
- class Model(*args: Any, seed: float | None = None, rng: RNGLike | SeedLike | None = None, scenario: S | None = None, **kwargs: Any)[source]#
Bases:
HasObservables,GenericBase class for models in the Mesa ABM library.
This class serves as a foundational structure for creating agent-based models. It includes the basic attributes and methods necessary for initializing and running a simulation model.
- Type Parameters:
A: The agent type used in this model S: The scenario type used in this model
- time#
the current simulation time. Automatically increments by 1.0 with each step unless controlled by a discrete event simulator.
- Type:
- random#
a seeded python.random number generator.
- rng#
a seeded numpy.random.Generator
- Type:
np.random.Generator
- scenario#
the scenario instance containing model parameters
Notes
Model.agents returns the AgentSet containing all agents registered with the model. Changing the content of the AgentSet directly can result in strange behavior. If you want change the composition of this AgentSet, ensure you operate on a copy.
Create a new model.
Overload this method with the actual code to initialize the model. Always start with super().__init__() to initialize the model object properly.
- Parameters:
args – arguments to pass onto super
seed – the seed for the random number generator
rng – Pseudorandom number generator state. When rng is None, a new numpy.random.Generator is created using entropy from the operating system. Types other than numpy.random.Generator are passed to numpy.random.default_rng to instantiate a Generator.
scenario – the scenario specifying the computational experiment to run
kwargs – keyword arguments to pass onto super
Notes
you have to pass either seed or rng, but not both.
- time: float#
Observable descriptor.
An observable is an attribute that emits ObservableSignals.CHANGED whenever it is changed to a different value.
- rng: np.random.Generator#
- property scenario: S#
Return scenario instance.
- property agents: _HardKeyAgentSet[A]#
Provides a _HardKeyAgentSet of all agents in the model, combining agents from all types.
- Returns:
The agent set containing all agents with strong references.
- Return type:
_HardKeyAgentSet
Warning
This returns the actual internal _HardKeyAgentSet used by Mesa for agent registration and tracking. It uses strong references to prevent premature garbage collection and reduce performance overhead caused by weak reference management.
Do not modify this AgentSet directly (e.g., by adding or removing agents manually). Direct modifications can break the model’s agent tracking system and cause unexpected behavior. Instead:
Use
Agent()to create new agents (automatically registers them)Use
agent.remove()to remove agents (automatically deregisters them)For read-only operations or transformations, work on a copy:
model.agents.copy()
Notes
This is Mesa’s core agent registration system. All agents created via
Agent.__init__are automatically registered here.
- property agent_types: list[type]#
Return a list of all unique agent types registered with the model.
- property agents_by_type: dict[type[A], _HardKeyAgentSet[A]]#
A dictionary where keys are agent types and values are the corresponding _HardKeyAgentSets.
- Returns:
Dictionary mapping agent types to their AgentSets.
- Return type:
Warning
Each AgentSet in this dictionary is a _HardKeyAgentSet with strong references, forming part of Mesa’s core agent registration system.
Do not modify these AgentSets directly. Direct modifications can break agent tracking and cause unexpected behavior. Instead:
Use
Agent()to create new agents (automatically registers them)Use
agent.remove()to remove agents (automatically deregisters them)For read-only operations, work on copies:
model.agents_by_type[AgentType].copy()
Notes
This is part of Mesa’s core agent registration system. All agents are automatically registered in the appropriate type-specific AgentSet when created via
Agent.__init__.
- register_agent(agent: A)[source]#
Register the agent with the model.
- Parameters:
agent – The agent to register.
Notes
This method is called automatically by
Agent.__init__, so there is no need to use this if you are subclassing Agent and calling its super in the__init__method.
- deregister_agent(agent: A)[source]#
Deregister the agent with the model.
- Parameters:
agent – The agent to deregister.
Notes
This method is called automatically by
Agent.remove
- observables = {'agents': frozenset({ModelSignals.AGENT_ADDED, ModelSignals.AGENT_REMOVED}), 'time': <enum 'ObservableSignals'>}#
- reset_randomizer(seed: int | None = None) None[source]#
Reset the model random number generator.
- Parameters:
seed – A new seed for the RNG; if None, reset using the current seed
- reset_rng(rng: Generator | BitGenerator | int | integer | Sequence[int] | SeedSequence | None = None) None[source]#
Reset the model random number generator.
- Parameters:
rng – A new seed for the RNG; if None, reset using the current seed
- remove_all_agents()[source]#
Remove all agents from the model.
Notes
This method calls agent.remove for all agents in the model. If you need to remove agents from e.g., a SingleGrid, you can either explicitly implement your own agent.remove method or clean this up near where you are calling this method.
- schedule_event(function: Callable, *, at: float | None = None, after: float | None = None, priority: Priority = Priority.DEFAULT) Event[source]#
Schedule a one-off event.
- Parameters:
function – The callable to execute
at – Absolute time to execute (mutually exclusive with after)
after – Relative time from now to execute (mutually exclusive with at)
priority – Priority level for the event
- Returns:
The scheduled Event (can be used to cancel)
- Raises:
ValueError – If both or neither of at/after are specified
ValueError – If both or neither of at/after are specified, or if the scheduled time is in the past.
- schedule_recurring(function: Callable, schedule: Schedule, priority: Priority = Priority.DEFAULT) EventGenerator[source]#
Schedule a recurring event based on a Schedule.
- Parameters:
function – The callable to execute repeatedly
schedule – The Schedule defining when events occur
priority – Priority level for generated events
- Returns:
The EventGenerator (can be used to stop)
- Raises:
ValueError – If the schedule start time is in the past.
- batch_run(model_cls: type[Model], parameters: Mapping[str, Any | Iterable[Any]], number_processes: int | None = 1, iterations: int | None = None, data_collection_period: int = -1, max_steps: int = 1000, display_progress: bool = True, rng: int | integer | Sequence[int] | SeedSequence | Iterable[int | integer | Sequence[int] | SeedSequence] | None = None) list[dict[str, Any]][source]#
Batch run a mesa model with a set of parameter values.
- Parameters:
model_cls (Type[Model]) – The model class to batch-run
parameters (Mapping[str, Union[Any, Iterable[Any]]]) – Dictionary with model parameters over which to run the model. You can either pass single values or iterables.
number_processes (int, optional) – Number of processes used, by default 1. Set this to None if you want to use all CPUs.
iterations (int, optional) – Number of iterations for each parameter combination, by default 1
data_collection_period (int, optional) – Number of steps after which data gets collected, by default -1 (end of episode)
max_steps (int, optional) – Maximum number of model steps after which the model halts, by default 1000
display_progress (bool, optional) – Display batch run process, by default True
rng – a valid value or iterable of values for seeding the random number generator in the model
- Returns:
List[Dict[str, Any]]
Notes
batch_run assumes the model has a datacollector attribute that has a DataCollector object initialized.