Skip to content

GrahlmanMatthew/Sandpile-Model

Repository files navigation

🏖️ Sandpile Model

Abelian sandpile model simulation — fractal patterns emerge from a single rule: when a cell accumulates four grains it topples, sending one grain to each neighbour.

CI GitHub release

Demo

How it works

The Abelian sandpile model is a cellular automaton that demonstrates self-organised criticality. The rules are deceptively simple:

  1. Drop a grain of sand onto a cell in a 2D grid.
  2. If any cell holds four or more grains, it topples — it loses four grains and each of its four cardinal neighbours gains one.
  3. Toppling can trigger neighbours to topple in turn, producing avalanches of all sizes.
  4. Repeat from step 1.

After enough grains the system self-organises into a critical state: avalanches follow a power-law size distribution, meaning small and enormous cascades co-exist with no characteristic scale. When grains are dropped at the centre, the colour mapping of the four grain-count states (0 → deep navy, 1 → teal, 2 → coral, 3 → cream) reveals a fractal structure with 4-fold symmetry — the same pattern at every zoom level.

The model is Abelian because the final stable configuration is independent of the order in which cells fire. This makes fully vectorised parallel toppling correct: all unstable cells fire simultaneously each round and the result is identical to any sequential ordering, which is why NumPy makes this fast without sacrificing correctness.

Prerequisites

  • Python 3.12+
  • uv — install once via PowerShell:
    powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
    

Installation and setup

git clone https://github.com/GrahlmanMatthew/Sandpile-Model.git
cd Sandpile-Model
uv venv
uv pip install -e ".[dev]"

Usage

uv run python -m sandpile.main

A Pygame window opens showing the simulation in real time. See Controls below to pause or reset while it runs.

Controls

Key Action
P Pause / resume
R Reset grid and restart from 0 grains

Configuration

All settings are overridable via environment variables. Copy .env.example to .env and adjust as needed:

Variable Default Description
GRID_SIZE 256 Grid dimensions (N×N cells)
NUM_GRAINS 500000 Total grains to drop
DROP_MODE center Drop position: center or random
CELL_SIZE 3 Pixels per grid cell
RENDER_FPS 10 Display refresh rate in frames per second
DEBUG (unset) Set to any value to enable debug logging

Example — quick run with a smaller grid:

GRID_SIZE=128 NUM_GRAINS=25000 uv run python -m sandpile.main

Running the tests

uv run pytest -v

About

🏖️ Simulating the Abelian sandpile model in Python using NumPy and Pygame, where grains dropped onto a grid self-organise into a critical state that reveals stunning fractal patterns.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages