Visualization#

For detailed tutorials, please refer to:

Jupyter Visualization#

Mesa visualization module for creating interactive model visualizations.

This module provides components to create browser- and Jupyter notebook-based visualizations of Mesa models, allowing users to watch models run step-by-step and interact with model parameters.

Key features:
  • SolaraViz: Main component for creating visualizations, supporting grid displays and plots

  • ModelController: Handles model execution controls (step, play, pause, reset)

  • UserInputs: Generates UI elements for adjusting model parameters

The module uses Solara for rendering in Jupyter notebooks or as standalone web applications. It supports various types of visualizations including matplotlib plots, agent grids, and custom visualization components.

Usage:
  1. Define an agent_portrayal function to specify how agents should be displayed

  2. Set up model_params to define adjustable parameters

  3. Create a SolaraViz instance with your model, parameters, and desired measures

  4. Display the visualization in a Jupyter notebook or run as a Solara app

See the Visualization Tutorial and example models for more details.

create_space_component(renderer: SpaceRenderer)[source]#

Create a space visualization component for the given renderer.

split_model_params(model_params)[source]#

Split model parameters into user-adjustable and fixed parameters.

Parameters:

model_params – Dictionary of all model parameters

Returns:

(user_adjustable_params, fixed_params)

Return type:

tuple

check_param_is_fixed(param)[source]#

Check if a parameter is fixed (not user-adjustable).

Parameters:

param – Parameter to check

Returns:

True if parameter is fixed, False otherwise

Return type:

bool

make_initial_grid_layout(num_components)[source]#

Create an initial grid layout for visualization components.

Parameters:

num_components – Number of components to display

Returns:

Initial grid layout configuration

Return type:

list

copy_renderer(renderer: SpaceRenderer, model: Model)[source]#

Create a new renderer instance with the same configuration as the original.

Custom visualization components.

class AgentPortrayalStyle(x: float | None = None, y: float | None = None, color: str | tuple | int | float | None = 'tab:blue', marker: str | None = 'o', size: int | float | None = 50, zorder: int | None = 1, alpha: float | None = 1.0, edgecolors: str | tuple | None = None, linewidths: float | int | None = 1.0)[source]#

Bases: object

Represents the visual styling options for an agent in a visualization.

User facing component to control how agents are drawn. Allows specifying properties like color, size, marker shape, position, and other plot attributes.

x, y are determined automatically according to the agent’s type (normal/CellAgent) and position in the space if not manually declared.

Example

>>> def agent_portrayal(agent):
>>>     return AgentPortrayalStyle(
>>>         x=agent.cell.coordinate[0],
>>>         y=agent.cell.coordinate[1],
>>>         color="red",
>>>         marker="o",
>>>         size=20,
>>>         zorder=2,
>>>         alpha=0.8,
>>>         edgecolors="black",
>>>         linewidths=1.5
>>>     )
>>>
>>> # or for a default agent portrayal
>>> def agent_portrayal(agent):
>>>     return AgentPortrayalStyle()
alpha: float | None = 1.0#
color: str | tuple | int | float | None = 'tab:blue'#
edgecolors: str | tuple | None = None#
linewidths: float | int | None = 1.0#
marker: str | None = 'o'#
size: int | float | None = 50#
update(*updates_fields: tuple[str, Any])[source]#

Updates attributes from variable (field_name, new_value) tuple arguments.

Example

>>> def agent_portrayal(agent):
>>>     primary_style = AgentPortrayalStyle(color="blue", marker="^", size=10, x=agent.pos[0], y=agent.pos[1])
>>>     if agent.type == 1:
>>>         primary_style.update(("color", "red"), ("size", 30))
>>>     return primary_style
x: float | None = None#
y: float | None = None#
zorder: int | None = 1#
class PropertyLayerStyle(colormap: str | None = None, color: str | None = None, alpha: float = 0.8, colorbar: bool = True, vmin: float | None = None, vmax: float | None = None)[source]#

Bases: object

Represents the visual styling options for a property layer in a visualization.

User facing component to control how property layers are drawn. Allows specifying properties like colormap, single color, value limits (vmin, vmax), transparency (alpha) and colorbar visibility.

Note: vmin and vmax are the lower and upper bounds for the colorbar and the data is normalized between these values for color/colormap rendering. If they are not declared the values are automatically determined from the data range.

Note: You can specify either a ‘colormap’ (for varying data) or a single ‘color’ (for a uniform layer appearance), but not both simultaneously.

Example

>>> def propertylayer_portrayal(layer):
>>>     return PropertyLayerStyle(colormap="viridis", vmin=0, vmax=100, alpha=0.5, colorbar=True)
>>> # or for a uniform color layer
>>> def propertylayer_portrayal(layer):
>>>     return PropertyLayerStyle(color="lightblue", alpha=0.8, colorbar=False)
alpha: float = 0.8#
color: str | None = None#
colorbar: bool = True#
colormap: str | None = None#
vmax: float | None = None#
vmin: float | None = None#
make_altair_space(agent_portrayal, propertylayer_portrayal=None, post_process=None, **space_drawing_kwargs)[source]#

Create an Altair-based space visualization component.

Parameters:
  • agent_portrayal – Function to portray agents.

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • post_process – A user specified callable that will be called with the Chart instance from Altair. Allows for fine tuning plots (e.g., control ticks)

  • space_drawing_kwargs – not yet implemented

agent_portrayal is called with an agent and should return a dict. Valid fields in this dict are “color”, “size”, “marker”, and “zorder”. Other field are ignored and will result in a user warning.

Returns:

A function that creates a SpaceMatplotlib component

Return type:

function

make_mpl_plot_component(measure: str | dict[str, str] | list[str] | tuple[str], post_process: Callable | None = None, page: int = 0, save_format='png')[source]#

Create a plotting function for a specified measure.

Parameters:
  • measure (str | dict[str, str] | list[str] | tuple[str]) – Measure(s) to plot.

  • post_process – a user-specified callable to do post-processing called with the Axes instance.

  • page – Page number where the plot should be displayed.

  • save_format – save format of figure in solara backend

Returns:

A tuple of a function that creates a PlotMatplotlib component and a page number.

Return type:

(function, page)

make_mpl_space_component(agent_portrayal: Callable | None = None, propertylayer_portrayal: dict | None = None, post_process: Callable | None = None, **space_drawing_kwargs) SpaceMatplotlib[source]#

Create a Matplotlib-based space visualization component.

Parameters:
  • agent_portrayal – Function to portray agents.

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • post_process – a callable that will be called with the Axes instance. Allows for fine tuning plots (e.g., control ticks)

  • space_drawing_kwargs – additional keyword arguments to be passed on to the underlying space drawer function. See the functions for drawing the various spaces for further details.

agent_portrayal is called with an agent and should return a dict. Valid fields in this dict are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

Returns:

A function that creates a SpaceMatplotlib component

Return type:

function

make_plot_component(measure: str | dict[str, str] | list[str] | tuple[str], post_process: Callable | None = None, backend: str = 'matplotlib', page: int = 0, **plot_drawing_kwargs)[source]#

Create a plotting function for a specified measure using the specified backend.

Parameters:
  • measure (str | dict[str, str] | list[str] | tuple[str]) – Measure(s) to plot.

  • post_process – a user-specified callable to do post-processing called with the Axes instance.

  • backend – the backend to use {“matplotlib”, “altair”}

  • page – Page number where the plot should be displayed (default 0).

  • plot_drawing_kwargs – additional keyword arguments to pass onto the backend specific function for making a plotting component

Returns:

A tuple of a function and page number that creates a plot component on that specific page.

Return type:

(function, page)

make_space_component(agent_portrayal: Callable | None = None, propertylayer_portrayal: dict | None = None, post_process: Callable | None = None, backend: str = 'matplotlib', **space_drawing_kwargs) SpaceMatplotlib | SpaceAltair[source]#

Create a Matplotlib-based space visualization component.

Parameters:
  • agent_portrayal – Function to portray agents.

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • post_process – a callable that will be called with the Axes instance. Allows for fine-tuning plots (e.g., control ticks)

  • backend – the backend to use {“matplotlib”, “altair”}

  • space_drawing_kwargs – additional keyword arguments to be passed on to the underlying backend specific space drawer function. See the functions for drawing the various spaces for the appropriate backend further details.

Returns:

A function that creates a space component

Return type:

function

User Parameters#

Solara visualization related helper classes.

class UserParam[source]#

Bases: object

UserParam.

maybe_raise_error(param_type, valid)[source]#
class Slider(label='', value=None, min=None, max=None, step=1, dtype=None)[source]#

Bases: UserParam

A number-based slider input with settable increment.

Example: slider_option = Slider(“My Slider”, value=123, min=10, max=200, step=0.1)

Parameters:
  • label – The displayed label in the UI

  • value – The initial value of the slider

  • min – The minimum possible value of the slider

  • max – The maximum possible value of the slider

  • step – The step between min and max for a range of possible values

  • dtype – either int or float

Initializes a slider.

Parameters:
  • label – The displayed label in the UI

  • value – The initial value of the slider

  • min – The minimum possible value of the slider

  • max – The maximum possible value of the slider

  • step – The step between min and max for a range of possible values

  • dtype – either int or float

get(attr)[source]#

Matplotlib-based visualizations#

Matplotlib based solara components for visualization MESA spaces and plots.

make_space_matplotlib(*args, **kwargs)[source]#
make_mpl_space_component(agent_portrayal: Callable | None = None, propertylayer_portrayal: dict | None = None, post_process: Callable | None = None, **space_drawing_kwargs) SpaceMatplotlib[source]#

Create a Matplotlib-based space visualization component.

Parameters:
  • agent_portrayal – Function to portray agents.

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • post_process – a callable that will be called with the Axes instance. Allows for fine tuning plots (e.g., control ticks)

  • space_drawing_kwargs – additional keyword arguments to be passed on to the underlying space drawer function. See the functions for drawing the various spaces for further details.

agent_portrayal is called with an agent and should return a dict. Valid fields in this dict are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

Returns:

A function that creates a SpaceMatplotlib component

Return type:

function

make_plot_measure(*args, **kwargs)[source]#
make_mpl_plot_component(measure: str | dict[str, str] | list[str] | tuple[str], post_process: Callable | None = None, page: int = 0, save_format='png')[source]#

Create a plotting function for a specified measure.

Parameters:
  • measure (str | dict[str, str] | list[str] | tuple[str]) – Measure(s) to plot.

  • post_process – a user-specified callable to do post-processing called with the Axes instance.

  • page – Page number where the plot should be displayed.

  • save_format – save format of figure in solara backend

Returns:

A tuple of a function that creates a PlotMatplotlib component and a page number.

Return type:

(function, page)

Helper functions for drawing mesa spaces with matplotlib.

These functions are used by the provided matplotlib components, but can also be used to quickly visualize a space with matplotlib for example when creating a mp4 of a movie run or when needing a figure for a paper.

collect_agent_data(space: SingleGrid | MultiGrid | OrthogonalMooreGrid | OrthogonalVonNeumannGrid | HexSingleGrid | HexMultiGrid | HexGrid | NetworkGrid | Network | ContinuousSpace | VoronoiGrid, agent_portrayal: Callable, default_size: float | None = None) dict[source]#

Collect the plotting data for all agents in the space.

Parameters:
  • space – The space containing the Agents.

  • agent_portrayal – A callable that is called with the agent and returns a AgentPortrayalStyle

  • default_size – default size

agent_portrayal should return a AgentPortrayalStyle, limited to size (size of marker), color (color of marker), zorder (z-order), marker (marker style), alpha, linewidths, and edgecolors.

draw_space(space, agent_portrayal: Callable, propertylayer_portrayal: Callable | None = None, ax: Axes | None = None, **space_drawing_kwargs)[source]#

Draw a Matplotlib-based visualization of the space.

Parameters:
  • space – the space of the mesa model

  • agent_portrayal – A callable that returns a AgnetPortrayalStyle specifying how to show the agent

  • propertylayer_portrayal – A callable that returns a PropertyLayerStyle specifying how to show the property layer

  • ax – the axes upon which to draw the plot

  • space_drawing_kwargs – any additional keyword arguments to be passed on to the underlying function for drawing the space.

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

draw_property_layers(space, propertylayer_portrayal: dict[str, dict[str, Any]] | Callable, ax: Axes)[source]#

Draw PropertyLayers on the given axes.

Parameters:
  • space (mesa.space._Grid) – The space containing the PropertyLayers.

  • propertylayer_portrayal (Callable) – A function that accepts a property layer object and returns either a PropertyLayerStyle object defining its visualization, or None to skip drawing this particular layer.

  • ax (matplotlib.axes.Axes) – The axes to draw on.

draw_orthogonal_grid(space: SingleGrid | MultiGrid | OrthogonalMooreGrid | OrthogonalVonNeumannGrid, agent_portrayal: Callable, ax: Axes | None = None, draw_grid: bool = True, **kwargs)[source]#

Visualize a orthogonal grid.

Parameters:
  • space – the space to visualize

  • agent_portrayal – a callable that is called with the agent and returns a AgentPortrayalStyle

  • ax – a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots

  • draw_grid – whether to draw the grid

  • kwargs – additional keyword arguments passed to ax.scatter

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

draw_hex_grid(space: HexSingleGrid | HexMultiGrid | HexGrid, agent_portrayal: Callable, ax: Axes | None = None, draw_grid: bool = True, **kwargs)[source]#

Visualize a hex grid.

Parameters:
  • space – the space to visualize

  • agent_portrayal – a callable that is called with the agent and returns a AgentPortrayalStyle

  • ax – a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots

  • draw_grid – whether to draw the grid

  • kwargs – additional keyword arguments passed to ax.scatter

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

draw_network(space: ~mesa.space.NetworkGrid | ~mesa.discrete_space.network.Network, agent_portrayal: ~collections.abc.Callable, ax: ~matplotlib.axes._axes.Axes | None = None, draw_grid: bool = True, layout_alg=<function spring_layout>, layout_kwargs=None, **kwargs)[source]#

Visualize a network space.

Parameters:
  • space – the space to visualize

  • agent_portrayal – a callable that is called with the agent and returns a AgentPortrayalStyle

  • ax – a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots

  • draw_grid – whether to draw the grid

  • layout_alg – a networkx layout algorithm or other callable with the same behavior

  • layout_kwargs – a dictionary of keyword arguments for the layout algorithm

  • kwargs – additional keyword arguments passed to ax.scatter

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

draw_continuous_space(space: ContinuousSpace, agent_portrayal: Callable, ax: Axes | None = None, **kwargs)[source]#

Visualize a continuous space.

Parameters:
  • space – the space to visualize

  • agent_portrayal – a callable that is called with the agent and returns a AgentPortrayalStyle

  • ax – a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots

  • kwargs – additional keyword arguments passed to ax.scatter

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

draw_voronoi_grid(space: VoronoiGrid, agent_portrayal: Callable, ax: Axes | None = None, draw_grid: bool = True, **kwargs)[source]#

Visualize a voronoi grid.

Parameters:
  • space – the space to visualize

  • agent_portrayal – a callable that is called with the agent and returns a AgentPortrayalStyle

  • ax – a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots

  • draw_grid – whether to draw the grid or not

  • kwargs – additional keyword arguments passed to ax.scatter

Returns:

Returns the Axes object with the plot drawn onto it.

agent_portrayal is called with an agent and should return a AgentPortrayalStyle. Valid fields in this object are “color”, “size”, “marker”, “zorder”, alpha, linewidths, and edgecolors. Other field are ignored and will result in a user warning.

Altair-based visualizations#

Altair based solara components for visualization mesa spaces.

make_space_altair(*args, **kwargs)[source]#
make_altair_space(agent_portrayal, propertylayer_portrayal=None, post_process=None, **space_drawing_kwargs)[source]#

Create an Altair-based space visualization component.

Parameters:
  • agent_portrayal – Function to portray agents.

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • post_process – A user specified callable that will be called with the Chart instance from Altair. Allows for fine tuning plots (e.g., control ticks)

  • space_drawing_kwargs – not yet implemented

agent_portrayal is called with an agent and should return a dict. Valid fields in this dict are “color”, “size”, “marker”, and “zorder”. Other field are ignored and will result in a user warning.

Returns:

A function that creates a SpaceMatplotlib component

Return type:

function

chart_property_layers(space, propertylayer_portrayal, chart_width, chart_height)[source]#

Creates Property Layers in the Altair Components.

Parameters:
  • space – the ContinuousSpace instance

  • propertylayer_portrayal – Dictionary of PropertyLayer portrayal specifications

  • chart_width – width of the agent chart to maintain consistency with the property charts

  • chart_height – height of the agent chart to maintain consistency with the property charts

  • agent_chart – the agent chart to layer with the property layers on the grid

Returns:

Altair Chart

make_altair_plot_component(measure: str | dict[str, str] | list[str] | tuple[str], post_process: Callable | None = None, page: int = 0, grid=False)[source]#

Create a plotting function for a specified measure.

Parameters:
  • measure (str | dict[str, str] | list[str] | tuple[str]) – Measure(s) to plot.

  • post_process – a user-specified callable to do post-processing called with the Axes instance.

  • page – Page number where the plot should be displayed.

  • grid – Bool to draw grid or not.

Returns:

A tuple of a function that creates a PlotAltair component and a page number.

Return type:

(function, page)

Command Console#

A command console interface for interactive Python code execution in the browser.

This module provides a set of classes and functions to create an interactive Python console that can be embedded in a web browser. It supports command history, multi-line code blocks, and special commands for console management.

Notes

  • The console supports multi-line code blocks with proper indentation

  • Output is captured and displayed with appropriate formatting

  • Error messages are displayed in red with distinct styling

  • The console maintains a history of commands and their outputs

class ConsoleEntry(command: str, output: str = '', is_error: bool = False, is_continuation: bool = False)[source]#

Bases: object

A class to store command console entries.

command#

The command entered

Type:

str

output#

The output of the command

Type:

str

is_error#

Whether the entry represents an error

Type:

bool

is_continuation#

Whether the entry is a continuation of previous command

Type:

bool

command: str#
output: str = ''#
is_error: bool = False#
is_continuation: bool = False#
class CaptureOutput[source]#

Bases: object

A context manager for capturing stdout and stderr output.

This class provides a way to capture output that would normally be printed to stdout and stderr during the execution of code within its context.

Initialize the CaptureOutput context manager with empty string buffers.

get_output()[source]#

Retrieve and clear the captured output.

Returns:

A pair of strings (stdout_output, stderr_output)

Return type:

tuple

class InteractiveConsole(locals_dict=None)[source]#

Bases: InteractiveConsole

A custom interactive Python console with output capturing capabilities.

This class extends code.InteractiveConsole to provide output capturing functionality when executing Python code interactively.

Parameters:

locals_dict (dict, optional) – Dictionary of local variables. Defaults to None.

Initialize the InteractiveConsole with the provided locals dictionary.

push(line)[source]#

Push a line to the command interpreter and execute it.

This method captures the output of the executed command and returns both the ‘more’ flag and the captured output.

Parameters:

line (str) – The line of code to be executed.

Returns:

A tuple containing:
  • more (bool): Flag indicating if more input is needed

  • str: The captured output from executing the command

Return type:

tuple

class ConsoleManager(model=None, additional_imports=None)[source]#

Bases: object

A console manager for executing Python code interactively.

This class provides functionality to execute Python code in an interactive console environment, maintain command history, and handle multi-line code blocks.

locals_dict#

Dictionary containing local variables available to the console

Type:

dict

console#

Python’s interactive console instance

Type:

InteractiveConsole

buffer#

Buffer for storing multi-line code blocks

Type:

list

history#

List of console entries containing commands and their outputs

Type:

list[ConsoleEntry]

Special Commands:
  1. history : Shows the command history

  2. cls : Clears the console screen

  3. tips : Shows available console commands and usage tips

Example

>>> console = ConsoleManager(model=my_model)
>>> console.execute_code("print('hello world')", set_input_callback)

Initialize the console manager with the provided model and imports.

execute_code(code_line: str, set_input_text: Callable[[str], None]) None[source]#

Execute the provided code line and update the console history.

clear_console() None[source]#

Clear the console history and reset the console state.

get_entries() list[ConsoleEntry][source]#

Get the list of console entries.

prev_command(current_text: str, set_input_text: Callable[[str], None]) None[source]#

Navigate to previous command in history.

next_command(set_input_text: Callable[[str], None]) None[source]#

Navigate to next command in history.

format_command_html(entry)[source]#

Format the command part of a console entry as HTML.

format_output_html(entry)[source]#

Format the output part of a console entry as HTML.

Portrayal Components#

Portrayal Components Module.

This module defines data structures for styling visual elements in Mesa agent-based model visualizations. It provides user-facing classes to specify how agents and property layers should appear in the rendered space.

Classes: 1. AgentPortrayalStyle: Controls the appearance of individual agents (e.g., color, shape, size, etc.). 2. PropertyLayerStyle: Controls the appearance of background property layers (e.g., color gradients or uniform fills).

These components are designed to be passed into Mesa visualizations to customize and standardize how data is presented.

class AgentPortrayalStyle(x: float | None = None, y: float | None = None, color: str | tuple | int | float | None = 'tab:blue', marker: str | None = 'o', size: int | float | None = 50, zorder: int | None = 1, alpha: float | None = 1.0, edgecolors: str | tuple | None = None, linewidths: float | int | None = 1.0)[source]#

Bases: object

Represents the visual styling options for an agent in a visualization.

User facing component to control how agents are drawn. Allows specifying properties like color, size, marker shape, position, and other plot attributes.

x, y are determined automatically according to the agent’s type (normal/CellAgent) and position in the space if not manually declared.

Example

>>> def agent_portrayal(agent):
>>>     return AgentPortrayalStyle(
>>>         x=agent.cell.coordinate[0],
>>>         y=agent.cell.coordinate[1],
>>>         color="red",
>>>         marker="o",
>>>         size=20,
>>>         zorder=2,
>>>         alpha=0.8,
>>>         edgecolors="black",
>>>         linewidths=1.5
>>>     )
>>>
>>> # or for a default agent portrayal
>>> def agent_portrayal(agent):
>>>     return AgentPortrayalStyle()
x: float | None = None#
y: float | None = None#
color: str | tuple | int | float | None = 'tab:blue'#
marker: str | None = 'o'#
size: int | float | None = 50#
zorder: int | None = 1#
alpha: float | None = 1.0#
edgecolors: str | tuple | None = None#
linewidths: float | int | None = 1.0#
update(*updates_fields: tuple[str, Any])[source]#

Updates attributes from variable (field_name, new_value) tuple arguments.

Example

>>> def agent_portrayal(agent):
>>>     primary_style = AgentPortrayalStyle(color="blue", marker="^", size=10, x=agent.pos[0], y=agent.pos[1])
>>>     if agent.type == 1:
>>>         primary_style.update(("color", "red"), ("size", 30))
>>>     return primary_style
class PropertyLayerStyle(colormap: str | None = None, color: str | None = None, alpha: float = 0.8, colorbar: bool = True, vmin: float | None = None, vmax: float | None = None)[source]#

Bases: object

Represents the visual styling options for a property layer in a visualization.

User facing component to control how property layers are drawn. Allows specifying properties like colormap, single color, value limits (vmin, vmax), transparency (alpha) and colorbar visibility.

Note: vmin and vmax are the lower and upper bounds for the colorbar and the data is normalized between these values for color/colormap rendering. If they are not declared the values are automatically determined from the data range.

Note: You can specify either a ‘colormap’ (for varying data) or a single ‘color’ (for a uniform layer appearance), but not both simultaneously.

Example

>>> def propertylayer_portrayal(layer):
>>>     return PropertyLayerStyle(colormap="viridis", vmin=0, vmax=100, alpha=0.5, colorbar=True)
>>> # or for a uniform color layer
>>> def propertylayer_portrayal(layer):
>>>     return PropertyLayerStyle(color="lightblue", alpha=0.8, colorbar=False)
colormap: str | None = None#
color: str | None = None#
alpha: float = 0.8#
colorbar: bool = True#
vmin: float | None = None#
vmax: float | None = None#

Backends#

Visualization backends for Mesa space rendering.

This module provides different backend implementations for visualizing Mesa agent-based model spaces and components.

Note

These backends are used internally by the space renderer and are not intended for direct use by end users. See SpaceRenderer for actual usage and setting up visualizations.

Available Backends:
  1. AltairBackend

  2. MatplotlibBackend

class AltairBackend(space_drawer)[source]#

Bases: AbstractRenderer

Altair-based renderer for Mesa spaces.

This module provides an Altair-based renderer for visualizing Mesa model spaces, agents, and property layers with interactive charting capabilities.

Initialize the renderer.

Parameters:
  • space_drawer – Object responsible for drawing space elements. Checkout SpaceDrawer

  • functions. (for more details on the detailed implementations of the drawing)

collect_agent_data(space, agent_portrayal: Callable, default_size: float | None = None)[source]#

Collect plotting data for all agents in the space for Altair.

Parameters:
  • space – The Mesa space containing agents.

  • agent_portrayal – Callable that returns AgentPortrayalStyle for each agent.

  • default_size – Default marker size if not specified in portrayal.

Returns:

Dictionary containing agent plotting data arrays.

Return type:

dict

draw_agents(arguments, chart_width: int = 450, chart_height: int = 350, **kwargs)[source]#

Draw agents using Altair backend.

Parameters:
  • arguments – Dictionary containing agent data arrays.

  • chart_width – Width of the chart.

  • chart_height – Height of the chart.

  • **kwargs – Additional keyword arguments for customization.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Altair chart representing the agents, or None if no agents.

Return type:

alt.Chart

draw_propertylayer(space, property_layers: dict[str, Any], propertylayer_portrayal: Callable, chart_width: int = 450, chart_height: int = 350)[source]#

Draw property layers using Altair backend.

Parameters:
  • space – The Mesa space object containing the property layers.

  • property_layers – A dictionary of property layers to draw.

  • propertylayer_portrayal – A function that returns PropertyLayerStyle that contains the visualization parameters.

  • chart_width – The width of the chart.

  • chart_height – The height of the chart.

Returns:

A tuple containing the base chart and the color bar chart.

Return type:

alt.Chart

draw_structure(**kwargs) Chart[source]#

Draw the space structure using Altair.

Parameters:
  • **kwargs – Additional arguments passed to the space drawer.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Altair chart representing the space structure.

Return type:

alt.Chart

initialize_canvas() None[source]#

Initialize the Altair canvas.

class MatplotlibBackend(space_drawer)[source]#

Bases: AbstractRenderer

Matplotlib-based renderer for Mesa spaces.

Provides visualization capabilities using Matplotlib for rendering space structures, agents, and property layers.

Initialize the Matplotlib backend.

Parameters:

space_drawer – An instance of a SpaceDrawer class that handles the drawing of the space structure.

collect_agent_data(space, agent_portrayal, default_size=None)[source]#

Collect plotting data for all agents in the space.

Parameters:
  • space – The Mesa space containing agents.

  • agent_portrayal (Callable) – Function that returns AgentPortrayalStyle for each agent.

  • default_size (float, optional) – Default marker size if not specified in portrayal.

Returns:

Dictionary containing agent plotting data arrays.

Return type:

dict

draw_agents(arguments, **kwargs)[source]#

Draw agents on the backend’s axes - optimized version.

Parameters:
  • arguments – Dictionary containing agent data arrays.

  • **kwargs – Additional keyword arguments for customization.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Matplotlib Axes with the agents drawn upon it.

Return type:

matplotlib.axes.Axes

draw_propertylayer(space, property_layers, propertylayer_portrayal)[source]#

Draw property layers using matplotlib backend.

Parameters:
  • space – The Mesa space object.

  • property_layers (dict) – Dictionary of property layers to visualize.

  • propertylayer_portrayal (Callable) – Function that returns PropertyLayerStyle.

Returns:

(matplotlib.axes.Axes, colorbar) - The matplotlib axes and colorbar objects.

Return type:

tuple

draw_structure(**kwargs)[source]#

Draw the space structure using matplotlib.

Parameters:
  • **kwargs – Additional arguments passed to the space drawer.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The matplotlib axes with the drawn structure.

initialize_canvas(ax=None)[source]#

Initialize the matplotlib canvas.

Parameters:

ax (matplotlib.axes.Axes, optional) – Existing axes to use. If None, creates new figure and axes.

Abstract base class for visualization backends in Mesa.

This module provides the foundational interface for implementing various visualization backends for Mesa agent-based models.

class AbstractRenderer(space_drawer)[source]#

Bases: ABC

Abstract base class for visualization backends.

This class defines the interface for rendering Mesa spaces and agents. For details on the methods checkout specific backend implementations.

Initialize the renderer.

Parameters:
  • space_drawer – Object responsible for drawing space elements. Checkout SpaceDrawer

  • functions. (for more details on the detailed implementations of the drawing)

abstractmethod initialize_canvas()[source]#

Set up the drawing canvas.

abstractmethod draw_structure(**kwargs)[source]#

Draw the space structure.

Parameters:

**kwargs – Structure drawing configuration options.

abstractmethod collect_agent_data(space, agent_portrayal, default_size=None)[source]#

Collect plotting data for all agents in the space.

Parameters:
  • space – The Mesa space containing agents.

  • agent_portrayal (Callable) – Function that returns AgentPortrayalStyle for each agent.

  • default_size (float, optional) – Default marker size if not specified in portrayal.

Returns:

Dictionary containing agent plotting data arrays with keys:

Return type:

dict

abstractmethod draw_agents(arguments, **kwargs)[source]#

Drawing agents on space.

Parameters:
  • arguments (dict) – Dictionary containing agent data.

  • **kwargs – Additional drawing configuration options.

abstractmethod draw_propertylayer(space, property_layers, propertylayer_portrayal)[source]#

Draw property layers on the visualization.

Parameters:
  • space – The model’s space object.

  • property_layers (dict) – Dictionary of property layers to visualize.

  • propertylayer_portrayal (Callable) – Function that returns PropertyLayerStyle.

class AltairBackend(space_drawer)[source]#

Bases: AbstractRenderer

Altair-based renderer for Mesa spaces.

This module provides an Altair-based renderer for visualizing Mesa model spaces, agents, and property layers with interactive charting capabilities.

Initialize the renderer.

Parameters:
  • space_drawer – Object responsible for drawing space elements. Checkout SpaceDrawer

  • functions. (for more details on the detailed implementations of the drawing)

initialize_canvas() None[source]#

Initialize the Altair canvas.

draw_structure(**kwargs) Chart[source]#

Draw the space structure using Altair.

Parameters:
  • **kwargs – Additional arguments passed to the space drawer.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Altair chart representing the space structure.

Return type:

alt.Chart

collect_agent_data(space, agent_portrayal: Callable, default_size: float | None = None)[source]#

Collect plotting data for all agents in the space for Altair.

Parameters:
  • space – The Mesa space containing agents.

  • agent_portrayal – Callable that returns AgentPortrayalStyle for each agent.

  • default_size – Default marker size if not specified in portrayal.

Returns:

Dictionary containing agent plotting data arrays.

Return type:

dict

draw_agents(arguments, chart_width: int = 450, chart_height: int = 350, **kwargs)[source]#

Draw agents using Altair backend.

Parameters:
  • arguments – Dictionary containing agent data arrays.

  • chart_width – Width of the chart.

  • chart_height – Height of the chart.

  • **kwargs – Additional keyword arguments for customization.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Altair chart representing the agents, or None if no agents.

Return type:

alt.Chart

draw_propertylayer(space, property_layers: dict[str, Any], propertylayer_portrayal: Callable, chart_width: int = 450, chart_height: int = 350)[source]#

Draw property layers using Altair backend.

Parameters:
  • space – The Mesa space object containing the property layers.

  • property_layers – A dictionary of property layers to draw.

  • propertylayer_portrayal – A function that returns PropertyLayerStyle that contains the visualization parameters.

  • chart_width – The width of the chart.

  • chart_height – The height of the chart.

Returns:

A tuple containing the base chart and the color bar chart.

Return type:

alt.Chart

class MatplotlibBackend(space_drawer)[source]#

Bases: AbstractRenderer

Matplotlib-based renderer for Mesa spaces.

Provides visualization capabilities using Matplotlib for rendering space structures, agents, and property layers.

Initialize the Matplotlib backend.

Parameters:

space_drawer – An instance of a SpaceDrawer class that handles the drawing of the space structure.

initialize_canvas(ax=None)[source]#

Initialize the matplotlib canvas.

Parameters:

ax (matplotlib.axes.Axes, optional) – Existing axes to use. If None, creates new figure and axes.

draw_structure(**kwargs)[source]#

Draw the space structure using matplotlib.

Parameters:
  • **kwargs – Additional arguments passed to the space drawer.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The matplotlib axes with the drawn structure.

collect_agent_data(space, agent_portrayal, default_size=None)[source]#

Collect plotting data for all agents in the space.

Parameters:
  • space – The Mesa space containing agents.

  • agent_portrayal (Callable) – Function that returns AgentPortrayalStyle for each agent.

  • default_size (float, optional) – Default marker size if not specified in portrayal.

Returns:

Dictionary containing agent plotting data arrays.

Return type:

dict

draw_agents(arguments, **kwargs)[source]#

Draw agents on the backend’s axes - optimized version.

Parameters:
  • arguments – Dictionary containing agent data arrays.

  • **kwargs – Additional keyword arguments for customization.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The Matplotlib Axes with the agents drawn upon it.

Return type:

matplotlib.axes.Axes

draw_propertylayer(space, property_layers, propertylayer_portrayal)[source]#

Draw property layers using matplotlib backend.

Parameters:
  • space – The Mesa space object.

  • property_layers (dict) – Dictionary of property layers to visualize.

  • propertylayer_portrayal (Callable) – Function that returns PropertyLayerStyle.

Returns:

(matplotlib.axes.Axes, colorbar) - The matplotlib axes and colorbar objects.

Return type:

tuple

Space Renderer#

Space rendering module for Mesa visualizations.

This module provides functionality to render Mesa model spaces with different backends, supporting various space types and visualization components.

class SpaceRenderer(model: Model, backend: Literal['matplotlib', 'altair'] | None = 'matplotlib')[source]#

Bases: object

Renders Mesa spaces using different visualization backends.

Supports multiple space types and backends for flexible visualization of agent-based models.

Initialize the space renderer.

Parameters:
  • model (mesa.Model) – The Mesa model to render.

  • backend (Literal["matplotlib", "altair"] | None) – The visualization backend to use.

draw_structure(**kwargs)[source]#

Draw the space structure.

Parameters:
  • **kwargs – Additional keyword arguments for the drawing function.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The visual representation of the space structure.

draw_agents(agent_portrayal: Callable, **kwargs)[source]#

Draw agents on the space.

Parameters:
  • agent_portrayal (Callable) – Function that takes an agent and returns AgentPortrayalStyle.

  • **kwargs – Additional keyword arguments for the drawing function.

  • **kwargs. (Checkout respective SpaceDrawer class on details how to pass) –

Returns:

The visual representation of the agents.

draw_propertylayer(propertylayer_portrayal: Callable | dict)[source]#

Draw property layers on the space.

Parameters:

propertylayer_portrayal (Callable | dict) – Function that returns PropertyLayerStyle or dict with portrayal parameters.

Returns:

The visual representation of the property layers.

Raises:

Exception – If no property layers are found on the space.

render(agent_portrayal: Callable | None = None, propertylayer_portrayal: Callable | dict | None = None, post_process: Callable | None = None, **kwargs)[source]#

Render the complete space with structure, agents, and property layers.

It is an all-in-one method that draws everything required therefore eliminates the need of calling each method separately, but has a drawback, if want to pass kwargs to customize the drawing, they have to be broken into space_kwargs and agent_kwargs.

Parameters:
  • agent_portrayal (Callable | None) – Function that returns AgentPortrayalStyle. If None, agents won’t be drawn.

  • propertylayer_portrayal (Callable | dict | None) – Function that returns PropertyLayerStyle or dict with portrayal parameters. If None, property layers won’t be drawn.

  • post_process (Callable | None) – Function to apply post-processing to the canvas.

  • **kwargs – Additional keyword arguments for drawing functions. * space_kwargs (dict): Arguments for draw_structure(). * agent_kwargs (dict): Arguments for draw_agents().

property canvas#

Get the current canvas object.

Returns:

The backend-specific canvas object.

property post_process#

Get the current post-processing function.

Returns:

The post-processing function, or None if not set.

Return type:

Callable | None

Space Drawers#

Mesa visualization space drawers.

This module provides the core logic for drawing spaces in Mesa, supporting orthogonal grids, hexagonal grids, networks, continuous spaces, and Voronoi grids. It includes implementations for both Matplotlib and Altair backends.

class BaseSpaceDrawer(space)[source]#

Bases: object

Base class for all space drawers.

Initialize the base space drawer.

Parameters:

space – Grid/Space type to draw.

get_viz_limits()[source]#

Get visualization limits for the space.

Returns:

A tuple of (xmin, xmax, ymin, ymax) for visualization limits.

class OrthogonalSpaceDrawer(space: SingleGrid | MultiGrid | OrthogonalMooreGrid | OrthogonalVonNeumannGrid)[source]#

Bases: BaseSpaceDrawer

Drawer for orthogonal grid spaces (SingleGrid, MultiGrid, Moore, VonNeumann).

Initialize the orthogonal space drawer.

Parameters:

space – The orthogonal grid space to draw

draw_matplotlib(ax=None, **space_kwargs)[source]#

Draw the orthogonal grid using matplotlib.

Parameters:
  • ax – Matplotlib axes object to draw on

  • **space_kwargs – Additional keyword arguments for styling.

Examples

figsize=(10, 10), color=”blue”, linewidth=2.

Returns:

The modified axes object

draw_altair(chart_width=450, chart_height=350, **chart_kwargs)[source]#

Draw the orthogonal grid using Altair.

Parameters:
  • chart_width – Width for the shown chart

  • chart_height – Height for the shown chart

  • **chart_kwargs – Additional keyword arguments for styling the chart.

Examples

width=500, height=500, title=”Grid”.

Returns:

Altair chart object

class HexSpaceDrawer(space: HexSingleGrid | HexMultiGrid | HexGrid)[source]#

Bases: BaseSpaceDrawer

Drawer for hexagonal grid spaces.

Initialize the hexagonal space drawer.

Parameters:

space – The hexagonal grid space to draw

draw_matplotlib(ax=None, **space_kwargs)[source]#

Draw the hexagonal grid using matplotlib.

Parameters:
  • ax – Matplotlib axes object to draw on

  • **space_kwargs – Additional keyword arguments for styling.

Examples

figsize=(8, 8), color=”red”, alpha=0.5.

Returns:

The modified axes object

draw_altair(chart_width=450, chart_height=350, **chart_kwargs)[source]#

Draw the hexagonal grid using Altair.

Parameters:
  • chart_width – Width for the shown chart

  • chart_height – Height for the shown chart

  • **chart_kwargs – Additional keyword arguments for styling the chart.

Examples

  • Line properties like color, strokeDash, strokeWidth, opacity.

  • Other kwargs (e.g., width, title) apply to the chart.

Returns:

Altair chart object representing the hexagonal grid.

class NetworkSpaceDrawer(space: ~mesa.space.NetworkGrid | ~mesa.discrete_space.network.Network, layout_alg=<function spring_layout>, layout_kwargs=None)[source]#

Bases: BaseSpaceDrawer

Drawer for network-based spaces.

Initialize the network space drawer.

Parameters:
  • space – The network space to draw

  • layout_alg – NetworkX layout algorithm to use

  • layout_kwargs – Keyword arguments for the layout algorithm

draw_matplotlib(ax=None, **space_kwargs)[source]#

Draw the network using matplotlib.

Parameters:
  • ax – Matplotlib axes object to draw on.

  • **space_kwargs – Dictionaries of keyword arguments for styling. Can also handle zorder for both nodes and edges if passed. * node_kwargs: A dict passed to nx.draw_networkx_nodes. * edge_kwargs: A dict passed to nx.draw_networkx_edges.

Returns:

The modified axes object.

draw_altair(chart_width=450, chart_height=350, **chart_kwargs)[source]#

Draw the network using Altair.

Parameters:
  • chart_width – Width for the shown chart

  • chart_height – Height for the shown chart

  • **chart_kwargs – Dictionaries for styling the chart. * node_kwargs: A dict of properties for the node’s mark_point. * edge_kwargs: A dict of properties for the edge’s mark_rule. * Other kwargs (e.g., title, width) are passed to chart.properties().

Returns:

Altair chart object representing the network.

class ContinuousSpaceDrawer(space: ContinuousSpace)[source]#

Bases: BaseSpaceDrawer

Drawer for continuous spaces.

Initialize the continuous space drawer.

Parameters:

space – The continuous space to draw

draw_matplotlib(ax=None, **space_kwargs)[source]#

Draw the continuous space using matplotlib.

Parameters:
  • ax – Matplotlib axes object to draw on

  • **space_kwargs – Keyword arguments for styling the axis frame.

Examples

linewidth=3, color=”green”

Returns:

The modified axes object

draw_altair(chart_width=450, chart_height=350, **chart_kwargs)[source]#

Draw the continuous space using Altair.

Parameters:
  • chart_width – Width for the shown chart

  • chart_height – Height for the shown chart

  • **chart_kwargs – Keyword arguments for styling the chart’s view properties. See Altair’s documentation for configure_view.

Returns:

An Altair Chart object representing the space.

class VoronoiSpaceDrawer(space: VoronoiGrid)[source]#

Bases: BaseSpaceDrawer

Drawer for Voronoi diagram spaces.

Initialize the Voronoi space drawer.

Parameters:

space – The Voronoi grid space to draw

draw_matplotlib(ax=None, **space_kwargs)[source]#

Draw the Voronoi diagram using matplotlib.

Parameters:
  • ax – Matplotlib axes object to draw on

  • **space_kwargs – Keyword arguments passed to matplotlib’s LineCollection.

Examples

lw=2, alpha=0.5, colors=’red’

Returns:

The modified axes object

draw_altair(chart_width=450, chart_height=350, **chart_kwargs)[source]#

Draw the Voronoi diagram using Altair.

Parameters:
  • chart_width – Width for the shown chart

  • chart_height – Height for the shown chart

  • **chart_kwargs – Additional keyword arguments for styling the chart.

Examples

  • Line properties like color, strokeDash, strokeWidth, opacity.

  • Other kwargs (e.g., width, title) apply to the chart.

Returns:

An Altair Chart object representing the Voronoi diagram.