Integrated interactive analysis/dashboard for agent and model data in SolaraViz
What's the problem this feature will solve? 1.)Data collection is separate from analysis Mesa collects agent-level and model-level data via DataCollector. But users must export this data to tools like pandas, numpy, or matplotlib to analyze it. 2.)No built-in exploratory analysis Users cannot quickly see distributions, scatter plots, or basic statistics inside the simulation environment. Even simple tasks like “What is the average age of agents?” or “How does an agent’s behavior evolve over time?” require writing extra code.
Describe the solution you'd like 1.)Integrated analysis inside SolaraViz: Add a built-in analysis dashboard for both agent-level and model-level data. Include commonly used functions such as histogram() → visualize distributions of agent attributes scatterplot() → track agent behavior over steps average() → compute and display model-level aggregated metrics 2.)Benefits: Saves users from exporting data to external libraries like pandas or matplotlib. Reduces boilerplate code, making exploratory modeling, debugging, and teaching faster and easier. Provides live, interactive visualization while the simulation runs
Existing scenario
import matplotlib.pyplot as plt
import pandas as pd
agent_data = model.datacollector.get_agent_vars_dataframe()
model_data = model.datacollector.get_model_vars_dataframe()
# Agent-level visualization: histogram (external library)
agent_data['Age'].hist()
plt.show()
# Model-level visualization: line plot of average age
model_data['Avg_Age'].plot()
plt.show()
purposal scenario
from data_analysis_dashboard import DataAnalysisDashboard
# Initialize with a Mesa model
dashboard = DataAnalysisDashboard(model=my_model, agent_vars=["Age"], model_vars=["Average_Age"])
# Directly call the functions
chart1 = dashboard.histogram("Age")
chart2 = dashboard.scatter("Age")
avg = dashboard.average("Average_Age")
stats = dashboard.stats("Age")
# Display charts
chart1.display()
chart2.display()
Code for implementation
from mesa.datacollection import DataCollector
import pandas as pd
import altair as alt
import solara
class DataAnalysisDashboard:
def __init__(self, model, agent_vars=None, model_vars=None, interactive=True):
"""
Dashboard for agent-level and model-level analysis.
Args:
model: Mesa model instance with a DataCollector.
agent_vars: List of agent-level variables to track.
model_vars: List of model-level variables to track.
interactive: If True, allows live updates in SolaraViz.
"""
self.model = model
self.agent_vars = agent_vars or []
self.model_vars = model_vars or []
self.interactive = interactive
def _get_agent_data(self):
"""Fetch latest agent-level data as pandas DataFrame"""
df = self.model.datacollector.get_agent_vars_dataframe()
if self.agent_vars:
df = df[self.agent_vars]
return df
def _get_model_data(self):
"""Fetch latest model-level data as pandas DataFrame"""
df = self.model.datacollector.get_model_vars_dataframe()
if self.model_vars:
df = df[self.model_vars]
return df
# -----------------------------
# Agent-level visualizations
# -----------------------------
def histogram(self, agent_var):
"""Plot a histogram of an agent-level variable"""
df = self._get_agent_data()
if agent_var not in df.columns:
raise ValueError(f"{agent_var} not in agent data")
chart = alt.Chart(df.reset_index()).mark_bar().encode(
alt.X(agent_var, bin=True),
y='count()'
).properties(title=f"Histogram of {agent_var}")
return chart
def scatter(self, agent_var, agent_id=None):
"""Scatter plot of agent-level variable vs agent_id (optional)"""
df = self._get_agent_data().reset_index()
x_field = agent_id or 'AgentID'
if x_field not in df.columns:
df[x_field] = df.index # fallback to index if agent_id not present
chart = alt.Chart(df).mark_point().encode(
x=x_field,
y=agent_var,
tooltip=list(df.columns)
).properties(title=f"Scatter plot of {agent_var}")
return chart
def line(self, agent_var):
"""Line plot of agent-level variable over steps"""
df = self._get_agent_data().reset_index()
chart = alt.Chart(df).mark_line().encode(
x='Step',
y=agent_var,
color='AgentID:N'
).properties(title=f"Line plot of {agent_var} over steps")
return chart
def stats(self, agent_var):
"""Return basic descriptive statistics for an agent-level variable"""
df = self._get_agent_data()
if agent_var not in df.columns:
raise ValueError(f"{agent_var} not in agent data")
series = df[agent_var]
return {
"mean": series.mean(),
"median": series.median(),
"variance": series.var(),
"min": series.min(),
"max": series.max(),
"quantiles": series.quantile([0.25, 0.5, 0.75]).to_dict()
}
# -----------------------------
# Model-level visualizations
# -----------------------------
def average(self, model_var):
"""Return average of a model-level variable"""
df = self._get_model_data()
if model_var not in df.columns:
raise ValueError(f"{model_var} not in model data")
return df[model_var].mean()
def plot(self, model_var):
"""Line plot of model-level variable over steps"""
df = self._get_model_data().reset_index()
chart = alt.Chart(df).mark_line().encode(
x='Step',
y=model_var
).properties(title=f"Model-level {model_var} over steps")
return chart
@quaquel @EwoutH please let me hear your thought on this
We are reworking the entire data collection, so let's wait and see how that shapes up.
I would in general advise against including this inside MESA itself. If a user wants this in her UI, it is trivial to add this. In particular with the new data collection that is being created. Remember, MESA aims to be an ABM package, not a statistics or UI package. Here, we can leverage other libraries in the python ecosystem.
Moreover, data analysis in my experience is done outside of the UI. Typically, you'll run a bunch of experiments and save these to disk for subsequent analysis. So, I don't see a strong use case for extensive UI level analysis capabilities.
Thanks @quaquel, that’s a very fair point.
I completely agree that Mesa shouldn’t try to become a statistics or full UI/analysis package, especially since the Python ecosystem already provides great tools like pandas, matplotlib, etc.
My main aim here was not to introduce new analysis functionality, but simply to make basic visualization of DataCollector output easier inside SolaraViz mainly by reducing the repetitive lines of code users often write just to quickly inspect agent/model variables during a run.
For example, instead of repeatedly exporting dataframes and writing plotting boilerplate, having small optional helper components could support quick debugging and teaching workflows.
That said, since the data collection system is being reworked, I’m happy to wait and see how the new design shapes up first.
Once that settles, I’d be glad to revisit this idea in a way that aligns with Mesa’s scope and direction.
instead of writing this
df = model.datacollector.get_agent_vars_dataframe()
df["Age"].hist()
plt.show()
Just write this
dashboard.histogram("Age")
If this idea still doesn’t align with Mesa’s direction, no problem at all — I’ll move forward accordingly.
Thanks again for the guidance.