Particle-Simulator

Python Pygame NumPy Numba License: MIT

Particle Simulator

Click Here to Watch the Full High-Resolution Timelapse Video

Core FeaturesPhysics ModelArchitectureHow to Run


This project is a high-performance 2D particle simulator engineered in Python to model complex astrophysical phenomena. The simulation universe is populated by particles governed by first-principles physics, including gravitational attraction, inelastic collisions, and thermodynamic evolution. Its architecture is meticulously designed for physical realism, computational efficiency, and numerical stability, enabling the emergence of sophisticated behaviors such as orbital mechanics, accretion disk formation, and stellar explosions.

The simulator’s exceptional performance is achieved through a sophisticated hybrid computational paradigm, combining Numba-JIT compilation of core physics kernels with vectorized NumPy operations. Visualization is rendered via Pygame, featuring a physically-inspired, temperature-based color gradient and a post-processing bloom effect for enhanced visual fidelity.


Core Features

Feature Description
N-Body Gravitational Simulation Employs a highly-optimized Barnes-Hut algorithm to simulate long-range gravitational forces with O(n log n) complexity, enabling large-scale structure formation.
First-Principles Thermodynamics Implements a multi-stage, energy-conserving collision model that correctly transforms kinetic and potential energy into thermal energy, adhering to the laws of thermodynamics.
Emergent Thermodynamic Phenomena Models thermal conduction, radiative cooling, and energetic particle explosions, allowing for the study of complex, system-wide thermodynamic behaviors.
High-Performance Hybrid Architecture Utilizes a dual spatial-partitioning scheme (QuadTree for gravity, Uniform Grid for collisions) and JIT-compiles the most demanding computational loops to native machine code.
Symplectic Numerical Integration Built upon the Velocity Verlet integration method, a symplectic integrator that ensures superior long-term energy and momentum conservation.
Configurable & Deterministic Simulation parameters are externalized to a config.json file, and all stochastic processes are governed by a single master seed for fully reproducible scientific experiments.

Physics & Simulation Model

The simulation loop is rigorously structured to maintain physical fidelity. Each discrete time step advances the system by first integrating continuous forces (gravity) and subsequently resolving discrete, instantaneous events (collisions and thermodynamic exchanges).

1. Numerical Integration: Velocity Verlet
The temporal evolution of the particle system is computed using the Velocity Verlet method. This symplectic integrator is selected for its exceptional energy and momentum conservation properties over extended simulation runs, a critical feature for maintaining the stability of orbital systems. The update sequence per tick is as follows:
2. Gravitational Interaction: Barnes-Hut Approximation
Gravitational forces are modeled using a Barnes-Hut N-body simulation, an elegant approximation that reduces the computational complexity from O(n²) to O(n log n).
3. Collision Dynamics & Energy Conservation
Collisions are modeled as discrete, inelastic events that strictly conserve the total energy of an interacting pair by transforming it between kinetic, potential, and thermal forms. The resolution process within the _resolve_collision_jit kernel is:
  1. Overlap Resolution: Spatially overlapping particles are repositioned along their normal vector, preserving the pair's center of mass.
  2. Potential Energy Accounting: This repositioning alters the inter-particle distance, changing their mutual gravitational potential energy. This pe_change is precisely calculated.
  3. Inelastic Impulse: Velocities are updated based on the coefficient_of_restitution, which models the kinetic energy dissipated during the collision.
  4. First Law of Thermodynamics: The net thermal energy (heat) generated is calculated by balancing the system's energy budget, directly enforcing the law of conservation of energy:
    heat_generated = kinetic_energy_lost - potential_energy_change
    This resulting thermal energy is then distributed between the particles, raising their internal temperatures.
4. Advanced Thermodynamic Modeling
The simulation incorporates several thermodynamic processes that contribute to emergent, system-wide behaviors:

Computational Architecture & Optimizations

1. Hybrid Spatial Partitioning
The simulation employs a sophisticated, dual-pronged strategy for spatial partitioning, leveraging the optimal data structure for each physical interaction domain:
2. Just-in-Time (JIT) Compilation with Numba
The most computationally intensive kernels of the simulation are written in a restricted, high-performance subset of Python and compiled to optimized machine code at runtime using Numba. This "zero-overhead" approach applies to:
3. Vectorization and Memory Management
All particle data is stored as NumPy arrays (Structure of Arrays), enabling vectorized operations that delegate computations to highly optimized, low-level C and Fortran libraries. To eliminate runtime overhead, memory for the QuadTree nodes is pre-allocated at the start of each frame, avoiding costly dynamic memory allocation within the simulation loop.

Visualization


How to Run the Simulation

1. Prerequisites

A working installation of Python 3.x is required. The necessary libraries can be installed via pip:

pip install pygame numpy numba

2. Configuration

Simulation behavior is controlled by two primary files:

Parameter Description
particle_count The initial number of particles in the simulation.
gravity_constant The universal gravitational constant, controlling the strength of gravity.
softening_factor A numerical stability parameter to prevent singularities at close range.
barnes_hut_theta The multipole acceptance criterion for the Barnes-Hut algorithm. Lower values increase accuracy at the cost of performance.
coefficient_of_restitution The elasticity of collisions (0.0 = perfectly inelastic, 1.0 = perfectly elastic).
thermal_damping_factor The rate of system-wide energy loss due to radiative cooling.
explosion_efficiency The fraction of a particle’s thermal energy converted to kinetic energy during an explosion.
grid_cell_size_multiplier A tuning parameter for the collision detection grid’s cell size.

3. Execution

To run the simulation, execute the main script from your terminal:

python main.py