mesa package¶
Subpackages¶
- mesa.visualization package
- Subpackages
- mesa.visualization.modules package
- Submodules
- mesa.visualization.modules.BarChartVisualization module
- mesa.visualization.modules.CanvasGridVisualization module
- mesa.visualization.modules.ChartVisualization module
- mesa.visualization.modules.HexGridVisualization module
- mesa.visualization.modules.NetworkVisualization module
- mesa.visualization.modules.PieChartVisualization module
- mesa.visualization.modules.TextVisualization module
- Module contents
- mesa.visualization.modules package
- Submodules
- mesa.visualization.ModularVisualization module
- mesa.visualization.TextVisualization module
- mesa.visualization.UserParam module
- Module contents
- Subpackages
Submodules¶
mesa.agent module¶
The agent class for Mesa framework.
Core Objects: Agent
mesa.batchrunner module¶
Batchrunner¶
A single class to manage a batch run or parameter sweep of a given model.
- batch_run(model_cls: Type[Model], parameters: Mapping[str, Union[Any, Iterable[Any]]], number_processes: Optional[int] = 1, iterations: int = 1, data_collection_period: int = -1, max_steps: int = 1000, display_progress: bool = True) List[Dict[str, Any]] [source]¶
Batch run a mesa model with a set of parameter values.
Parameters¶
- model_clsType[Model]
The model class to batch-run
- parametersMapping[str, Union[Any, Iterable[Any]]],
Dictionary with model parameters over which to run the model. You can either pass single values or iterables.
- number_processesint, optional
Number of processes used, by default 1. Set this to None if you want to use all CPUs.
- iterationsint, optional
Number of iterations for each parameter combination, by default 1
- data_collection_periodint, optional
Number of steps after which data gets collected, by default -1 (end of episode)
- max_stepsint, optional
Maximum number of model steps after which the model halts, by default 1000
- display_progressbool, optional
Display batch run process, by default True
Returns¶
- List[Dict[str, Any]]
[description]
- exception ParameterError(bad_names)[source]¶
Bases:
TypeError
- MESSAGE = 'Parameters must map a name to a value. These names did not match parameters: {}'¶
- exception VariableParameterError(bad_names)[source]¶
Bases:
ParameterError
- MESSAGE = 'Variable_parameters must map a name to a sequence of values. These parameters were given with non-sequence values: {}'¶
- class FixedBatchRunner(model_cls, parameters_list=None, fixed_parameters=None, iterations=1, max_steps=1000, model_reporters=None, agent_reporters=None, display_progress=True)[source]¶
Bases:
object
This class is instantiated with a model class, and model parameters associated with one or more values. It is also instantiated with model and agent-level reporters, dictionaries mapping a variable name to a function which collects some data from the model or its agents at the end of the run and stores it.
Note that by default, the reporters only collect data at the end of the run. To get step by step data, simply have a reporter store the model’s entire DataCollector object.
Create a new BatchRunner for a given model with the given parameters.
- Args:
model_cls: The class of model to batch-run. parameters_list: A list of dictionaries of parameter sets.
The model will be run with dictionary of parameters. For example, given parameters_list of
[{“homophily”: 3, “density”: 0.8, “minority_pc”: 0.2}, {“homophily”: 2, “density”: 0.9, “minority_pc”: 0.1}, {“homophily”: 4, “density”: 0.6, “minority_pc”: 0.5}]
3 models will be run, one for each provided set of parameters.
- fixed_parameters: Dictionary of parameters that stay same through
- all batch runs. For example, given fixed_parameters of
{“constant_parameter”: 3},
every instantiated model will be passed constant_parameter=3 as a kwarg.
- iterations: The total number of times to run the model for each set
of parameters.
- max_steps: Upper limit of steps above which each run will be halted
if it hasn’t halted on its own.
- model_reporters: The dictionary of variables to collect on each run
at the end, with variable names mapped to a function to collect them. For example:
{“agent_count”: lambda m: m.schedule.get_agent_count()}
- agent_reporters: Like model_reporters, but each variable is now
collected at the level of each agent present in the model at the end of the run.
display_progress: Display progress bar with time estimation?
- run_model(model)[source]¶
Run a model object to completion, or until reaching max steps.
If your model runs in a non-standard way, this is the method to modify in your subclass.
- get_model_vars_dataframe()[source]¶
Generate a pandas DataFrame from the model-level variables collected.
- get_agent_vars_dataframe()[source]¶
Generate a pandas DataFrame from the agent-level variables collected.
- class BatchRunner(model_cls, variable_parameters=None, fixed_parameters=None, iterations=1, max_steps=1000, model_reporters=None, agent_reporters=None, display_progress=True)[source]¶
Bases:
FixedBatchRunner
DEPRECATION WARNING: BatchRunner Class has been replaced batch_run function This class is instantiated with a model class, and model parameters associated with one or more values. It is also instantiated with model and agent-level reporters, dictionaries mapping a variable name to a function which collects some data from the model or its agents at the end of the run and stores it.
Note that by default, the reporters only collect data at the end of the run. To get step by step data, simply have a reporter store the model’s entire DataCollector object.
Create a new BatchRunner for a given model with the given parameters.
- Args:
model_cls: The class of model to batch-run. variable_parameters: Dictionary of parameters to lists of values.
The model will be run with every combo of these parameters. For example, given variable_parameters of
- {“param_1”: range(5),
“param_2”: [1, 5, 10]}
- models will be run with {param_1=1, param_2=1},
{param_1=2, param_2=1}, …, {param_1=4, param_2=10}.
- fixed_parameters: Dictionary of parameters that stay same through
- all batch runs. For example, given fixed_parameters of
{“constant_parameter”: 3},
every instantiated model will be passed constant_parameter=3 as a kwarg.
- iterations: The total number of times to run the model for each
combination of parameters.
- max_steps: Upper limit of steps above which each run will be halted
if it hasn’t halted on its own.
- model_reporters: The dictionary of variables to collect on each run
at the end, with variable names mapped to a function to collect them. For example:
{“agent_count”: lambda m: m.schedule.get_agent_count()}
- agent_reporters: Like model_reporters, but each variable is now
collected at the level of each agent present in the model at the end of the run.
display_progress: Display progress bar with time estimation?
- class BatchRunnerMP(model_cls, nr_processes=None, **kwargs)[source]¶
Bases:
BatchRunner
DEPRECATION WARNING: BatchRunner class has been replaced by batch_run Child class of BatchRunner, extended with multiprocessing support.
Create a new BatchRunnerMP for a given model with the given parameters.
model_cls: The class of model to batch-run. nr_processes: int
the number of separate processes the BatchRunner should start, all running in parallel.
kwargs: the kwargs required for the parent BatchRunner class
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 three types of data: model-level data, agent-level data, and tables.
A DataCollector is instantiated with two dictionaries of reporter names and associated variable names or functions for each, one for model-level data and one for agent-level data; a third 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 in the model scheduler.
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 agents id and its values.
Finally, DataCollector can create a pandas DataFrame from each collection.
- The default DataCollector here makes several assumptions:
The model has a schedule object called ‘schedule’
The schedule has an agent list called agents
For collecting agent-level variables, agents must have a unique_id
- class DataCollector(model_reporters=None, agent_reporters=None, tables=None)[source]¶
Bases:
object
Class for collecting data generated by a Mesa model.
A DataCollector is instantiated with dictionaries of names of model- and agent-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 and agent reporters. Both model_reporters and agent_reporters accept a dictionary mapping a variable name to either an attribute name, or a method. For example, if there was only one model-level reporter for number of agents, it might look like:
{“agent_count”: lambda m: m.schedule.get_agent_count() }
If there was only one agent-level reporter (e.g. the agent’s energy), it might look like this:
{“energy”: “energy”}
- or like this:
{“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”]}
- Args:
model_reporters: Dictionary of reporter names and attributes/funcs agent_reporters: Dictionary of reporter names and attributes/funcs. 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, you should only use attribute names for the agent reporter, it will be much faster.
Model reporters can take four types of arguments: lambda like above: {“agent_count”: lambda m: m.schedule.get_agent_count() } method with @property decorators {“agent_count”: schedule.get_agent_count() class attributes of model {“model_attribute”: “model_attribute”} functions with parameters that have placed in a list {“Model_Function”:[function, [param_1, param_2]]}
- add_table_row(table_name, row, ignore_missing=False)[source]¶
Add a row dictionary to a specific table.
- Args:
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.
mesa.main module¶
mesa.model module¶
The model class for Mesa framework.
Core Objects: Model
- class Model(*args: Any, **kwargs: Any)[source]¶
Bases:
object
Base class for models.
Create a new model. Overload this method with the actual code to start the model.
- Attributes:
schedule: schedule object running: a bool indicating if the model should continue running
mesa.space module¶
Mesa Space Module¶
Objects used to add a spatial component to a model.
Grid: base grid, which creates a rectangular grid. SingleGrid: extension to Grid which strictly enforces one agent per cell. MultiGrid: extension to Grid where each cell can contain a set of agents. HexGrid: extension to 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, by automatically wrapping tuple in single-item list rather than forcing user to do it.
- class Grid(width: int, height: int, torus: bool)[source]¶
Bases:
object
Base class for a rectangular grid.
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
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus. grid: Internal list-of-lists which holds the grid cells themselves.
Create a new grid.
- Args:
width, height: The width and height of the grid torus: Boolean whether the grid wraps or not.
- coord_iter() Iterator[tuple[GridContent, int, int]] [source]¶
An iterator that returns coordinates as well as cell contents.
- neighbor_iter(pos: Tuple[int, int], moore: bool = True) Iterator[Agent] [source]¶
Iterate over position neighbors.
- Args:
pos: (x,y) coords tuple for the position to get the neighbors of. moore: Boolean for whether to use Moore neighborhood (including
diagonals) or Von Neumann (only up/down/left/right).
- iter_neighborhood(pos: Tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) Iterator[Tuple[int, int]] [source]¶
Return an iterator over cell coordinates that are in the neighborhood of a certain point.
- Args:
pos: Coordinate tuple 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 coordinate tuples representing the neighborhood. For example with radius 1, it will return list with number of elements equals at most 9 (8) if Moore, 5 (4) if Von Neumann (if not including the center).
- get_neighborhood(pos: Coordinate, moore: bool, include_center: bool = False, radius: int = 1) list[Coordinate] [source]¶
Return a list of cells that are in the neighborhood of a certain point.
- Args:
pos: Coordinate tuple 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:
A list of coordinate tuples representing the neighborhood; With radius 1, at most 9 if Moore, 5 if Von Neumann (8 and 4 if not including the center).
- 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.
- Args:
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).
- get_neighbors(pos: Coordinate, moore: bool, include_center: bool = False, radius: int = 1) list[Agent] [source]¶
Return a list of neighbors to a certain point.
- Args:
pos: Coordinate tuple 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:
A list 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).
- torus_adj(pos: Tuple[int, int]) Tuple[int, int] [source]¶
Convert coordinate, handling torus looping.
- out_of_bounds(pos: Tuple[int, int]) bool [source]¶
Determines whether position is off the grid, returns the out of bounds coordinate.
- move_agent(agent: Agent, pos: Tuple[int, int]) None [source]¶
Move an agent from its current position to a new position.
- Args:
- agent: Agent object to move. Assumed to have its current location
stored in a ‘pos’ tuple.
pos: Tuple of new position to move the agent to.
- place_agent(agent: Agent, pos: Tuple[int, int]) None [source]¶
Place the agent at the specified location, and set its pos variable.
- remove_agent(agent: Agent) None [source]¶
Remove the agent from the grid and set its pos attribute to None.
- class SingleGrid(width: int, height: int, torus: bool)[source]¶
Bases:
Grid
Grid where each cell contains exactly at most one object.
Create a new grid.
- Args:
width, height: The width and height of the grid torus: Boolean whether the grid wraps or not.
- position_agent(agent: Agent, x: int | str = 'random', y: int | str = 'random') None [source]¶
Position an agent on the grid. This is used when first placing agents! Setting either x or y to “random” gives the same behavior as ‘move_to_empty()’ to get a random position. If x or y are positive, they are used. Use ‘swap_pos()’ to swap agents positions.
- class MultiGrid(width: int, height: int, torus: bool)[source]¶
Bases:
Grid
Grid where each cell can contain more than one object.
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.
Each grid cell holds a set object.
- Properties:
width, height: The grid’s width and height.
torus: Boolean which determines whether to treat the grid as a torus.
grid: Internal list-of-lists which holds the grid cells themselves.
- Methods:
get_neighbors: Returns the objects surrounding a given cell.
Create a new grid.
- Args:
width, height: The width and height of the grid torus: Boolean whether the grid wraps or not.
- place_agent(agent: Agent, pos: Tuple[int, int]) None [source]¶
Place the agent at the specified location, and set its pos variable.
- class HexGrid(width: int, height: int, torus: bool)[source]¶
Bases:
Grid
Hexagonal Grid: Extends Grid to handle hexagonal neighbors.
Functions according to odd-q rules. See http://www.redblobgames.com/grids/hexagons/#coordinates for more.
- Properties:
width, height: The grid’s width and height. torus: Boolean which determines whether to treat the grid as a torus.
- Methods:
get_neighbors: Returns the objects surrounding a given cell. get_neighborhood: Returns the cells surrounding a given cell. iter_neighbors: Iterates over position neighbors. iter_neighborhood: Returns an iterator over cell coordinates that are
in the neighborhood of a certain point.
Create a new grid.
- Args:
width, height: The width and height of the grid torus: Boolean whether the grid wraps or not.
- get_neighborhood(pos: Coordinate, include_center: bool = False, radius: int = 1) list[Coordinate] [source]¶
Return a list of coordinates that are in the neighborhood of a certain point. To calculate the neighborhood for a HexGrid the parity of the x coordinate of the point is important, the neighborhood can be sketched as:
Always: (0,-), (0,+) When x is even: (-,+), (-,0), (+,+), (+,0) When x is odd: (-,0), (-,-), (+,0), (+,-)
- Args:
pos: Coordinate tuple for the neighborhood to get. 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:
A list of coordinate tuples representing the neighborhood. For example with radius 1, it will return list with number of elements equals at most 9 (8) if Moore, 5 (4) if Von Neumann (if not including the center).
- neighbor_iter(pos: Tuple[int, int]) Iterator[Agent] [source]¶
Iterate over position neighbors.
- Args:
pos: (x,y) coords tuple for the position to get the neighbors of.
- iter_neighborhood(pos: Tuple[int, int], include_center: bool = False, radius: int = 1) Iterator[Tuple[int, int]] [source]¶
Return an iterator over cell coordinates that are in the neighborhood of a certain point.
- Args:
pos: Coordinate tuple for the neighborhood to get. 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 coordinate tuples representing the neighborhood.
- iter_neighbors(pos: Tuple[int, int], include_center: bool = False, radius: int = 1) Iterator[Agent] [source]¶
Return an iterator over neighbors to a certain point.
- Args:
pos: Coordinates for the neighborhood to get. 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
- get_neighbors(pos: Coordinate, include_center: bool = False, radius: int = 1) list[Agent] [source]¶
Return a list of neighbors to a certain point.
- Args:
pos: Coordinate tuple for the neighborhood to get. 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:
A list of non-None objects in the given neighborhood
- class ContinuousSpace(x_max: float, y_max: float, torus: bool, x_min: float = 0, y_min: float = 0)[source]¶
Bases:
object
Continuous 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.
Create a new continuous space.
- Args:
x_max, y_max: Maximum x and y coordinates for the space. torus: Boolean for whether the edges loop around. x_min, y_min: (default 0) If provided, set the minimum x and y
coordinates for the space. Below them, values loop to the other edge (if torus=True) or raise an exception.
- place_agent(agent: Agent, pos: Union[Tuple[float, float], ndarray[Any, dtype[float]]]) None [source]¶
Place a new agent in the space.
- Args:
agent: Agent object to place. pos: Coordinate tuple for where to place the agent.
- move_agent(agent: Agent, pos: Union[Tuple[float, float], ndarray[Any, dtype[float]]]) None [source]¶
Move an agent from its current position to a new position.
- Args:
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.
- Args:
agent: The agent object to remove
- get_neighbors(pos: FloatCoordinate, radius: float, include_center: bool = True) list[Agent] [source]¶
Get all agents within a certain radius.
- Args:
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.
- get_heading(pos_1: Union[Tuple[float, float], ndarray[Any, dtype[float]]], pos_2: Union[Tuple[float, float], ndarray[Any, dtype[float]]]) Union[Tuple[float, float], ndarray[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.
- Args:
pos_1, pos_2: Coordinate tuples for both points.
- get_distance(pos_1: Union[Tuple[float, float], ndarray[Any, dtype[float]]], pos_2: Union[Tuple[float, float], ndarray[Any, dtype[float]]]) float [source]¶
Get the distance between two point, accounting for toroidal space.
- Args:
pos_1, pos_2: Coordinate tuples for both points.
- torus_adj(pos: Union[Tuple[float, float], ndarray[Any, dtype[float]]]) Union[Tuple[float, float], ndarray[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.
- Args:
pos: Coordinate tuple to convert.
- class NetworkGrid(G: Any)[source]¶
Bases:
object
Network Grid where each node contains zero or more agents.
Create a new network.
- Args:
G: a NetworkX graph instance.
- get_neighbors(node_id: int, include_center: bool = False) list[int] [source]¶
Get all adjacent nodes
- move_agent(agent: Agent, node_id: int) None [source]¶
Move an agent from its current node to a new node.
- remove_agent(agent: Agent) None [source]¶
Remove the agent from the network and set its pos attribute to None.
mesa.time module¶
Mesa Time Module¶
Objects for handling the time component of a model. In particular, this module contains Schedulers, which handle agent activation. A Scheduler is an object which controls when agents are called upon to act, and when.
The activation order can have a serious impact on model behavior, so it’s important to specify it explicitly. Example simple activation regimes include activating all agents in the same order every step, shuffling the activation order every time, activating each agent on average once per step, and more.
- Key concepts:
Step: Many models advance in ‘steps’. A step may involve the activation of all agents, or a random (or selected) subset of them. Each agent in turn may have their own step() method.
Time: Some models may simulate a continuous ‘clock’ instead of discrete steps. However, by default, the Time is equal to the number of steps the model has taken.
- class BaseScheduler(model: Model)[source]¶
Bases:
object
Simplest scheduler; activates agents one at a time, in the order they were added.
Assumes that each agent added has a step method which takes no arguments.
(This is explicitly meant to replicate the scheduler in MASON).
Create a new, empty BaseScheduler.
- add(agent: Agent) None [source]¶
Add an Agent object to the schedule.
- Args:
agent: An Agent to be added to the schedule. NOTE: The agent must have a step() method.
- class RandomActivation(model: Model)[source]¶
Bases:
BaseScheduler
A scheduler which activates each agent once per step, in random order, with the order reshuffled every step.
This is equivalent to the NetLogo ‘ask agents…’ and is generally the default behavior for an ABM.
Assumes that all agents have a step(model) method.
Create a new, empty BaseScheduler.
- class SimultaneousActivation(model: Model)[source]¶
Bases:
BaseScheduler
A scheduler to simulate the simultaneous activation of all the agents.
This scheduler requires that each agent have two methods: step and advance. step() activates the agent and stages any necessary changes, but does not apply them yet. advance() then applies the changes.
Create a new, empty BaseScheduler.
- class StagedActivation(model: Model, stage_list: list[str] | None = None, shuffle: bool = False, shuffle_between_stages: bool = False)[source]¶
Bases:
BaseScheduler
A scheduler which allows agent activation to be divided into several stages instead of a single step method. All agents execute one stage before moving on to the next.
Agents must have all the stage methods implemented. Stage methods take a model object as their only argument.
This schedule tracks steps and time separately. Time advances in fractional increments of 1 / (# of stages), meaning that 1 step = 1 unit of time.
Create an empty Staged Activation schedule.
- Args:
model: Model object associated with the schedule. stage_list: List of strings of names of stages to run, in the
order to run them in.
shuffle: If True, shuffle the order of agents each step. shuffle_between_stages: If True, shuffle the agents after each
stage; otherwise, only shuffle at the start of each step.
- class RandomActivationByType(model: Model)[source]¶
Bases:
BaseScheduler
A scheduler which activates each type of agent once per step, in random order, with the order reshuffled every step.
The step_type method is equivalent to the NetLogo ‘ask [breed]…’ and is generally the default behavior for an ABM. The step method performs step_type for each of the agent types.
Assumes that all agents have a step() method.
This implementation assumes that the type of an agent doesn’t change throughout the simulation.
If you want to do some computations / data collections specific to an agent type, you can either: - loop through all agents, and filter by their type - access via your_model.scheduler.agents_by_type[your_type_class]
Create a new, empty BaseScheduler.
- add(agent: Agent) None [source]¶
Add an Agent object to the schedule
- Args:
agent: An Agent to be added to the schedule.
- step(shuffle_types: bool = True, shuffle_agents: bool = True) None [source]¶
Executes the step of each agent type, one at a time, in random order.
- Args:
- shuffle_types: If True, the order of execution of each types is
shuffled.
- shuffle_agents: If True, the order of execution of each agents in a
type group is shuffled.
Module contents¶
Mesa Agent-Based Modeling Framework
Core Objects: Model, and Agent.
- class Model(*args: Any, **kwargs: Any)[source]¶
Bases:
object
Base class for models.
Create a new model. Overload this method with the actual code to start the model.
- Attributes:
schedule: schedule object running: a bool indicating if the model should continue running
- class Agent(unique_id: int, model: Model)[source]¶
Bases:
object
Base class for a model agent.
Create a new agent.
- Args:
unique_id (int): A unique numeric identified for the agent model: (Model): Instance of the model that contains the agent
- class DataCollector(model_reporters=None, agent_reporters=None, tables=None)[source]¶
Bases:
object
Class for collecting data generated by a Mesa model.
A DataCollector is instantiated with dictionaries of names of model- and agent-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 and agent reporters. Both model_reporters and agent_reporters accept a dictionary mapping a variable name to either an attribute name, or a method. For example, if there was only one model-level reporter for number of agents, it might look like:
{“agent_count”: lambda m: m.schedule.get_agent_count() }
If there was only one agent-level reporter (e.g. the agent’s energy), it might look like this:
{“energy”: “energy”}
- or like this:
{“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”]}
- Args:
model_reporters: Dictionary of reporter names and attributes/funcs agent_reporters: Dictionary of reporter names and attributes/funcs. 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, you should only use attribute names for the agent reporter, it will be much faster.
Model reporters can take four types of arguments: lambda like above: {“agent_count”: lambda m: m.schedule.get_agent_count() } method with @property decorators {“agent_count”: schedule.get_agent_count() class attributes of model {“model_attribute”: “model_attribute”} functions with parameters that have placed in a list {“Model_Function”:[function, [param_1, param_2]]}
- add_table_row(table_name, row, ignore_missing=False)[source]¶
Add a row dictionary to a specific table.
- Args:
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.
- batch_run(model_cls: Type[Model], parameters: Mapping[str, Union[Any, Iterable[Any]]], number_processes: Optional[int] = 1, iterations: int = 1, data_collection_period: int = -1, max_steps: int = 1000, display_progress: bool = True) List[Dict[str, Any]] [source]¶
Batch run a mesa model with a set of parameter values.
Parameters¶
- model_clsType[Model]
The model class to batch-run
- parametersMapping[str, Union[Any, Iterable[Any]]],
Dictionary with model parameters over which to run the model. You can either pass single values or iterables.
- number_processesint, optional
Number of processes used, by default 1. Set this to None if you want to use all CPUs.
- iterationsint, optional
Number of iterations for each parameter combination, by default 1
- data_collection_periodint, optional
Number of steps after which data gets collected, by default -1 (end of episode)
- max_stepsint, optional
Maximum number of model steps after which the model halts, by default 1000
- display_progressbool, optional
Display batch run process, by default True
Returns¶
- List[Dict[str, Any]]
[description]