Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Cellular Automata Simulation Framework

A modular, high-performance scientific simulation framework for exploring discrete dynamical systems through two-dimensional cellular automata. Built on NumPy with fully vectorized update kernels for efficient large-scale simulations, supporting synchronous and stochastic asynchronous updates, dynamic real-time parameter tuning, and multi-model coupled overlays.


🏗️ Architecture Overview

The framework follows a strict object-oriented design where models inherit from a common interface, separating lattice state management, transition rules, visualization, and statistical analysis.

classDiagram
    class Lattice {
        +Tuple shape
        +BoundaryCondition boundary
        +np.ndarray state
        +initialize_random(states, probabilities)
        +initialize_from_array(array)
        +initialize_from_image(path, state_map)
        +initialize_from_function(func)
        +get_neighbor_counts(neighborhood, states)
        +get_padded_state(pad_width)
        +save_as_image(filepath, cmap)
    }

    class CellularAutomaton {
        <<Abstract>>
        +Lattice lattice
        +str update_mode
        +float async_update_rate
        +int generation
        +initialize()**
        +step()**
        +update_lattice(new_state)
        +get_observables()**
        +run(steps, record)
        +reset()
    }

    class InteractingCA {
        <<Abstract>>
        +step()**
    }

    CellularAutomaton <|-- GameOfLife
    CellularAutomaton <|-- ForestFire
    CellularAutomaton <|-- EpidemicSpread
    CellularAutomaton <|-- CustomCA
    CellularAutomaton <|-- InteractingCA
    InteractingCA <|-- WildfireEpidemicCA
    CellularAutomaton *-- Lattice
Loading

✨ Features

💻 Core Engine

  • Fully Vectorized Update Kernels: Updates lattices simultaneously using NumPy array slicing and convolutions, enabling $\sim 1000+$ generations/second on $500 \times 500$ grids.
  • Flexible Boundary Conditions:
    • Fixed: Border cells take a constant value (e.g. Dirichlet condition).
    • Periodic (Toroidal): Wraps boundaries around (top-to-bottom, left-to-right).
    • Reflective: Mirrors boundary values back into the lattice.
  • Multiple Neighborhoods: Native vectorized Moore (8-cell) and von Neumann (4-cell) neighborhood support.
  • Asynchronous Stochastic Updates: Toggles stochastic updates where cells update stochastically in random order at each timestep based on a configurable update rate.
  • Lattice Image Exports: Native color-mapped PNG/JPEG generation directly from lattice states without Matplotlib overhead.

🔬 Built-in Scientific Models

  1. Conway's Game of Life: Classic birth/survival/overpopulation rules generating emergent gliders, oscillators, and still lives.
  2. Forest Fire Spread: Simulations of fire fronts over landscapes with wind direction vector biases, fuel growth, spontaneous ignition, and fuel regeneration.
  3. Epidemic Spread (SIR): Susceptible-Infected-Recovered dynamics featuring vaccination and quarantine interventions, waning immunity timescales, and cluster outbreaks.
  4. Interacting Multi-Model Overlays: Multi-layer model orchestration (WildfireEpidemicCA) showcasing feedback loops where active wildfires boost local disease infection probabilities due to smoke stress, while quarantined/infected humans hamper firefighting capabilities, raising local fire spread rates.

📊 Statistical Analysis

  • Cluster Analysis: Connected component labeling with size distributions, mean cluster sizes, and standard deviations.
  • Fractal Dimension: Estimations of pattern boundary fractal dimensions using box-counting and pair-correlation sums.
  • Correlation Lengths: Radial spatial autocorrelation computation via Fast Fourier Transforms (FFT).
  • Percolation Analysis: Determines horizontal and vertical spanning clusters for critical phenomena and phase transitions.

🎛️ Dynamic Interactive Visualization

  • Dark Theme Interface: Sleek dark theme mapping distinct color profiles to model states.
  • Control Center: Real-time Play/Pause, Step-by-Step, Speed control, and Reset.
  • On-The-Fly Slider Panels: Automatic GUI parameter sliders. Tweak infection rates, fire spread probabilities, and wind vectors in real-time to watch transitions dynamically without restarting the simulation.

🚀 Installation

# Clone the repository
git clone https://github.com/username/cellular_automata_framework.git
cd cellular_automata_framework

# Install requirements
pip install -r requirements.txt

📖 Quick Start

1. Conway's Game of Life (Interactive)

from ca_framework import Lattice, BoundaryCondition, GameOfLife, CAVisualizer

# Create a periodic lattice
lattice = Lattice((150, 150), boundary=BoundaryCondition.PERIODIC)

# Initialize Game of Life with a Gosper Glider Gun
ca = GameOfLife(lattice)
ca.initialize(pattern='gosper')

# Start real-time visualization with statistics
viz = CAVisualizer(ca, show_stats=True)
viz.start()

2. Coupled Wildfire-Epidemic Interacting Overlay

from ca_framework import Lattice, WildfireEpidemicCA, CAVisualizer

lattice = Lattice((120, 120))
ca = WildfireEpidemicCA(
    lattice,
    p_burn=0.45,
    p_infect=0.15,
    p_recover=0.03,
    smoke_infection_boost=0.35, # wildfires cause smoke-induced health stress
    infection_fire_boost=2.5    # sick populations can't clear brush/fight fire
)
ca.initialize(tree_density=0.65, initial_infected=0.01)

# Visualizer renders a custom 20-color blended state layout with parameter sliders
viz = CAVisualizer(ca)
viz.start()

3. Asynchronous Stochastic Simulation

# Enable stochastic asynchronous updates (only ~20% of cells chosen at random update per step)
ca = GameOfLife(lattice, update_mode='asynchronous', async_update_rate=0.20)
ca.initialize(pattern='random', density=0.3)

viz = CAVisualizer(ca)
viz.start()

📈 Parameter sweeps & Analysis

Explore critical phenomena and bifurcation thresholds automatically:

from ca_framework import ParameterExplorer, ForestFire

explorer = ParameterExplorer(ForestFire, lattice_shape=(80, 80))

# 1. Run grid search parameter sweeps
results = explorer.grid_search(
    param_grid={'p_burn': [0.3, 0.5, 0.7, 0.9], 'tree_density': [0.5, 0.7]},
    steps=100,
    replicates=2
)
explorer.generate_report('./outputs/fire_sweep')

# 2. Critical point detection for phase transitions
critical = explorer.critical_point_detection(
    param_name='p_burn',
    param_range=(0.1, 1.0),
    observable='burning_fraction'
)
print(f"Emergent critical fire propagation point: p_burn = {critical['critical_point']:.3f}")

📂 Project Directory Structure

cellular_automata_framework/
├── ca_framework/               # Core Package
│   ├── __init__.py             # Public API exports
│   ├── core.py                 # Lattice, update kernels, rule specifications
│   ├── models.py               # Built-in GoL, Forest Fire, SIR, and Overlay models
│   ├── visualization.py        # Matplotlib GUI engine & parameter sliders
│   ├── statistics.py           # Connected components, fractals, autocorrelation
│   └── exploration.py          # Grid search sweeps, critical point estimators
├── examples/                   # Walkthrough scripts
│   ├── game_of_life_example.py
│   ├── forest_fire_example.py
│   ├── epidemic_example.py
│   ├── custom_rules_example.py
│   ├── parameter_sweep_example.py
│   └── interacting_overlay_example.py  # Coupled overlay demonstration
├── tests/                      # Python Unit Test Suite
│   ├── __init__.py
│   ├── test_core.py            # Tests lattice kernels, padding, neighbor counting
│   ├── test_models.py          # Tests GoL, Forest Fire, SIR, async updates, overlays
│   └── test_statistics.py      # Tests cluster analysis, entropy, percolation
├── main.py                     # Command-line interface unified demo
└── requirements.txt            # Project dependencies

🔬 Running the Demo & Tests

# Run the complete test suite
python -m unittest discover -s tests

# Run all interactive GUI demos sequentially
python main.py

# Run a specific coupled overlay model demo
python main.py --demo overlay

# Run Game of Life in stochastically asynchronous mode
python main.py --demo life --update-mode asynchronous --async-rate 0.20

📝 License & Citation

MIT License. If you utilize this framework in academic work, please cite:

Cellular Automata Simulation Framework (2026).
Modular scientific simulation toolkit for discrete dynamical systems and coupled socio-ecological models.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages