Skip to content

spock74/econphysics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Economic Simulation Lab

This project is a personal research initiation focused on agent-based modeling (ABM) of economic systems using a high-performance computational stack. The primary objective is to evaluate the limits of real-time simulation in distributed environments (Web and Desktop) using Rust and WebAssembly.

System Architecture

The project is structured as a mono-repository separating the core simulation logic from the delivery layers.

graph TD
    subgraph Core_Engine [Rust Workspace]
        SE[simulation-engine] --> |Low-level Logic| WA[web-adapter]
    end

    subgraph Adapters [Data Bridge]
        WA --> |WASM/wasm-bindgen| TS[TypeScript Bindings]
    end

    subgraph Consumers [Frontend]
        TS --> UI[Next.js Web App]
        UI --> DS[Tauri Desktop Shell]
    end

    subgraph Native_Thread [Native Execution]
        DS --> |Direct Link| SE
    end
Loading

Stack Rationale

The technical stack was chosen to maximize throughput and minimize latency in the simulation loop.

  1. Rust (Core): Used for the memory-safe implementation of agent logic. The use of slotmap provides O(1) access to agent data while avoiding pointer chasing, which is critical for CPU cache efficiency during mass updates.
  2. WebAssembly (WASM): Enables the execution of the same Rust engine in the browser at near-native speeds.
  3. Tauri: Provides a desktop wrapper that allows for future native multi-threading capabilities, bypassing browser sandbox limitations when necessary.
  4. Canvas API (Bypass): The UI uses a "Bypass Architecture" where the state is rendered via direct 2D Canvas context, avoiding React reconciliation overhead for the positions of 10,000+ agents.

Simulation Dynamics

The simulation follows a standard ABM loop where global parameters influence discrete agent behavior.

sequenceDiagram
    participant JS as Frontend (Control)
    participant WA as WASM Adapter
    participant SE as Simulation Engine
    
    loop Every Frame
        JS->>WA: tick()
        WA->>SE: update_state(parameters)
        SE->>SE: 1. Apply Physics (Brownian)
        SE->>SE: 2. Apply Economic Stochastics
        SE->>SE: 3. Calculate Global Metrics (Gini)
        WA->>JS: get_state_view()
        JS->>JS: Render Canvas + Charts
    end
    
    Note over JS, SE: Parametric updates occur asynchronously via set_params()
Loading

Parameter Definitions and Economic Validity

The simulation currently exposes four global parameters that model fundamental macroeconomic and stochastic behaviors:

Parameter Computational Implementation Economic Validity
Volatility Scaling factor for Brownian motion and noise. Models market uncertainty and information asymmetry.
Interest Rate Fixed or proportional decay per tick. Represents cost of living, taxation, or monetary inflation.
Tail Risk Bernoulli distribution for "Black Swan" events. Models systemic shocks (financial crises, pandemics).
Non-linearity Toggle between additive and multiplicative growth. Models the difference between income-based and capital-based economies.

Note on Multiplicative Dynamics

In non-linear mode, the simulation implements a multiplicative return-on-capital model ($W_{t+1} = W_t \cdot (1 + r)$). This is a known precursor to the Pareto Distribution (80/20 rule), where wealth concentration becomes an emergent property of the system rather than a pre-defined outcome.

Technical Implementation Details

Data Flow and Synchronization

To ensure consistent performance, the SimulationStateView struct in Rust is serialized to a JavaScript-compatible format. Global metrics such as the Gini Index are calculated within the Rust engine to offload the main UI thread.

classDiagram
    class SimulationState {
        +u64 tick
        +SlotMap agents
        +SystemParams params
        +update()
    }
    class Agent {
        +Uuid id
        +f64 cash
        +f32 x, y
    }
    class SystemParams {
        +f32 volatility
        +f32 interest_rate
        +bool is_nonlinear
    }
    SimulationState *-- Agent
    SimulationState *-- SystemParams
Loading

Local Setup

Requirements

  • Rust (latest stable)
  • Node.js (v18+)
  • pnpm
  • wasm-pack

Instructions

  1. Build the WASM module:
    wasm-pack build crates/web-adapter --target web --out-dir ../../apps/ui-web/src/wasm --out-name economy_sim
  2. Install dependencies:
    pnpm install
  3. Run Web Application:
    pnpm --filter ui-web dev
  4. Run Desktop Application:
    pnpm --filter desktop-shell tauri dev

Project Roadmap

The current implementation is in Phase 1 (Core Dynamics). Future research focuses on the following milestones:

  • Spatial Topology (Phase 2): Implementation of trade logic based on agent proximity.
  • Credit Markets (Phase 3): Introduction of debt instruments and leverage between agents.
  • Multithreaded Native Engine (Phase 4): Offloading simulation to secondary threads in the Tauri shell for higher agent counts (>100k).
  • Data Persistence (Phase 5): Export of historical time-series data for analysis in external statistical tools.

About

Laboratório de simulação econômica de alta performance baseado em agentes, desenvolvido com Rust, WebAssembly e visualização em tempo real.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors