Skip to content

Repository files navigation

🧲 High-Performance 2D Ising Model Simulation

Python Streamlit Numba

Live Demo: Click here to view the Dashboard

📖 Overview

An interactive Monte Carlo simulation of ferromagnetic phase transitions using the Metropolis algorithm.

While the core logic is based on Statistical Mechanics, the primary goal of this project was Software Performance Engineering. It demonstrates how to optimize stochastic Python simulations to run at C++ speeds using JIT compilation and parallel computing.


🚀 Engineering Highlights

1️⃣ Baseline Implementation vs. Optimization

  • The Problem: Pure Python loops differ significanly in performance compared to compiled languages due to the Global Interpreter Lock (GIL) and dynamic typing.
  • The Solution: I architected a transition from a naive implementation to a fully optimized engine.

2️⃣ JIT Compilation (Numba)

  • Applied @jit(nopython=True) to compile the critical Metropolis loop into LLVM Machine Code.
  • Bypassed the Python Interpreter overhead entirely for the heavy math operations.
  • Result: Achieved a 67x speedup over the baseline.

3️⃣ Parallelization (Multi-Threading)

  • Standard Monte Carlo simulations are sequential and hard to parallelize due to data dependencies.
  • Algorithm: Implemented Checkerboard (Red-Black) Decomposition. This splits the grid into two independent sets, allowing safe concurrent updates.
  • Tech: leveraged numba.prange to utilize all CPU cores without race conditions.
  • Result: Achieved a massive 315x speedup on an 8-core CPU.

4️⃣ Memory Optimization

  • Precomputed Boltzmann Factors: Replaced expensive np.exp() calls inside the loop with a pre-calculated Lookup Table ($O(1)$ access).
  • Zero-Allocation Loops: Refactored logic to use scalar variables on the Stack instead of allocating new Lists on the Heap, reducing Garbage Collection pauses.

📊 Benchmark Results

Version Implementation Detail Spins/sec Speedup
Baseline Pure Python (Single Thread) ~1.3 M 1x
Optimized Numba JIT (Single Thread) ~87 M 67x
Parallel Numba JIT + AVX + Multithreading ~410 M 315x

> Hardware: Intel i7-12700H | 8 Threads | 256x256 Grid | 10,000 Sweeps


🖥️ Interactive Dashboard

Built with Streamlit to visualize the physics in real-time.

  • Real-time Visualization: Heatmap rendering of spin states.
  • Controls: Adjust Temperature ($T$) and Grid Size on the fly.
  • Performance Metrics: Live FPS counter and M-FLIPS (Million Flips Per Second) monitor.

🛠️ How to Run Locally

  1. Clone the repository:
    git clone https://github.com/samdanisayam/ising-model-performance.git
    cd ising-model-performance

Releases

Packages

Contributors

Languages