Status: stable, Python 3.12+, release 1.5.2. Every public name has a stability level
(docs/api_stability.toml): stable names follow semantic versioning and the deprecation policy;
the newest packages are marked provisional. The current version is modelly.__version__.
pip install modelly-abm
python -c "import modelly; print(modelly.__version__)" # the import name is modelly
Then run the wealth-exchange example,
which prints its Gini coefficient.
Vision
Agent-based models are how researchers study systems whose behaviour emerges from many
interacting parts: markets, epidemics, ecosystems, cities, opinions. The models are easy to
describe and hard to keep correct, reproducible and fast. Modelly exists to remove that gap.
What we are building
- A research instrument, not a toy. Every run is seeded, every parameter lives in a typed
scenario, every dataset lands in pandas. A result you got once is a result you can get again.
- Fast by construction. The hot paths of a simulation (activating agents, moving them,
looking up neighbours, recording data) are measured, benchmarked before every release, and written so the cost
per agent-step stays flat as models grow. Performance is a feature with a test, not a hope.
- Small, readable modules. A researcher should be able to open any file and understand it in
one sitting. Files stay under 300 lines, functions under 25, and the rule is enforced by a script,
not by goodwill. The Pelloux guidelines are the contract.
- One mental model from notebook to cluster. The same scenario object drives a quick look in a
notebook, a browser visualization, a parameter sweep and a batch of replications.
Where we are going. The engine keeps one Python object per agent, which is what makes models
easy to write, and moves the heavy lifting into arrays: Column attributes give the model a numpy
view of every agent, continuous space answers neighbour queries for the whole population with one
KD-tree, vectorised step phases act on the whole population, and one model can be split across
processes or run its columns on a GPU (Scale out and connect).
The performance audit records what has been done and what is next.
Why Modelly
Modelly gives you the boring, load-bearing parts as small composable objects, so your model file
reads like the description of the system instead of the plumbing around it:
| Building block |
What it gives you |
| Scenario |
Parameters as a typed class: one run, one seed, one config object |
| Agents |
Agent classes with a step(), grouped in ordered AgentSets |
| Columns |
Attributes stored in numpy arrays, readable per agent and as a whole |
| Space |
Orthogonal / hexagonal grids, cells, networks, Voronoi meshes, continuous space |
| Time |
Discrete ticks, events, generators and priorities in one scheduler |
| Data |
Reporters and datasets that land in pandas, ready to plot |
| Front end |
Browser visualization (Solara), static charts, notebooks |
No global state, no hidden step order, no bespoke loops: reproducibility is the default.
Install
Modelly requires Python 3.12+ and is published on PyPI as
modelly-abm.
python -m venv .venv && source .venv/bin/activate
pip install modelly-abm
Add extras for what you need:
pip install "modelly-abm[viz]" # + solara, matplotlib, altair
pip install "modelly-abm[network]" # + networkx
pip install "modelly-abm[rec]" # network + viz: what the bundled examples need
pip install "modelly-abm[geo]" # + geopandas, rasterio, pyproj: geographic space
pip install "modelly-abm[distributed]" # + mpi4py: split runs over MPI (dask, ray extras too)
pip install "modelly-abm[gpu]" # + CuPy (CUDA); "modelly-abm[diff]" adds JAX, CPU everywhere
pip install "modelly-abm[calibrate]" # + optuna; xarray, mqtt and kafka extras likewise
pip install "modelly-abm[experiments]" # + pyarrow, duckdb: sweeps, calibration's run store
pip install "modelly-abm[decide]" # + optuna: intervention optimisation (modelly.decide)
To work on Modelly itself, install from a clone instead: see Development.
To depend on Modelly from your own project, add it to pyproject.toml (the distribution is
modelly-abm, the import is modelly):
dependencies = ["modelly-abm>=1.5"]
The full walkthrough, from an empty folder to a tested and replicated model, is
docs/using_modelly_in_your_project.md.
A model in 30 seconds
Agents wander a grid and hand one unit of wealth to a random cellmate. Inequality emerges.
The same code ships as example.py.
from modelly import Model
from modelly.space import CellAgent, OrthogonalMooreGrid
from modelly.scenarios import Scenario
class WealthScenario(Scenario):
"""Everything that can vary between runs lives here."""
n: int = 120
width: int = 12
height: int = 12
class MoneyAgent(CellAgent):
def __init__(self, model, cell):
super().__init__(model)
self.cell = cell
self.wealth = 1
def step(self):
self.cell = self.cell.neighborhood.select_random_cell()
cellmates = [a for a in self.cell.agents if a is not self]
if self.wealth > 0 and cellmates:
self.random.choice(cellmates).wealth += 1
self.wealth -= 1
class WealthModel(Model):
def __init__(self, scenario: WealthScenario = WealthScenario):
super().__init__(scenario=scenario)
self.grid = OrthogonalMooreGrid(
(scenario.width, scenario.height), random=self.random
)
MoneyAgent.create_agents(
self,
scenario.n,
self.random.choices(self.grid.all_cells.cells, k=scenario.n),
)
def step(self):
self.agents.shuffle_do("step") # every agent, in random order
@property
def gini(self):
x = sorted(a.wealth for a in self.agents)
n = len(x)
weighted = sum(xi * (n - i) for i, xi in enumerate(x))
return 1 + 1 / n - 2 * weighted / (n * sum(x))
model = WealthModel()
for _ in range(100):
model.step()
print(model.gini) # 0.0 at the start, about 0.6 after 100 ticks
Three pieces, and nothing else: a scenario of inputs, agents that know one thing each,
and a model that owns the world and advances it.
Record it, then look at it
from modelly.data.collector import DataCollector
class WealthModel(Model):
def __init__(self, scenario: WealthScenario = WealthScenario):
super().__init__(scenario=scenario)
# ... grid and agents as above ...
self.datacollector = DataCollector(
model_reporters={"Gini": "gini"}, # anything reachable from the model
agent_reporters={"Wealth": "wealth"}, # anything on each agent
)
def step(self):
self.agents.shuffle_do("step")
self.datacollector.collect(self) # one row per tick
model_vars = model.datacollector.get_model_vars_dataframe() # Gini per tick
agent_vars = model.datacollector.get_agent_vars_dataframe() # wealth per agent per tick
agent_vars.groupby("Step")["Wealth"].mean().plot()
Both frames are plain pandas, so everything you already know how to do keeps working.
Attribute reporters are gathered in C (operator.attrgetter), so a string reporter is the fast
path, not just the convenient one.
Vectorise the bulk work
An agent-based model has two kinds of work: what one agent does in its step, which is Python
by nature, and what the model does to all agents at once (aggregate, filter, record, update),
which should be numpy. Declare a Column and the attribute lives in a model-owned array: the
agent keeps reading and writing it as before, and the model gets a zero-copy view of everyone.
import numpy as np
from modelly import Agent, Column, Model
class MoneyAgent(Agent):
wealth = Column(int, default=1) # one numpy array for the whole class
def step(self):
other = self.random.choice(self.model.agents.to_list())
if self.wealth > 0: # per-agent access works as before
other.wealth += 1
self.wealth -= 1
class WealthModel(Model):
@property
def gini(self):
x = np.sort(self.columns[MoneyAgent].wealth) # view, no copy
n = len(x)
return 1 + 1 / n - 2 * np.sum(x * (n - np.arange(n))) / (n * x.sum())
def tax(self):
w = self.columns[MoneyAgent].wealth
w[w > 10] -= 1 # bulk update, in place
def rich(self):
table = self.columns[MoneyAgent]
return table.where(table.wealth > 10) # an AgentSet
Nothing else changes: model.agents, shuffle_do, DataCollector and the examples work the
same, and attribute reporters on a column are recorded straight from the array. Measured on
10,000 agents:
| Operation |
Plain attribute |
Column |
| Gini coefficient |
1.09 ms |
0.03 ms |
Count agents with wealth > 0 |
0.94 ms |
0.008 ms |
| Mean wealth |
0.47 ms |
0.009 ms |
Decrement every wealth > 5 |
0.15 ms |
0.004 ms |
DataCollector.collect, one reporter |
0.95 ms |
0.46 ms |
One agent.wealth read inside step |
6 ns |
27 ns |
The last row is the trade-off: use columns for attributes you aggregate, filter, record or update
in bulk; a plain attribute is still the cheapest thing to touch inside step. In the Boltzmann
example the object loop is unchanged within noise while the model-level work is 30x cheaper.
The whole population at once
Two more operations run over everyone in one call, so a model can move its population-wide phases
out of the per-agent loop:
# A whole-population step for the sheep: decrement, die, reproduce, no per-agent loop.
table = self.columns[Sheep]
table.energy -= 1
table.remove_where(table.energy < 0)
table.do_where(table.draw(0.04), "spawn_offspring") # one seeded draw per sheep
# Continuous space: one KD-tree answers the whole flock, same snapshot for all.
lists = self.space.neighbors_within(radius=5.0)
for boid in self.agents:
boid.neighbors = lists[boid]
draw uses the model's seeded numpy generator, so the run stays reproducible. neighbors_within
is O(n log n) for the whole flock instead of one O(n) scan per agent, is periodic on a torus, and
is cached while no position changes. The Boids example uses it: 2,000 boids go from 98 ms to
42 ms per step.
Replications in parallel
from modelly.scenarios import RunConfiguration, run_scenarios
scenarios = WealthScenario(n=5000, rng=1).spawn_replications(32) # 32 independent seeds
store = run_scenarios(scenarios, RunConfiguration(WealthModel, until=200), workers=8)
Each replication carries its own seed derived from the base scenario, so the sweep is
reproducible; workers= spreads it over processes.
For a plain factorial experiment, run_grid is the one-call version: every combination times
the replicates, each run with its own seed, results in design order whatever the number of
workers, so the DataFrame is identical to the sequential loop's.
from modelly import run_grid
def season(task): # a notebook function works: on Linux the workers are forked
model = Orchard(budget=task["budget"], invasion=task["invasion"], rng=task["seed"])
model.run_for(100)
return {"harvested": model.harvested, "rotten": model.rotten}
results = run_grid(
season, {"budget": [0, 150, 300, 600], "invasion": [3, 10, 30]}, replicates=3
)
Populations as cohorts
When individuals in the same state face the same probabilities (an insect's stage, age and
sex), one row with a count replaces them all, and each per-individual draw becomes one
binomial draw per row with exactly the same law. CohortTable holds such a population with no
agent objects; the stage-structured playbook runs 251x faster than its individual Mesa 2.3
version and agrees with it statistically.
from modelly import CohortTable
insects = CohortTable(model.rng, stage=np.int8, age=np.int16, female=bool)
insects.add(500, stage=EGG)
insects.thin(daily_survival[insects["stage"]]) # Binomial(count, s) per row
insects.split(0.5, where=emerging, stage=ADULT, female=True) # sex at emergence
eggs = insects.draw(lay_prob, where=mature_females).sum() * clutch
Scale out and connect
Each item keeps the authoring model above; each number is measured on one laptop and recorded
in the docs it links to, shortfalls included.
- Split runs (
modelly.distributed): one model across processes with MPI, Dask or locally,
byte-identical to a single process at 1, 2, 4 and 16 partitions; weak scaling on a 16-core
laptop stays far below a cluster's, 85% at 2 workers and 5% at 16 (guide).
- GPU backend (
modelly.gpu): columns, cohorts and cell operations on CuPy or JAX, same
integer state as numpy; 34x faster at 10 million agents on a laptop RTX 5050, slower at
20,000 (guide).
- Differentiable models (
modelly.diff): JAX-traced phases and gradient calibration that
recovers known parameters on two zoo models (guide).
- Live data and assimilation (
modelly.stream): sources, replicate ensembles, a particle
filter (nowcast error 5 people against 69 unfiltered on the tutorial's synthetic truth) and an
ensemble Kalman filter (tutorial).
- Fields and ODEs (
modelly.couple): diffusion, advection and decay on a grid layer, ODE and
stock-flow parts, a checked coupling schedule; mass conserved to round-off (guide).
- Emulators and history matching (
modelly.emulate): Gaussian-process and neural emulators,
active learning, waves that shrink the plausible space from 17% to 2.5% on the SEIR zoo model (guide).
- Synthetic populations (
modelly.population): people from census tables, households,
places and contact networks; three zoo models on real Burlington data, licences bundled (guide).
- A model in the browser:
modelly export-web model.py:Model writes a static site that runs
it in Pyodide; every bundled model verified in headless Chromium; first load 8 s on a 50 Mbit/s
line for a model without scipy, 21 s on a fast 4G profile (guide).
- Studio II: ensemble, assimilation, experiment, analysis and WebGL map tabs, a session
recorded as a script that reproduces the run (guide).
- Tools: a NetLogo translator for a stated subset (guide),
modelly lint --lsp for editors, pre-commit hooks, 21 lint rules, strict typing on the
research packages.
New in 1.5: ecosystem and collaboration