> ## Documentation Index
> Fetch the complete documentation index at: https://docs.veydra.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Simulation Engine

> Run system dynamics models in real time, directly in your browser

## Overview

Veydra's simulation engine runs Python-based system dynamics models **entirely in your browser** — no installs, no servers, no setup. When you open a model, Veydra automatically loads a complete scientific Python environment and executes the model locally on your device. Every parameter change produces instant results.

This engine powers every experience on the platform: the [Model Playground](/playground/overview), [Activities](/features/activities), and the [AI Assistant](/features/ai-assistant) all rely on the same real-time simulation pipeline under the hood.

## What You Can Do

<CardGroup cols={2}>
  <Card title="Instant Feedback" icon="bolt">
    Move a slider and see charts update in real time — no waiting for a server round-trip.
  </Card>

  <Card title="What-If Scenarios" icon="flask">
    Change assumptions, compare outcomes, and explore different futures interactively.
  </Card>

  <Card title="AI-Assisted Analysis" icon="sparkles">
    The AI Assistant runs simulations on your behalf to answer questions, suggest experiments, and interpret results.
  </Card>

  <Card title="Turn-Based Games" icon="gamepad">
    Activities use the same engine to power interactive decision-making games with scoring and objectives.
  </Card>
</CardGroup>

## How It Works

<Steps>
  <Step title="Model Loads Automatically">
    When you open a model, Veydra fetches the Python source code and boots a scientific Python runtime in your browser. No action required on your part.
  </Step>

  <Step title="Baseline Results Appear">
    The model runs once with its default parameters and renders the baseline charts — stocks, flows, and time series.
  </Step>

  <Step title="You Adjust Parameters">
    Use sliders, presets, or the AI Assistant to change input values. Each change triggers a new simulation run instantly.
  </Step>

  <Step title="Results Update in Real Time">
    Updated charts, diagrams, and data tables reflect the new simulation output immediately.
  </Step>
</Steps>

## Where the Engine Is Used

### Model Playground

The [Model Playground](/playground/overview) is the primary interface for working with models. Depending on the mode you're in, the simulation engine behaves differently:

| Mode             | How the Engine Is Used                                                       |
| ---------------- | ---------------------------------------------------------------------------- |
| **Presentation** | Runs the baseline simulation for display alongside slides and guided content |
| **Design**       | Re-runs the model as you edit parameters, equations, or structure            |
| **Experiment**   | Runs what-if scenarios and overlays results against the baseline             |
| **Calibrate**    | Iterates simulations to fit model output to real-world data                  |
| **Decide**       | Runs multiple scenarios in parallel for side-by-side comparison              |

### Activities

[Activities](/features/activities) wrap the simulation engine in a game-like experience. At each turn, the player adjusts parameters and commits their choices. The engine advances the simulation by a configured time increment and returns the results — enabling scoring, objectives, and competitive play.

### AI Assistant

The [AI Assistant](/features/ai-assistant) uses the simulation engine programmatically. When you ask "What happens if I double the growth rate?", the assistant builds a parameter set, runs the simulation, and interprets the results — all without you touching a slider.

## Key Capabilities

### Real-Time Parameter Adjustment

Every model parameter — growth rates, initial conditions, thresholds — can be adjusted via interactive sliders. Changes take effect immediately:

1. You move a slider
2. The engine re-runs the simulation with the updated value
3. Charts and diagrams refresh instantly

### Scenario Comparison

Run the model with different assumptions and compare results side by side:

* **Baseline vs. Scenario** — See how your changes differ from the defaults
* **Multiple Scenarios** — Save named parameter sets and switch between them
* **Presets** — Models ship with curated scenarios that highlight interesting dynamics

### Data Export

Simulation results can be exported for further analysis:

* **CSV** — Time series data for stocks and flows
* **Charts** — Download visualizations as images

## Performance

* **No server required** — all computation happens on your device
* **Near-native speed** — the Python runtime is compiled to WebAssembly for fast numerical execution
* **Smart caching** — model files and recent results are cached locally for fast reloads
* **Handles complexity** — multi-stock models with dozens of parameters run smoothly in the browser

<Note>
  The first time you open a model, there's a brief loading period while the runtime initializes. Subsequent visits are faster thanks to browser caching.
</Note>

## Privacy

Because models execute entirely in your browser:

* **Simulation inputs and results stay on your device** — nothing is sent to a server during execution
* **No server compute costs** — your device does the work
* **Isolated execution** — each model runs in its own sandboxed environment

## Error Handling

### Graceful Failures

The simulation engine includes robust error handling:

<Accordion title="Syntax Errors">
  Python syntax errors in model code are caught and displayed with helpful debugging information
</Accordion>

<Accordion title="Runtime Errors">
  Execution errors during simulation show specific error messages and line numbers
</Accordion>

<Accordion title="Data Errors">
  Invalid parameter values or data format issues are automatically detected and reported
</Accordion>

<Accordion title="Recovery Mechanisms">
  Automatic fallback to last known good state when errors occur
</Accordion>

## Advanced Features

### Custom Model Functions

Write sophisticated Python models with full library support:

```python theme={null}
import numpy as np
import pandas as pd

def complex_model(params, time_range):
    # Complex calculations with scientific libraries
    data = np.array(time_range)
    results = pd.DataFrame()
    
    # Your model logic here
    
    return results.to_dict('records')
```

### Multi-Stock Analysis

Handle models with multiple interacting stocks:

* **Cross-stock Dependencies**: Model interactions between stocks
* **Synchronized Updates**: Consistent time-step processing
* **Relationship Mapping**: Track dependencies and influences
* **Aggregate Views**: Summary statistics across all stocks

## Debugging Tools

### Execution Monitoring

* **Real-time Logs**: View Python execution output
* **Performance Metrics**: Track execution time and memory
* **Parameter Tracking**: Monitor parameter changes
* **Error Reporting**: Detailed error messages and stack traces

### Model Validation

* **Syntax Checking**: Pre-execution code validation
* **Parameter Validation**: Check ranges and types
* **Output Verification**: Ensure proper data formats
* **Consistency Checks**: Verify model logic

<Tip>
  Use the browser's developer console to see detailed execution logs and debug model issues
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="Chart Components" icon="chart-line" href="/components/charts">
    Learn about visualization options
  </Card>

  <Card title="Model Controls" icon="sliders" href="/components/model-controls">
    Master parameter management
  </Card>
</CardGroup>
