VibeSpin
VibeSpin is a Python framework for high-performance simulation and analysis of two-dimensional lattice spin models. The codebase focuses on three foundational systems: the Ising model, the XY model, and the q-state Clock model, provided as ClockSimulation (continuous XY-plus-anisotropy form) and DiscreteClockSimulation (integer state indices with cosine lookup tables). It combines Numba-accelerated Monte Carlo dynamics with an analysis suite for equilibrium observables, coarsening kinetics, and topological defect tracking.
The implementation is optimized for speed, scalability, and physical repeatability. Core kernels use Numba JIT compilation with optional multi-core parallelization, periodic boundaries are handled via precomputed index arrays, and all stochastic trajectories are fully deterministic when seeded (serial kernels; the optional parallel checkerboard kernels are not seed-reproducible because Numba seeds only the calling thread’s RNG).
Project Policies & Scope Discipline
VibeSpin enforces strict development policies for physical correctness, code quality, reproducibility, and documentation. All edits must follow the Scope Discipline: never change, rewrite, or delete code/text unrelated to the current task. See AGENTS.md for the full list of mandatory development policies.
Reference Policy
All references used in VibeSpin are listed in BIBLIOGRAPHY.md. Reference policy and link validation are enforced as described in AGENTS.md.
Background and References
The Ising model [1], XY model [2], and q-state Clock model [3] are canonical systems in statistical physics for studying phase transitions, critical phenomena, and topological defects. Monte Carlo methods, especially the Metropolis-Hastings algorithm [4], are standard for simulating these models. The Wolff cluster algorithm [5] is highly effective near criticality, reducing autocorrelation times by exploiting collective spin updates. For a thorough introduction to these models and algorithms, see the references below.
Scope and Methods
VibeSpin supports three update schemes tailored to specific physical regimes. Checkerboard Updates maximize equilibrium throughput via SIMD vectorization and multi-core execution. Random Site Selection is mandatory for non-equilibrium kinetics and aging studies, where preserving the stochastic trajectory is essential for physical validity. The Wolff Cluster Algorithm provides high efficiency near critical temperatures by mitigating critical slowing down through collective spin updates.
The framework provides a full suite of diagnostics for physical analysis. Thermodynamic measurements include magnetization magnitude, energy per site, susceptibility, and specific heat. Spatial correlations are analyzed through radially averaged spin-spin correlation functions and 2D structure factor mapping. For topological systems, the engine supports directed phase-wrapping for vorticity maps, vortex density tracking, and helicity modulus calculations. Kinetics studies use integrated autocorrelation times and phase-ordering growth law extraction to quantify the temporal evolution of the system.
Installation
The project runs in a local virtual environment managed by uv. uv.lock pins every dependency, and .python-version selects Python 3.12, which uv downloads if it is not already installed. On Windows, use WSL and clone the repository into the Linux file system (for example ~/code/VibeSpin) rather than under /mnt/c, where file access is slow and permissions behave differently.
curl -LsSf https://astral.sh/uv/install.sh | sh # once per machine
uv sync --all-extras
uv run pre-commit install --hook-type pre-commit --hook-type pre-push
uv sync creates .venv/ in the repository and installs VibeSpin in editable mode with the development, notebook, and documentation extras. Prefix commands with uv run, or activate the environment with source .venv/bin/activate. JupyterLab starts with uv run jupyter lab. In VS Code, select .venv/bin/python as the interpreter; under WSL, open the folder through the WSL extension first.
GitHub access needs no project-specific setup: use gh auth login or an SSH key in ~/.ssh, on Windows inside WSL rather than in Windows itself.
Without uv, the same pinned set installs with pip from requirements.txt, which a pre-commit hook exports from uv.lock:
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pip install -e . --no-deps
pre-commit install --hook-type pre-commit --hook-type pre-push
To change a dependency, edit pyproject.toml or run uv lock --upgrade-package <name>, then commit uv.lock together with the regenerated requirements.txt. CI installs from uv.lock and fails if the two files disagree.
The repository enforces documentation consistency at both commit and push time. The pre-push hook runs link validation, API docs sync checks, and a Sphinx HTML build with warnings treated as errors.
Benchmarking & Performance
VibeSpin includes a performance analysis suite that measures throughput and identifies hardware-bound scaling regimes. The benchmark tool quantifies simulation efficiency in terms of sweeps per second and nanoseconds per site, while also isolating the overhead of thermodynamic and topological measurements from the pure simulation time. This granularity allows for deep algorithmic profiling across different lattice sizes and update schemes.
# Run a scaling benchmark across multiple lattice sizes
python scripts/benchmarks/throughput.py --sizes 128 256 512 1024 --sweeps 100
Key engineering features ensure high performance across all models. Checkerboard updates are distributed across multiple CPU cores using Numba parallelization. For q-state clock models, the discrete representation replaces trigonometric evaluations with integer lookups, providing up to a ~2.5x speedup over continuous variants. Benchmarking results consistently isolate the simulation kernel performance, enabling a clear understanding of numerical cost in various regimes.
Typical Usage
Regenerate every dataset the notebooks read, so that they render published-quality figures instead of their inline fallbacks:
python -m scripts.generate_all # production parameters, about an hour on four cores
python -m scripts.generate_all --quick # the same eighteen scripts in about a minute, as a smoke test
Run an individual experiment instead. Launch an equilibrium temperature sweep for the XY model:
python scripts/xy/temperature_sweep.py --size 64 --t-min 0.2 --t-max 1.5 --t-points 20
Temperature sweep scripts use Two-Start Convergence equilibration: for every temperature/seed point, two independent simulations (one starting from a random disordered state and one from a fully ordered state) are evolved in parallel. The burn-in continues in chunks (defined by --eq-probe-steps) until both smoothed magnetization traces pass a mutual cross-band test: the random-start trace must lie within a band of \(\pm k\) standard deviations of the ordered-start tail mean, and vice versa. A sigma floor prevents band collapse when either trace is nearly variance-free.
The two starts use independent seeds; with a shared seed they draw identical random numbers and their traces become correlated, which lets them pass the cross-band test without having relaxed independently. Below the ordering temperature of models with a discrete order parameter (Ising, discrete clock), the protocol adds Quasi-Steady Stuck Detection: if the random-start trace stays stranded on a metastable plateau while the ordered-start trace has settled, the point is accepted and measured on the ordered start. Elsewhere, and for the XY model at any temperature, stuck detection is off, because the detector cannot distinguish a stranded run from one that is still relaxing slowly. To maximize throughput, individual points are parallelized across the worker pool, ensuring full CPU utilization even for single-seed sweeps. The --eq-max-steps flag provides a hard cap on the total equilibration time; a point that reaches it without converging is stored as NaN rather than measured.
Investigate phase-ordering kinetics in the Ising model using random-site updates:
python scripts/ising/ordering_kinetics.py --size 512 --max-steps 5000
Generate a visual ordering evolution for the XY model:
python scripts/xy/ordering_evolution.py --size 256 --targets 1 10 100 1000 5000
Compare Wolff cluster and Metropolis efficiency near the Ising critical point:
python scripts/ising/wolff_efficiency.py --size 64 --t-min 1.8 --t-max 3.2 --t-points 20
Measure the dynamical critical exponent \(z\) at \(T_c\):
python scripts/ising/measure_z.py --sizes 16 32 48 64 96 128 --n-seeds 10
Development Guidance
VibeSpin enforces engineering and physical standards. All update algorithms must strictly satisfy detailed balance and ergodicity, whether via the Metropolis-Hastings acceptance rule (for single-spin updates) or the Fortuin-Kasteleyn bond construction (for Wolff cluster updates).
Performance-critical kernels are implemented with Numba JIT compilation to minimize execution time and memory allocation. These kernels use @njit(cache=True, fastmath=True) and avoid expensive modulo operations by using precomputed neighbor index arrays. To maintain reproducibility, models synchronize Numba’s internal random number generator with the project seed.
Verification Suite
Before proposing changes, ensure all verification checks pass using uv run (or standard environment commands):
uv run pytest
uv run ruff check .
uv run mypy --explicit-package-bases models/ utils/ scripts/
uv run pre-commit run --all-files --hook-stage pre-push
Documentation
Full documentation is available at https://manganite.github.io/VibeSpin/.
To build the documentation locally:
uv run make -C docs html
Sphinx Setup Notes
The documentation stack uses Sphinx with MyST Markdown and nbsphinx for notebook pages. Its dependencies are part of the docs extra, which uv sync --all-extras installs.
Notebook rendering requires Pandoc. The docs configuration includes a fallback that uses the bundled binary from pypandoc-binary when a system pandoc executable is not available, so normal builds should work without manual Pandoc installation.
Docs Troubleshooting
If make html fails, resynchronize the environment and rebuild:
uv sync --all-extras
uv run make -C docs html
If this still fails, check that the selected interpreter is the project virtual environment at .venv/bin/python.
For deeper insights, refer to the source guides:
Physics and Algorithm Guide: Detailed explanation of physical models, observables, and algorithm prerequisites.
Architecture and Developer Guide: Technical blueprint, engineering rationale, and testing strategy.
Scripts Catalog: Complete catalog of entry-point scripts.
Agent Instruction Guide: Mandatory technical constraints for AI Agents.
Performance Benchmarks: Detailed scaling analysis.
Ising Temperature Sweep: Equilibrium thermodynamics of the 2D Ising model across the Onsager transition.
XY Temperature Sweep: Thermodynamic sweep across the BKT crossover for the XY model.
Clock Temperature Sweep: Temperature sweep for the q-state clock model showing the two-crossover regime structure.
BKT Transition: Vortex density, helicity modulus, and correlation functions across the BKT transition.
Correlation and Coarsening: Equilibrium correlation functions and non-equilibrium coarsening dynamics across all three models.
Ising Relaxation and Autocorrelation Analysis: Comparative analysis of equilibration and autocorrelation across update schemes.
Dynamic Critical Exponents: Scaling analysis of autocorrelation times at criticality.
Wolff Efficiency: Quantitative comparison of Metropolis and Wolff cluster algorithms near criticality.
Project Context
VibeSpin was developed using AI-assisted scientific coding workflows. The framework demonstrates how high-level physical design and validation can be accelerated through iterative modeling, benchmarking, and automated testing.
For detailed procedural instructions, see Agent Instruction Guide.
Bibliography
[1] L. Onsager, “Crystal Statistics. I. A Two-Dimensional Model with an Order-Disorder Transition,” Physical Review, vol. 65, no. 3-4, pp. 117–149, 1944. APS
[2] J. M. Kosterlitz and D. J. Thouless, “Ordering, metastability and phase transitions in two-dimensional systems,” Journal of Physics C: Solid State Physics, vol. 6, no. 7, pp. 1181–1203, 1973. IOP
[3] J. V. José, L. P. Kadanoff, S. Kirkpatrick, and D. R. Nelson, “Renormalization, vortices, and symmetry-breaking perturbations in the two-dimensional planar model,” Physical Review B 16, 1217-1241 (1977). APS
[4] W. K. Hastings, “Monte Carlo sampling methods using Markov chains and their applications,” Biometrika, vol. 57, no. 1, pp. 97–109, 1970. Oxford Academic Open Access
[5] U. Wolff, “Collective Monte Carlo Updating for Spin Systems,” Physical Review Letters, vol. 62, no. 4, pp. 361–364, 1989. APS