AgentPy: Pythonic Agent-Based Modeling for Social System Simulation and Parameter Exploration
Agent-based modeling (ABM) has long been the domain of specialized platforms—NetLogo, Repast, MASON—each with its own syntax and ecosystem. AgentPy (version 0.1+) breaks from that tradition by embedding ABM natively within the Python scientific stack, giving researchers direct access to NumPy arrays, pandas DataFrames, NetworkX graphs, and Jupyter notebooks without any bridging layer. For social scientists and computational modelers who already live in Python, AgentPy offers a compelling alternative that trades raw performance for rapid iteration and seamless integration.
Core Architecture
AgentPy organizes a simulation around four primary objects:
| Object | Role |
|---|---|
ap.Agent |
Base class for individual actors; subclass to add attributes and step logic |
ap.AgentList |
Vectorized container; apply methods across all agents in one call |
ap.Grid / ap.Network |
Spatial and network environments |
ap.Model |
Orchestrates setup, step, and end phases; holds the parameter dict |
The AgentList is the library's key performance lever. Rather than iterating agents in a Python loop, operations are dispatched across the list and—where possible—delegated to NumPy, keeping overhead low for models with tens of thousands of agents.
import agentpy as ap
class WealthAgent(ap.Agent):
def setup(self):
self.wealth = 1
def give_money(self):
if self.wealth > 0:
partner = self.model.agents.random()
self.wealth -= 1
partner.wealth += 1
class WealthModel(ap.Model):
def setup(self):
self.agents = ap.AgentList(self, self.p.n_agents, WealthAgent)
def step(self):
self.agents.give_money()
def end(self):
self.agents.record('wealth')
This Boltzmann wealth redistribution model—a canonical ABM benchmark—runs in under 20 lines of idiomatic Python.
Parameter Sweeps with ap.Sample and ap.Experiment
Where AgentPy genuinely excels is in systematic parameter exploration. The ap.Experiment class wraps any model with a full factorial or sampled parameter space, runs replicates in parallel (via multiprocessing), and returns a tidy ap.DataDict that converts directly to a pandas DataFrame.
parameters = {
'n_agents': 100,
'steps': ap.Values(50, 100, 200), # discrete sweep
'p_give': ap.Range(0.1, 0.9), # continuous range for Saltelli sampling
}
sample = ap.Sample(parameters, n=64, method='saltelli')
exp = ap.Experiment(WealthModel, sample, iterations=5, record=True)
results = exp.run(n_jobs=-1) # uses all CPU cores
The saltelli method generates Sobol quasi-random sequences, enabling variance-based global sensitivity analysis (Saltelli et al., 2010) directly from the results object—a workflow that would require substantial glue code in NetLogo or Repast.
Network and Spatial Environments
AgentPy integrates with NetworkX for graph-based social structures. Agents can be placed on any NetworkX graph, and the ap.Network object exposes neighbor queries that respect the underlying topology:
class OpinionAgent(ap.Agent):
def setup(self):
self.opinion = self.model.random.uniform(-1, 1)
def update(self):
neighbors = self.network.neighbors(self)
if len(neighbors) > 0:
avg = sum(n.opinion for n in neighbors) / len(neighbors)
self.opinion += self.p.mu * (avg - self.opinion) # bounded confidence
Placing agents on a Watts-Strogatz small-world graph requires a single call:
G = nx.watts_strogatz_graph(n=200, k=6, p=0.1)
self.network = ap.Network(self, G)
self.network.add_agents(self.agents)
This makes it straightforward to compare opinion dynamics across Erdős-Rényi random graphs, scale-free Barabási-Albert networks, and empirical social network datasets—a common research design in computational social science.
Visualization and Analysis
AgentPy ships with ap.gridplot for spatial snapshots and integrates with Matplotlib for time-series plots. For interactive exploration, models run inside Jupyter notebooks with live output via IPython.display. The DataDict structure stores agent-level records, model-level variables, and parameter metadata together, making it easy to reproduce any run from its saved state.
For sensitivity analysis, AgentPy's results integrate directly with the SALib library:
from SALib.analyze import sobol
Si = sobol.analyze(problem, results['variables']['WealthModel']['gini'].values)
This end-to-end pipeline—model definition → parameter sampling → parallel execution → sensitivity analysis—is available without leaving the Python ecosystem.
Benchmarks and Practical Limits
AgentPy is not designed for million-agent simulations. Benchmarks on a modern workstation show comfortable performance up to ~50,000 agents per step at 10 Hz; beyond that, FLAME GPU 2 or MASON are better choices. For the typical social science use case—hundreds to low thousands of agents, dozens of parameters, hundreds of replicates—AgentPy's overhead is negligible and its productivity advantages are substantial.
When to Choose AgentPy
- Rapid prototyping: The Pythonic API reduces model-to-results time significantly compared to Java-based platforms.
- Sensitivity analysis: Built-in Saltelli sampling and SALib integration make global sensitivity analysis a first-class workflow.
- Network models: Native NetworkX support covers the full range of social network topologies without custom adapters.
- Reproducible research: Jupyter integration and
DataDictserialization support open, reproducible workflows. - Teaching: Clean syntax and minimal boilerplate make AgentPy accessible for graduate courses in computational social science.



Further Resources
- AgentPy Documentation — full API reference and tutorials
- AgentPy GitHub Repository — source code and issue tracker
- SALib: Sensitivity Analysis Library — Saltelli, Sobol, and Morris methods
- NetworkX Documentation — graph construction and analysis
- Foramitti, J. (2021). AgentPy: A package for agent-based modeling in Python. Journal of Open Source Software, 6(62), 3065. https://doi.org/10.21105/joss.03065
AgentPy occupies a productive niche between the simplicity of Mesa and the scalability of Repast4Py. For researchers who need rigorous parameter exploration, network-aware social dynamics, and seamless integration with the Python data science ecosystem, it is a tool worth serious consideration.