### Install Mesa and Run Schelling Example Source: https://mesa.readthedocs.io/latest/examples/basic/schelling.html Commands to install the Mesa framework with recommended dependencies and execute the interactive Schelling model application. ```bash pip install "mesa[rec]" solara run app.py ``` -------------------------------- ### Install and Run Streamlit Visualization Source: https://mesa.readthedocs.io/latest/examples/basic/boltzmann_wealth_model.html Commands to install the necessary dependencies for the optional Streamlit visualization and launch the application. ```bash pip install streamlit altair streamlit run st_app.py ``` -------------------------------- ### Configure Renderer with Method Chaining Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Demonstrates the shift from passing portrayal arguments directly to draw methods to using setup methods for configuration. This separates the setup phase from the rendering phase. ```python renderer.setup_agents(agent_portrayal).draw_agents() renderer.setup_propertylayer(propertylayer_portrayal).draw_propertylayer() ``` -------------------------------- ### Install Mesa and Dependencies (Bash) Source: https://mesa.readthedocs.io/latest/tutorials/0_first_model.html Installs the Mesa library with optional extras for data collection, Jupyter for interactive notebooks, and Seaborn for data visualization. Python 3.12 or higher is recommended. ```bash pip install mesa[rec] pip install jupyter pip install seaborn ``` -------------------------------- ### Wolf Sheep Agent Portrayal and Visualization Setup - Python Source: https://mesa.readthedocs.io/latest/examples/advanced/wolf_sheep.html Defines how agents (Wolf, Sheep, GrassPatch) are visually represented in the simulation space and sets up the visualization components. It includes agent portrayal logic, model parameters for interactive control, and the main visualization page setup using SolaraViz. ```python from mesa.examples.advanced.wolf_sheep.agents import GrassPatch, Sheep, Wolf from mesa.examples.advanced.wolf_sheep.model import WolfSheep, WolfSheepScenario from mesa.visualization import ( CommandConsole, Slider, SolaraViz, SpaceRenderer, make_plot_component, ) from mesa.visualization.components import AgentPortrayalStyle def wolf_sheep_portrayal(agent): if agent is None: return portrayal = AgentPortrayalStyle( size=50, marker="o", zorder=2, ) if isinstance(agent, Wolf): portrayal.update(("color", "red")) elif isinstance(agent, Sheep): portrayal.update(("color", "cyan")) elif isinstance(agent, GrassPatch): if agent.fully_grown: portrayal.update(("color", "tab:green")) else: portrayal.update(("color", "tab:brown")) portrayal.update(("marker", "s"), ("size", 125), ("zorder", 1)) return portrayal model_params = { "rng": { "type": "InputText", "value": 42, "label": "Random Seed", }, "grass": { "type": "Select", "value": True, "values": [True, False], "label": "grass regrowth enabled?", }, "grass_regrowth_time": Slider("Grass Regrowth Time", 20, 1, 50), "initial_sheep": Slider("Initial Sheep Population", 100, 10, 300), "sheep_reproduce": Slider("Sheep Reproduction Rate", 0.04, 0.01, 1.0, 0.01), "initial_wolves": Slider("Initial Wolf Population", 10, 5, 100), "wolf_reproduce": Slider( "Wolf Reproduction Rate", 0.05, 0.01, 1.0, 0.01, ), "wolf_gain_from_food": Slider("Wolf Gain From Food Rate", 20, 1, 50), "sheep_gain_from_food": Slider("Sheep Gain From Food", 4, 1, 10), } def post_process_space(ax): ax.set_aspect("equal") ax.set_xticks([]) ax.set_yticks([]) def post_process_lines(ax): ax.legend(loc="center left", bbox_to_anchor=(1, 0.9)) lineplot_component = make_plot_component( {"Wolves": "tab:orange", "Sheep": "tab:cyan", "Grass": "tab:green"}, post_process=post_process_lines, ) model = WolfSheep(scenario=WolfSheepScenario(grass=True)) renderer = SpaceRenderer( model, backend="matplotlib", ).setup_agents(wolf_sheep_portrayal) renderer.post_process = post_process_space renderer.draw_agents() page = SolaraViz( model, renderer, components=[lineplot_component, CommandConsole], model_params=model_params, name="Wolf Sheep", ) page # noqa ``` -------------------------------- ### Model Initialization for SolaraViz Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Illustrates the updated way to initialize a Mesa model for use with SolaraViz. The visualization now expects a model instance and allows for optional user-settable model parameters. ```python class MyModel(mesa.Model): def __init__(self, n_agents=10, seed=None): super().__init__(seed=seed) # Initialize the model with N agents ``` -------------------------------- ### Install Mesa framework via pip Source: https://mesa.readthedocs.io/latest Commands to install the Mesa library using the Python package manager. Includes options for the latest stable release, pre-release versions, and recommended dependencies for visualization and analysis. ```bash pip install -U mesa ``` ```bash pip install -U --pre mesa ``` ```bash pip install -U mesa[rec] ``` ```bash pip install -U "mesa[rec]" ``` -------------------------------- ### Replace Simulator Classes with Model Methods Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Illustrates the migration from deprecated ABMSimulator and DEVSimulator classes to direct model method calls. ```python # Replacing ABMSimulator model.run_for(100) # Replacing DEVSimulator model.schedule_event(callback, at=10.5) model.run_for(50) ``` -------------------------------- ### Initialize MESA Spatial Environments Source: https://mesa.readthedocs.io/latest/_sources/overview.md.txt Examples for creating various discrete and continuous spaces for agent interaction, including grid-based, network, and Voronoi structures. ```python # Discrete Spaces grid = mesa.discrete_space.OrthogonalVonNeumannGrid((width, height), torus=False) grid = mesa.discrete_space.OrthogonalMooreGrid((width, height), torus=True) grid = mesa.discrete_space.HexGrid((width, height), torus=False) network = mesa.discrete_space.Network(graph) mesh = mesa.discrete_space.VoronoiMesh(points) # Property Layers grid.create_property_layer("elevation", default_value=10) high_ground = grid.property_layers["elevation"] > 50 # Continuous Space space = mesa.space.ContinuousSpace(x_max, y_max, torus=True) space.move_agent(agent, (new_x, new_y)) ``` -------------------------------- ### Manage agents with AgentSet Source: https://mesa.readthedocs.io/latest/_sources/overview.md.txt Provides examples for interacting with the AgentSet class, including filtering, sorting, shuffling, and batch-executing methods on agents. ```python # Accessing agents num_agents = len(model.agents) for agent in model.agents: print(agent.unique_id) # Selecting and manipulating high_energy_agents = model.agents.select(lambda a: a.energy > 50) shuffled_agents = model.agents.shuffle() sorted_agents = model.agents.sort(key="energy", ascending=False) # Batch operations model.agents.do("step") model.agents.shuffle_do("move") # Aggregation and grouping avg_energy = model.agents.agg("energy", func=np.mean) grouped_agents = model.agents.groupby("species") species_counts = grouped_agents.count() ``` -------------------------------- ### Define Multi-Page Plot Components Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Illustrates how to organize visualization components into distinct pages using the page parameter in make_plot_component. ```python from mesa.visualization import SolaraViz, make_plot_component SolaraViz( model, components=[ make_plot_component("foo", page=1), make_plot_component("bar", "baz", page=2), ], ) ``` -------------------------------- ### Handle Agent Placement with Capacity Source: https://mesa.readthedocs.io/latest/apis/discrete_space.html Examples for interacting with grid cells that have finite capacity constraints. Shows how to select random available cells and query capacity status. ```python # Place an agent in any non-full cell agent.move_to(grid.select_random_cell_with_capacity()) # Count how many cells still have room count = len(list(grid.cells_with_capacity)) ``` -------------------------------- ### Define MoneyAgent with wealth and say_wealth method (Python) Source: https://mesa.readthedocs.io/latest/tutorials/0_first_model.html Defines a simple agent with an initial wealth attribute and a method to print its wealth. This serves as a starting point for agent behavior. ```python class MoneyAgent(mesa.Agent): """An agent with fixed initial wealth.""" def __init__(self, model): # Pass the parameters to the parent class. super().__init__(model) # Create the agent's variable and set the initial values. self.wealth = 1 def say_wealth(self): # The agent's step will go here. # FIXME: need to print the agent's wealth print("Hi, I am an agent and I am broke!") ``` -------------------------------- ### Mesa Sugarscape G1MT Model Setup Source: https://mesa.readthedocs.io/latest/examples/advanced/sugarscape_g1mt.html Imports necessary components for the Mesa Sugarscape G1MT model, including Path, numpy, mesa, OrthogonalVonNeumannGrid, Trader agent, and Scenario. ```python from pathlib import Path import numpy as np import mesa from mesa.discrete_space import OrthogonalVonNeumannGrid from mesa.examples.advanced.sugarscape_g1mt.agents import Trader from mesa.experimental.scenarios import Scenario ``` -------------------------------- ### Mandatory Model Initialization with super().__init__() Source: https://mesa.readthedocs.io/latest/migration_guide.html In Mesa 3.0, calling super().__init__() in the model's __init__ method is mandatory for proper setup of model variables and agent handling. The 'seed' argument can be passed to control the random number generator. ```python class MyModel(mesa.Model): def __init__(self, some_arg_I_need, seed=None, some_kwarg_I_need=True): super().__init__(seed=seed) # Calling super is now required, passing seed is highly recommended # Your model initialization code here # this code uses some_arg_I_need and my_init_kwarg ``` -------------------------------- ### Create and run a MoneyModel instance (Python) Source: https://mesa.readthedocs.io/latest/tutorials/0_first_model.html Demonstrates how to instantiate the MoneyModel with a specified number of agents and run it for a set number of steps. This is a fundamental step in executing any Mesa model. ```python model = MoneyModel(10) # Tells the model to create 10 agents for _ in range(30): # Runs the model for 30 steps; model.step() # Note: An underscore is common convention for a variable that is not used. ``` -------------------------------- ### Mandatory Model Initialization with super().__init__() Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt In Mesa 3.0, calling `super().__init__()` within the model's `__init__` method is mandatory. This ensures proper setup of model variables and agent registration. The `seed` argument can be passed to `super().__init__()` for controlling the random number generator's seed. Failure to do so will result in a `RuntimeError`. ```python class MyModel(mesa.Model): def __init__(self, some_arg_I_need, seed=None, some_kwarg_I_need=True): super().__init__(seed=seed) # Calling super is now required, passing seed is highly recommended # Your model initialization code here # this code uses some_arg_I_need and my_init_kwarg ``` ```text RuntimeError: The Mesa Model class was not initialized. You must explicitly initialize the Model by calling super().__init__() on initialization. ``` -------------------------------- ### Instantiate and Run Mesa Model Source: https://mesa.readthedocs.io/latest/tutorials/0_first_model.html Demonstrates how to create an instance of a Mesa model and execute its `step` method. The model runs for one time step, activating agents and performing their defined actions. The `step` method can be called multiple times to advance the simulation. ```python # Create the model object, and run it for one step: starter_model = MoneyModel(10) starter_model.step() # Run this step a few times and see what happens! starter_model.step() ``` -------------------------------- ### Configure Dashboard Page Layout Source: https://mesa.readthedocs.io/latest/tutorials/10_visualization_custom.html Demonstrates how to assign plot components and custom components to specific pages within the Solara dashboard interface. ```python # Assigning a plot component to page 1 plot_comp = make_plot_component("encoding", page=1) # Assigning a custom component to page 1 @solara.component def CustomComponent(): ... page = SolaraViz( model, renderer, components=[(CustomComponent, 1)] ) ``` -------------------------------- ### Run multiple model instances for aggregated results (Python) Source: https://mesa.readthedocs.io/latest/tutorials/0_first_model.html Demonstrates how to run the model multiple times (e.g., 100 times) and collect data (agent wealth) from each run. This is useful for analyzing the variability and robustness of model outcomes. ```python all_wealth = [] # This runs the model 100 times, each model executing 30 steps. for _ in range(100): # Run the model model = MoneyModel(10) model.run_for(30) # Store the results for agent in model.agents: all_wealth.append(agent.wealth) ``` -------------------------------- ### GET /datacollector/data Source: https://mesa.readthedocs.io/latest/genindex.html Retrieves collected simulation data from the DataCollector instance as pandas DataFrames. ```APIDOC ## GET /datacollector/data ### Description Retrieves the collected agent or model variables in a structured DataFrame format for analysis. ### Method GET ### Endpoint /datacollector/get_model_vars_dataframe ### Parameters #### Query Parameters - **model_reporter** (string) - Required - The name of the model reporter to retrieve. ### Request Example { "model_reporter": "total_wealth" } ### Response #### Success Response (200) - **data** (DataFrame) - The collected data series. #### Response Example { "data": "[0, 10, 25, 50]" } ``` -------------------------------- ### Initialize Spatial Environments Source: https://mesa.readthedocs.io/latest/overview.html Shows how to create various spatial structures including discrete grids, networks, Voronoi meshes, and continuous spaces for agent movement. ```python # Discrete Grids grid = mesa.discrete_space.OrthogonalVonNeumannGrid((width, height), torus=False) grid = mesa.discrete_space.OrthogonalMooreGrid((width, height), torus=True) grid = mesa.discrete_space.HexGrid((width, height), torus=False) # Network and Voronoi network = mesa.discrete_space.Network(graph) mesh = mesa.discrete_space.VoronoiMesh(points) # Continuous Space space = mesa.space.ContinuousSpace(x_max, y_max, torus=True) space.move_agent(agent, (new_x, new_y)) ``` -------------------------------- ### Wolf-Sheep Predation Model Implementation Source: https://mesa.readthedocs.io/latest/examples/advanced/wolf_sheep.html Implements the core logic of the Wolf-Sheep Predation Model. It initializes the grid, agents (sheep, wolves, grass), and data collectors based on the provided scenario. The `step` method orchestrates the activation of agents and data collection for each simulation tick. ```python class WolfSheep(Model): """Wolf-Sheep Predation Model. A model for simulating wolf and sheep (predator-prey) ecosystem modelling. """ description = ( "A model for simulating wolf and sheep (predator-prey) ecosystem modelling." ) def __init__(self, scenario: WolfSheepScenario = WolfSheepScenario): """Create a new Wolf-Sheep model with the given parameters. Args: scenario: WolfSheepScenario containing model parameters. """ super().__init__(scenario=scenario) # Initialize model parameters self.height = scenario.height self.width = scenario.width self.grass = scenario.grass # Create grid using experimental cell space self.grid = OrthogonalVonNeumannGrid( [self.height, self.width], torus=True, capacity=math.inf, random=self.random, ) # Set up data collection model_reporters = { "Wolves": lambda m: len(m.agents_by_type[Wolf]), "Sheep": lambda m: len(m.agents_by_type[Sheep]), } if self.grass: model_reporters["Grass"] = lambda m: len( m.agents_by_type[GrassPatch].select(lambda a: a.fully_grown) ) self.datacollector = DataCollector(model_reporters) # Create sheep: Sheep.create_agents( self, scenario.initial_sheep, energy=self.rng.random((scenario.initial_sheep,)) * 2 * scenario.sheep_gain_from_food, p_reproduce=scenario.sheep_reproduce, energy_from_food=scenario.sheep_gain_from_food, cell=self.random.choices( self.grid.all_cells.cells, k=scenario.initial_sheep ), ) # Create Wolves: Wolf.create_agents( self, scenario.initial_wolves, energy=self.rng.random((scenario.initial_wolves,)) * 2 * scenario.wolf_gain_from_food, p_reproduce=scenario.wolf_reproduce, energy_from_food=scenario.wolf_gain_from_food, cell=self.random.choices( self.grid.all_cells.cells, k=scenario.initial_wolves ), ) # Create grass patches if enabled if self.grass: possibly_fully_grown = [True, False] for cell in self.grid: fully_grown = self.random.choice(possibly_fully_grown) countdown = ( 0 if fully_grown else self.random.randrange(0, scenario.grass_regrowth_time) ) GrassPatch(self, countdown, scenario.grass_regrowth_time, cell) # Collect initial data self.running = True self.datacollector.collect(self) def step(self): """Execute one step of the model.""" # First activate all sheep, then all wolves, both in random order self.agents_by_type[Sheep].shuffle_do("step") self.agents_by_type[Wolf].shuffle_do("step") # Collect data self.datacollector.collect(self) ``` -------------------------------- ### GET /agent/vars Source: https://mesa.readthedocs.io/latest/mesa.html Retrieves agent-level variables as a pandas DataFrame. ```APIDOC ## GET /agent/vars ### Description 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. ### Method GET ### Endpoint /agent/vars ### Response #### Success Response (200) - **dataframe** (pandas.DataFrame) - A DataFrame containing agent variables with tick and agent_id columns. #### Response Example { "data": "pandas.DataFrame object" } ``` -------------------------------- ### GET /agentset/get Source: https://mesa.readthedocs.io/latest/apis/agentset.html Retrieves specified attributes from each agent within the AgentSet. ```APIDOC ## GET /agentset/get ### Description Retrieve the specified attribute(s) from each agent in the AgentSet. ### Method GET ### Parameters #### Query Parameters - **attr_names** (str|list[str]) - Required - The name(s) of the attribute(s) to retrieve. - **handle_missing** (str) - Optional - Strategy for missing attributes ('error' or 'default'). - **default_value** (Any) - Optional - Value to return if handle_missing is 'default'. ### Response #### Success Response (200) - **data** (list[Any]) - A list of attribute values for each agent. ### Response Example { "data": [10, 20, 15] } ``` -------------------------------- ### Initialize Visualization Imports Source: https://mesa.readthedocs.io/latest/tutorials/10_visualization_custom.html Required imports for setting up Solara-based visualizations in Mesa, including Matplotlib figure support and update tracking utilities. ```python import solara from matplotlib.figure import Figure from mesa.visualization.utils import update_counter ``` -------------------------------- ### Initialize and Render Mesa Model Visualization Source: https://mesa.readthedocs.io/latest/tutorials/10_visualization_custom.html Configures a MoneyModel instance with specific dimensions and attaches visualization components including space graphs and plots. The resulting SolaraViz object is then rendered to display the interactive model interface. ```python money_model = MoneyModel(n=50, width=10, height=10) SpaceGraph = make_space_component(agent_portrayal) GiniPlot = make_plot_component("Gini", page=1) page = SolaraViz( money_model, components=[SpaceGraph, GiniPlot, (Histogram, 2)], model_params=model_params, name="Boltzmann Wealth Model", ) page ``` -------------------------------- ### GET /space/neighbors Source: https://mesa.readthedocs.io/latest/genindex.html Queries spatial relationships and identifies neighboring agents or cells within a defined space. ```APIDOC ## GET /space/neighbors ### Description Finds agents or cells within a specific radius or proximity to a given agent or coordinate. ### Method GET ### Endpoint /continuous_space/get_agents_in_radius ### Parameters #### Query Parameters - **pos** (tuple) - Required - The center coordinate. - **radius** (float) - Required - The search radius. ### Request Example { "pos": [10, 10], "radius": 5.0 } ### Response #### Success Response (200) - **agents** (list) - List of agent objects found in the radius. #### Response Example { "agents": ["agent_1", "agent_5"] } ``` -------------------------------- ### Configure SolaraViz Visualization Source: https://mesa.readthedocs.io/latest/_sources/overview.md.txt Shows how to initialize a SolaraViz page by defining agent portrayals, model parameters with UI controls, and visualization components such as space grids and plots. ```python from mesa.visualization import SolaraViz, make_space_component, make_plot_component def agent_portrayal(agent): return AgentPortrayalStyle(color="blue", size=50) model_params = { "n_agents": Slider( label="Number of agents:", value=50, min=1, max=100, step=1 ) } page = SolaraViz( MyModel(n_agents=42), [ make_space_component(agent_portrayal), make_plot_component("mean_age") ], model_params=model_params ) page ``` -------------------------------- ### GET /table/{table_name} Source: https://mesa.readthedocs.io/latest/mesa.html Retrieves data from a specific table as a pandas DataFrame. ```APIDOC ## GET /table/{table_name} ### Description Create a pandas DataFrame from a particular table. ### Method GET ### Endpoint /table/{table_name} ### Parameters #### Path Parameters - **table_name** (string) - Required - The name of the table to convert. ### Response #### Success Response (200) - **dataframe** (pandas.DataFrame) - A DataFrame containing the table data. #### Response Example { "data": "pandas.DataFrame object" } ``` -------------------------------- ### Initialize Epstein Model Environment Source: https://mesa.readthedocs.io/latest/examples/advanced/epstein_civil_violence.html Sets up the model environment using Mesa's discrete space grids and scenario configurations. This snippet imports the necessary agent classes and grid types to initialize the simulation space. ```python from typing import Literal import mesa from mesa.discrete_space import OrthogonalMooreGrid, OrthogonalVonNeumannGrid from mesa.examples.advanced.epstein_civil_violence.agents import ( Citizen, CitizenState, Cop, ) from mesa.experimental.scenarios import Scenario ``` -------------------------------- ### GET /model/vars Source: https://mesa.readthedocs.io/latest/mesa.html Retrieves model-level variables as a pandas DataFrame indexed by tick. ```APIDOC ## GET /model/vars ### Description 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. ### Method GET ### Endpoint /model/vars ### Response #### Success Response (200) - **dataframe** (pandas.DataFrame) - A DataFrame containing model variables indexed by tick. #### Response Example { "data": "pandas.DataFrame object" } ``` -------------------------------- ### GET /agent_type/vars/{agent_type} Source: https://mesa.readthedocs.io/latest/mesa.html Retrieves variables for a specific agent type as a pandas DataFrame. ```APIDOC ## GET /agent_type/vars/{agent_type} ### Description Create a pandas DataFrame from the agent-type variables for a specific agent type. ### Method GET ### Endpoint /agent_type/vars/{agent_type} ### Parameters #### Path Parameters - **agent_type** (string) - Required - The type of agent to get the data for. ### Response #### Success Response (200) - **dataframe** (pandas.DataFrame) - A DataFrame containing variables for the specified agent type. #### Response Example { "data": "pandas.DataFrame object" } ``` -------------------------------- ### Assemble SolaraViz Web Application (Python) Source: https://mesa.readthedocs.io/latest/examples/basic/boltzmann_wealth_model.html Combines the Mesa model, its renderer, and plot components into a Solara web application. This allows for interactive visualization and exploration of the model's behavior. The application can be run by saving the code as 'app.py' and executing 'solara run app.py'. ```python # The SolaraViz page combines the model, renderer, and components into a web interface. # To run the visualization, save this code as app.py and run `solara run app.py` page = SolaraViz( model, renderer, components=[GiniPlot], model_params=model_params, name="Boltzmann Wealth Model", ) page # noqa ``` -------------------------------- ### Update DataCollector Initialization Source: https://mesa.readthedocs.io/latest/migration_guide.html Replaces the deprecated initialize_data_collector method in the Model class with a direct assignment to the datacollector attribute. ```python # Old self.initialize_data_collector(...) # New self.datacollector = DataCollector(...) ``` -------------------------------- ### Agent Action Management Source: https://mesa.readthedocs.io/latest/mesa.html Details methods for managing agent actions, including starting, interrupting, and canceling. ```APIDOC ## Agent Action Management ### Description Methods for controlling the execution of actions by an agent, including starting new actions, interrupting ongoing ones, and canceling them. ### Methods #### `start_action(_action: Action_) -> Action` - **Description**: Start performing an action. The action must be in a PENDING or INTERRUPTED state, and the agent must not be currently performing another action. - **Parameters**: - **action** (Action) - The Action to perform. Must have been created with this agent as its agent. - **Returns**: The started Action. - **Raises**: `ValueError` - If the agent is already performing an action, or if the action doesn’t belong to this agent. #### `interrupt_for(_new_action: Action_) -> bool` - **Description**: Interrupt the current action and start a new one. If there is no current action, it simply starts the new one. If the current action is non-interruptible, returns `False` and does nothing. - **Parameters**: - **new_action** (Action) - The Action to perform instead. - **Returns**: `True` if the new action was started (either no current action, or the current one was successfully interrupted). `False` if the current action is non-interruptible. #### `cancel_action() -> bool` - **Description**: Cancel the current action, ignoring the interruptible flag. Calls `on_interrupt()` with partial progress. Returns `False` only if there is no current action. - **Returns**: `True` if an action was cancelled, `False` if the agent was idle. ``` -------------------------------- ### Import Mesa Visualization Dependencies Source: https://mesa.readthedocs.io/latest/tutorials/10_visualization_custom.html Imports necessary libraries for data analysis and visualization, including Mesa's visualization components and version compatibility checks. ```python import numpy as np import pandas as pd import seaborn as sns import mesa from mesa.discrete_space import CellAgent, OrthogonalMooreGrid if mesa.__version__.startswith(("3.0", "3.1", "3.2")): print(f"⚠️ Mesa {mesa.__version__} detected. Visualization features require Mesa 3.3+") print("To upgrade: pip install --upgrade mesa") from mesa.visualization import SolaraViz, make_plot_component, make_space_component ``` -------------------------------- ### Boltzmann Wealth Model Visualization App (Python) Source: https://mesa.readthedocs.io/latest/examples/basic/boltzmann_wealth_model.html This Python code sets up the visualization for the Boltzmann Wealth Model using Solara and Altair. It defines agent portrayal, model parameters, and a post-processing function for the chart. Dependencies include altair, mesa.examples.basic.boltzmann_wealth_model.model, mesa.mesa_logging, and mesa.visualization. ```python import altair as alt from mesa.examples.basic.boltzmann_wealth_model.model import ( BoltzmannScenario, BoltzmannWealth, ) from mesa.mesa_logging import INFO, log_to_stderr from mesa.visualization import ( SolaraViz, SpaceRenderer, make_plot_component, ) from mesa.visualization.components import AgentPortrayalStyle log_to_stderr(INFO) def agent_portrayal(agent): return AgentPortrayalStyle( color=agent.wealth, tooltip={"Agent ID": agent.unique_id, "Wealth": agent.wealth}, # we are using a colormap to translate wealth to color ) model_params = { "rng": { "type": "InputText", "value": 42, "label": "Random Seed", }, "n": { "type": "SliderInt", "value": 50, "label": "Number of agents:", "min": 10, "max": 100, "step": 1, }, "width": 10, "height": 10, } def post_process(chart): """Post-process the Altair chart to add a colorbar legend.""" chart = chart.encode( color=alt.Color( "color:N", scale=alt.Scale(scheme="viridis", domain=[0, 10]), legend=alt.Legend( title="Wealth", orient="right", type="gradient", gradientLength=200, ), ), ) return chart model = BoltzmannWealth( scenario=BoltzmannScenario( n=50, width=10, height=10, ) ) # The SpaceRenderer is responsible for drawing the model's space and agents. ``` -------------------------------- ### Replacing BaseScheduler with AgentSet Source: https://mesa.readthedocs.io/latest/migration_guide.html The BaseScheduler is deprecated in Mesa 3.0. Replace its usage with the 'do' method on the AgentSet for agent activation. ```python # Replace: self.schedule = BaseScheduler(self) self.schedule.step() # With: self.agents.do("step") ``` -------------------------------- ### Update DataCollector Initialization Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Replaces the deprecated initialize_data_collector method with direct assignment to the datacollector attribute within the Model class. ```python # Replace this: self.initialize_data_collector(...) # With this: self.datacollector = DataCollector(...) ``` -------------------------------- ### Run Model and Visualize Data Source: https://mesa.readthedocs.io/latest/tutorials/10_visualization_custom.html Executes the model for a set number of steps and generates a histogram of agent wealth distribution using Seaborn. ```python model = MoneyModel(100, 10, 10) model.run_for(20) data = model.datacollector.get_agent_vars_dataframe() g = sns.histplot(data["Wealth"], discrete=True) g.set(title="Wealth distribution", xlabel="Wealth", ylabel="Number of Agents") ``` -------------------------------- ### Implement SpaceRenderer for Visualization Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Shows the usage of the SpaceRenderer class introduced in Mesa 3.3.0 to manage model visualization backends. ```python from mesa.visualization import SolaraViz, SpaceRenderer renderer = SpaceRenderer(model, backend="matplotlib").render( agent_portrayal=agent_portrayal ) SolaraViz( model, renderer, components=[] ) ``` -------------------------------- ### Initialize and Execute Code with ConsoleManager Source: https://mesa.readthedocs.io/latest/apis/visualization.html Demonstrates how to instantiate the ConsoleManager and execute a line of Python code within the interactive environment. ```python >>> console = ConsoleManager(model=my_model) >>> console.execute_code("print('hello world')", set_input_callback) ``` -------------------------------- ### Replacing RandomActivation with AgentSet Source: https://mesa.readthedocs.io/latest/migration_guide.html RandomActivation is deprecated in Mesa 3.0. Use the 'shuffle_do' method on the AgentSet to activate agents in a random order. ```python # Replace: self.schedule = RandomActivation(self) self.schedule.step() # With: self.agents.shuffle_do("step") ``` -------------------------------- ### Initialize and Configure SpaceRenderer Source: https://mesa.readthedocs.io/latest/apis/visualization.html Demonstrates how to instantiate the SpaceRenderer with a specific backend and configure the model components using method chaining. ```python from mesa.visualization import SpaceRenderer # Initialize renderer with a backend renderer = SpaceRenderer(model=my_model, backend="matplotlib") # Configure components using method chaining renderer.setup_structure() .setup_agents(agent_portrayal=my_portrayal_func) .setup_property_layer(my_layer_style) ``` -------------------------------- ### AgentSet sequence behavior migration Source: https://mesa.readthedocs.io/latest/migration_guide.html Updates indexing and slicing operations on AgentSet objects, which are deprecated in favor of the explicit to_list() method. ```python # New approach using to_list() first_agent = model.agents.to_list()[0] some_agents = model.agents.to_list()[1:5] # Reusing list for multiple operations agent_list = model.agents.to_list() first = agent_list[0] last = agent_list[-1] ``` -------------------------------- ### Boltzmann Wealth Model Implementation (Python) Source: https://mesa.readthedocs.io/latest/examples/basic/boltzmann_wealth_model.html This Python code defines the Boltzmann Wealth Model using the Mesa framework. It includes agent creation, wealth exchange logic, and data collection for wealth distribution and the Gini coefficient. Dependencies include mesa, mesa.datacollection, mesa.discrete_space, mesa.examples.basic.boltzmann_wealth_model.agents, mesa.experimental.data_collection, and mesa.experimental.scenarios. ```python """ Boltzmann Wealth Model ===================== A simple model of wealth distribution based on the Boltzmann-Gibbs distribution. Agents move randomly on a grid, giving one unit of wealth to a random neighbor when they occupy the same cell. """ from mesa import Model from mesa.datacollection import DataCollector from mesa.discrete_space import OrthogonalMooreGrid from mesa.examples.basic.boltzmann_wealth_model.agents import MoneyAgent from mesa.experimental.data_collection import DataRecorder, DatasetConfig from mesa.experimental.scenarios import Scenario class BoltzmannScenario(Scenario): """Scenario parameters for the Boltzmann Wealth model.""" n: int = 100 width: int = 10 height: int = 10 class BoltzmannWealth(Model): """A simple model of an economy where agents exchange currency at random. All agents begin with one unit of currency, and each time step agents can give a unit of currency to another agent in the same cell. Over time, this produces a highly skewed distribution of wealth. Attributes: num_agents (int): Number of agents in the model grid (MultiGrid): The space in which agents move running (bool): Whether the model should continue running datacollector (DataCollector): Collects and stores model data """ def __init__(self, scenario: BoltzmannScenario = BoltzmannScenario): """Initialize the model. Args: scenario: BoltzmannScenario object containing model parameters. """ super().__init__(scenario=scenario) self.num_agents = scenario.n self.grid = OrthogonalMooreGrid( (scenario.width, scenario.height), random=self.random ) self.recorder = DataRecorder(self) ( self.data_registry.track_agents(self.agents, "agent_data", "wealth").record( self.recorder ) ) ( self.data_registry.track_model(self, "model_data", "gini").record( self.recorder, configuration=DatasetConfig(start_time=4, interval=2) ) ) # Set up data collection self.datacollector = DataCollector( model_reporters={"Gini": "gini"}, agent_reporters={"Wealth": "wealth"}, ) MoneyAgent.create_agents( self, self.num_agents, self.random.choices(self.grid.all_cells.cells, k=self.num_agents), ) self.running = True self.datacollector.collect(self) def step(self): self.agents.shuffle_do("step") # Activate all agents in random order self.datacollector.collect(self) # Collect data @property def gini(self): """Calculate the Gini coefficient for the model's current wealth distribution. The Gini coefficient is a measure of inequality in distributions. - A Gini of 0 represents complete equality, where all agents have equal wealth. - A Gini of 1 represents maximal inequality, where one agent has all wealth. """ agent_wealths = [agent.wealth for agent in self.agents] x = sorted(agent_wealths) n = self.num_agents # Calculate using the standard formula for Gini coefficient b = sum(xi * (n - i) for i, xi in enumerate(x)) / (n * sum(x)) return 1 + (1 / n) - 2 * b ``` -------------------------------- ### Schedule Events in Mesa 3.5.0 Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Shows how to schedule one-off and recurring events directly on the model, replacing experimental Simulator classes. ```python # One-off model.schedule_event(callback, at=50.0) model.schedule_event(callback, after=5.0) # Recurring from mesa.time import Schedule model.schedule_recurring(func, Schedule(interval=10)) model.schedule_recurring(func, Schedule(interval=1.0, count=10)) ``` -------------------------------- ### Initialize and Configure SpaceRenderer for Mesa Visualization (Python) Source: https://mesa.readthedocs.io/latest/examples/basic/boltzmann_wealth_model.html Initializes a SpaceRenderer for a Mesa model, allowing customization of the grid structure and agent portrayal using a specified backend like 'altair' or 'matplotlib'. It sets up visual properties such as grid color, dash pattern, opacity, and agent color mapping. ```python renderer = ( SpaceRenderer(model, backend="altair") .setup_structure( grid_color="black", grid_dash=[6, 2], grid_opacity=0.3 ) .setup_agents(agent_portrayal, cmap="viridis", vmin=0, vmax=10) ) renderer.render() # The post_process function is used to modify the Altair chart after it has been created. # It can be used to add legends, colorbars, or other visual elements. renderer.post_process = post_process ``` -------------------------------- ### Migrate SolaraViz Agent Visualization Source: https://mesa.readthedocs.io/latest/_sources/migration_guide.md.txt Updates the SolaraViz initialization by moving agent portrayals into the components list using the make_space_component helper function. ```python # Old approach from mesa.experimental import SolaraViz SolaraViz(model_cls, model_params, agent_portrayal=agent_portrayal) # New approach from mesa.visualization import SolaraViz, make_space_component SolaraViz(model, components=[make_space_component(agent_portrayal)]) ``` -------------------------------- ### Replicating step_type with AgentSet shuffle_do Source: https://mesa.readthedocs.io/latest/migration_guide.html Explains how to replicate the functionality of the `step_type` method from RandomActivationByType using AgentSet's shuffle_do for specific agent types. ```python self.schedule.step_type(AgentType) # Replaced with: self.agents_by_type[AgentType].shuffle_do("step") ``` -------------------------------- ### Configure Mesa Model Constructor for SolaraViz Source: https://mesa.readthedocs.io/latest/apis/visualization.html Demonstrates the correct implementation of a Mesa model constructor using keyword-only arguments. This ensures compatibility with SolaraViz's internal model instantiation process. ```python # Not supported: MyModel(10, 10) # Supported: MyModel(width=10, height=10) # Recommended implementation: class MyModel(Model): def __init__(self, *, width, height, seed=None): ... ```