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

# Simulation Engine

> Generate realistic emergency scenarios for testing and training

## Simulation Overview

The access911 simulation engine generates realistic emergency scenarios to test system performance, train operators, and validate response procedures. The engine supports multiple disaster types and can generate thousands of emergency calls with realistic metadata.

## Supported Scenarios

### Los Angeles Wildfire

Simulates wildfire emergency conditions in Los Angeles County:

* **Areas**: Pacific Palisades, Malibu, Topanga, Brentwood, Santa Monica Mountains
* **Emergency Types**: Structure fires, evacuation assistance, trapped persons, medical emergencies, shelter information
* **Severity Levels**: Critical, High, Moderate

### Nashville Tornado Outbreak

Simulates tornado emergency conditions in Nashville:

* **Areas**: Downtown Nashville, East Nashville, Germantown, The Gulch, Music Row
* **Emergency Types**: Building damage, trapped persons, debris injuries, power lines down, gas leaks, vehicle accidents, shelter needed
* **Severity Levels**: Critical, High, Moderate

### San Francisco Earthquake

Simulates earthquake emergency conditions in San Francisco:

* **Areas**: Marina District, Mission District, Financial District
* **Emergency Types**: Building collapse, gas leaks, trapped persons, medical injuries
* **Severity Levels**: Critical, High, Moderate

### Florida Hurricane

Simulates hurricane emergency conditions in Florida:

* **Areas**: Miami Beach, Fort Lauderdale, West Palm Beach
* **Emergency Types**: Flooding, wind damage, power outages, evacuation needed
* **Severity Levels**: Critical, High, Moderate

## Simulation Features

### AI-Powered Generation

For small batches (≤20 calls), the simulation uses AWS Bedrock AI to generate human-like call summaries:

```python theme={null}
# AI-generated summary example
prompt = "Write a brief 2-sentence 911 dispatcher summary for: house fire with family evacuating at 1234 Sunset Mesa Dr, Pacific Palisades. Include emergency services dispatched."

# Result: "Caller reported house fire with family evacuating at 1234 Sunset Mesa Dr, Pacific Palisades. Fire and EMS units dispatched to scene with ETA 5-7 minutes."
```

### Template-Based Generation

For large batches (>20 calls), the simulation uses templates for high throughput:

```python theme={null}
# Template examples
templates = [
    "Caller reported {emergency_desc} at {address}. Emergency services have been dispatched to the scene.",
    "911 dispatch received report of {emergency_desc} at {address}. First responders en route with ETA 5-7 minutes.",
    "Emergency call regarding {emergency_desc} at {address}. Fire and EMS units notified and responding."
]
```

### Unique Location Generation

The simulation ensures each call has a unique location to avoid duplicates:

```python theme={null}
def generate_unique_locations(num_calls, scenario):
    unique_locations = []
    used_addresses = set()
    
    for i in range(num_calls):
        # Select random location with variance
        location = random.choice(scenario['locations'])
        lat = location['lat'] + random.uniform(-0.02, 0.02)
        lon = location['lon'] + random.uniform(-0.02, 0.02)
        
        # Generate unique address
        street = random.choice(scenario['streets'])
        street_num = random.randint(100, 2999)
        address = f"{street_num} {street}, {location['area']}"
        
        # Ensure uniqueness
        location_key = f"{address}_{round(lat, 4)}_{round(lon, 4)}"
        if location_key not in used_addresses:
            used_addresses.add(location_key)
            unique_locations.append({
                'location': location,
                'lat': lat,
                'lon': lon,
                'address': address
            })
    
    return unique_locations
```

## API Usage

### Generate Emergency Calls

```bash theme={null}
curl -X POST https://v2y08vmfga.execute-api.us-east-1.amazonaws.com/simulate \
  -H "Content-Type: application/json" \
  -d '{
    "scenario": "nashville_tornado",
    "num_calls": 50,
    "table_name": "wildfire-simulation-calls"
  }'
```

### Response Format

```json theme={null}
{
  "message": "Generated 50 calls for Nashville Tornado Outbreak",
  "scenario": "nashville_tornado",
  "total_requested": 50,
  "successful": 50,
  "failed": 0,
  "generation_method": "Templates (fast mode)",
  "sample_calls": [
    {
      "call_id": "NASHVILLE_TORNADO-1703123456-1234",
      "location": "Downtown Nashville",
      "emergency_type": "building_damage"
    }
  ],
  "errors": []
}
```

### Available Scenarios

| Scenario ID         | Name                     | Description                     |
| ------------------- | ------------------------ | ------------------------------- |
| `la_wildfire`       | Los Angeles Wildfire     | Wildfire emergency simulation   |
| `nashville_tornado` | Nashville Tornado        | Tornado outbreak simulation     |
| `earthquake_sf`     | San Francisco Earthquake | Earthquake emergency simulation |
| `hurricane_florida` | Florida Hurricane        | Hurricane emergency simulation  |

## Load Balancing and Performance

### Automatic Scaling

The simulation engine automatically adjusts generation methods based on call volume:

* **≤20 calls**: Uses AWS Bedrock AI for high-quality, varied summaries
* **>20 calls**: Uses templates for fast, high-throughput generation

### Performance Metrics

| Call Volume  | Generation Method | Approximate Time | Quality |
| ------------ | ----------------- | ---------------- | ------- |
| 1-20 calls   | AI-powered        | 2-5 seconds      | High    |
| 21-100 calls | Template-based    | 1-3 seconds      | Good    |
| 100+ calls   | Template-based    | 3-10 seconds     | Good    |

### Concurrency Handling

The simulation engine handles concurrent requests efficiently:

```python theme={null}
# Lambda function handles multiple concurrent requests
def lambda_handler(event, context):
    # Parse request parameters
    body = json.loads(event.get('body', '{}'))
    num_calls = body.get('num_calls', 1)
    scenario_name = body.get('scenario', 'la_wildfire')
    
    # Generate calls with unique locations
    unique_locations = generate_unique_locations(num_calls, scenario)
    
    # Process calls in batches for optimal performance
    for i in range(num_calls):
        call = generate_call(i, num_calls, scenario, scenario_name, use_ai, unique_locations[i])
        table.put_item(Item=call)
```

## Call Data Structure

Each generated emergency call includes:

```json theme={null}
{
  "call_id": "NASHVILLE_TORNADO-1703123456-1234",
  "timestamp": 1703123456,
  "created_at": "2023-12-21T10:30:56.789Z",
  "location": {
    "latitude": "36.1627",
    "longitude": "-86.7816",
    "address": "1234 Broadway, Downtown Nashville",
    "area": "Downtown Nashville"
  },
  "emergency_type": "building_damage",
  "severity": "critical",
  "description": "severe structural damage from tornado",
  "summary": "Caller reported severe structural damage from tornado at 1234 Broadway, Downtown Nashville. Fire and EMS units dispatched to scene.",
  "duration_secs": 180,
  "caller_phone": "+16155551234",
  "status": "active",
  "simulation": true,
  "scenario": "nashville_tornado",
  "scenario_name": "Nashville Tornado Outbreak"
}
```

## Dashboard Integration

The simulation engine integrates seamlessly with the dashboard:

1. **Real-time Updates**: Generated calls appear immediately on the map
2. **Live Visualization**: Watch calls appear with animated pins
3. **Status Tracking**: Monitor call processing in real-time
4. **History Storage**: All simulated calls are stored for analysis

## Best Practices

### Testing Scenarios

<AccordionGroup>
  <Accordion icon="flask" title="Start Small">
    Begin with 10-20 calls to test system responsiveness before scaling up.
  </Accordion>

  <Accordion icon="chart-line" title="Monitor Performance">
    Watch system performance metrics during large simulations.
  </Accordion>

  <Accordion icon="database" title="Data Management">
    Regularly clean up old simulation data to maintain performance.
  </Accordion>
</AccordionGroup>

### Training Use Cases

* **Operator Training**: Use simulations to train new emergency operators
* **System Testing**: Validate system performance under load
* **Procedure Validation**: Test emergency response procedures
* **Capacity Planning**: Understand system limits and scaling needs

## Error Handling

The simulation engine includes comprehensive error handling:

```python theme={null}
try:
    call = generate_call(i, num_calls, scenario, scenario_name, use_ai, unique_locations[i])
    table.put_item(Item=call)
    generated_calls.append({
        'call_id': call['call_id'],
        'location': call['location']['area'],
        'emergency_type': call['emergency_type']
    })
except Exception as e:
    error_msg = f"Error on call {i+1}: {str(e)}"
    print(f"✗ {error_msg}")
    errors.append(error_msg)
```

## Monitoring and Analytics

Track simulation performance with built-in metrics:

* **Success Rate**: Percentage of successfully generated calls
* **Generation Time**: Time taken to generate all calls
* **Error Rate**: Number of failed call generations
* **System Load**: Resource utilization during simulation

<Note>
  **Production Use**: The simulation engine is designed for testing and training. For production emergency response, ensure proper integration with your existing 911 systems.
</Note>
