Skip to content

chenders/AirMedSim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

445 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AirMedSim: Inter-Hospital Patient Transfer Simulation System

Python 3.12 React 18 TypeScript License: MIT

A discrete-event simulation system designed to analyze and optimize inter-hospital patient transfer coordination, with a focus on improving outcomes for rural and underserved populations.

AirMedSim Screenshot

The Problem

Inter-hospital patient transfers currently face critical inefficiencies:

  • Median transfer time: 17 hours (some cases taking up to 10 days)
  • 70% increase in mortality for rural sepsis patients
  • $6,897 additional cost per transfer
  • Manual coordination requiring dozens of phone calls per transfer
  • 76% of transfers arrive overnight when physician oversight is minimal

For Native American reservations and rural areas, these problems are magnified by:

  • Geographic isolation (some reservations larger than entire states)
  • Only 60% of healthcare needs funded (IHS spending $2,849 per person vs. $7,717 national average)
  • Limited facilities lacking basic equipment

Solution

AirMedSim provides a discrete-event simulation framework to test and optimize transfer coordination strategies before real-world implementation. The system models:

  • Hospital network topology with real facility data (beds, capabilities, locations)
  • Patient transfer requests with configurable demand patterns
  • Ambulance fleets (ground and air) with realistic capacity and routing
  • Coordination strategies including centralized dispatch and regional hubs
  • Performance metrics tracking wait times, utilization, and transfer success rates

Features

Simulation Engine

  • Discrete-event simulation with priority queuing
  • Real hospital data from CMS datasets for Montana
  • Realistic routing with OSRM road network calculations
  • Weather integration with NOAA API for real-time conditions affecting transport
  • Multiple ambulance types (BLS, ALS, CCT ground + air ambulances)
  • Configurable scenarios for testing different strategies
  • Performance analytics with detailed metrics tracking

Web Visualization

  • Interactive map showing Montana hospital network
  • Real-time playback of simulation events with adjustable speed (0.5x-20x)
  • Animated ambulance movements with vehicle type icons (🚁 🚑 🚐)
  • Metrics dashboard tracking key performance indicators
  • Analytics dashboard with KPI charts and statistics
  • PDF report generation (executive summary, detailed analysis, comparison reports)
  • Custom Tailwind UI with responsive design and resizable panels

Data Pipeline

  • Automated data collection from CMS hospital datasets
  • Geocoding integration for accurate hospital locations
  • Data validation ensuring quality and completeness
  • Caching layer for optimal performance

Historical Data Validation

  • Statistical validation comparing simulation results to real EMS data
  • Flexible data import from CSV/Excel with custom column mapping
  • NEMSIS-compliant schema for standardized transfer records
  • Multiple statistical tests including Kolmogorov-Smirnov and t-tests
  • Comprehensive reporting with validation summaries and detailed metrics
  • Sample data generation for testing and demonstration

Multi-Region Support

  • Region-specific configurations with unique characteristics and constraints
  • Comparative analysis across different geographic areas
  • Customizable templates for rural, urban, and hybrid healthcare networks
  • Demand profiling with seasonal and time-of-day variations
  • Operational profiles capturing terrain, weather, and infrastructure differences
  • Best practices identification from top-performing regions

Policy Optimization

  • Multi-objective optimization balancing wait times, utilization, and completion rates
  • Policy comparison using designed experiments with statistical rigor
  • Cost-benefit analysis with detailed economic breakdowns and ROI calculations
  • Pareto frontier identification for trade-off analysis
  • Automated recommendations based on performance metrics and objectives
  • Incremental cost-effectiveness comparing policies against baselines

Machine Learning Integration

  • Demand forecasting using time-series models (SMA, ETS, ARIMA, LSTM)
  • Utilization prediction for ambulances and hospital beds
  • Optimal resource positioning with demand-weighted and coverage-optimized strategies
  • Proactive capacity management identifying bottlenecks before they occur
  • Anomaly detection for unusual demand patterns
  • Dynamic reallocation recommendations based on predicted demand

Quick Start

Prerequisites

  • Python 3.11+
  • Node.js 20+ and npm
  • Poetry (Python package manager)
  • Docker (optional, for OSRM routing)

Installation

# Clone the repository
git clone https://github.com/yourusername/AirMedSim.git
cd AirMedSim

# Install Python dependencies
poetry install

# Install frontend dependencies
cd web/frontend
npm install

Environment Setup

Create .env files with required API keys:

Root .env:

GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here

web/frontend/.env.local:

VITE_GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here

OSRM Routing Setup (Optional but Recommended)

The simulation uses realistic road network routing via OSRM (Open Source Routing Machine). This provides accurate distance and travel time calculations instead of straight-line estimates.

1. Set up OSRM with Montana data:

# Download and process Montana OSM data
./scripts/setup_osrm.sh

# This will:
# - Download ~92MB Montana map data from Geofabrik
# - Extract road network
# - Build routing index (~5 minutes)

2. Start OSRM server:

docker compose -f docker-compose.osrm.yml up -d

3. Verify OSRM is running:

curl "http://localhost:5001/route/v1/driving/-112.0391,46.5891;-113.9940,46.8721"

4. Configure simulation to use OSRM:

Edit config/montana_simulation.yaml:

routing:
  method: osrm                    # Use OSRM routing
  osrm_host: "http://localhost:5001"
  distance_multiplier: 1.4

Benefits:

  • Real road network distances (Helena → Missoula: 182 km vs 152 km straight-line)
  • Actual travel times based on road speeds
  • Route geometry for visualization
  • Millisecond query response times

Fallback: If OSRM is not available, the system automatically falls back to haversine (straight-line) distance calculations with a configurable multiplier.

Running the System

1. Start the Backend API:

cd web/backend
poetry run uvicorn api:app --reload

2. Start the Frontend (in a new terminal):

cd web/frontend
npm run dev

3. Access the Application:

Running Examples

Validate simulation results and compare regions:

# Run comprehensive validation examples
poetry run python examples/run_historical_validation.py

# Run sensitivity analysis examples
poetry run python examples/run_sensitivity_analysis.py

# Run multi-region comparison examples
poetry run python examples/run_multi_region_comparison.py

# Run policy optimization examples
poetry run python examples/run_policy_optimization.py

# Run machine learning integration examples
poetry run python examples/run_ml_integration.py

These examples demonstrate:

  • Importing historical transfer data from CSV/Excel
  • Statistical comparison using K-S tests and t-tests
  • Generating validation reports
  • Sensitivity analysis with confidence intervals
  • Comparing performance across different regions
  • Identifying best practices from top performers
  • Optimizing coordination policies with multi-objective analysis
  • Economic evaluation with cost-benefit analysis
  • Forecasting patient transfer demand with time-series models
  • Predicting resource utilization to prevent bottlenecks
  • Optimizing ambulance positioning based on predicted demand
  • Proactive vs reactive coordination strategies

Project Structure

AirMedSim/
├── src/airmedsim/           # Core simulation engine
│   ├── simulation/          # Discrete-event simulation logic
│   ├── data/                # Data loading and processing
│   ├── validation/          # Historical data validation
│   ├── analysis/            # Sensitivity analysis and regional comparison
│   ├── ml/                  # Machine learning for forecasting and optimization
│   └── utils/               # Configuration and utilities (including region_config)
├── config/                  # Configuration files
│   ├── regions/            # Region-specific configurations
│   │   ├── montana_rural.yaml      # Montana rural network
│   │   ├── arizona_urban.yaml      # Phoenix metro area
│   │   ├── template_rural.yaml     # Template for rural regions
│   │   └── template_urban.yaml     # Template for urban regions
│   └── montana_simulation.yaml     # Main simulation config
├── web/                     # Web application
│   ├── backend/             # FastAPI backend
│   │   ├── api.py          # API endpoints
│   │   └── tests/          # Backend tests
│   └── frontend/            # React + TypeScript frontend
│       ├── src/            # Source code
│       │   ├── components/ # React components
│       │   ├── hooks/      # Custom React hooks
│       │   └── services/   # API client
│       └── tests/e2e/      # Playwright E2E tests
├── examples/                # Example scripts and usage
├── data/                    # Data files and cache
├── docs/                    # Documentation
└── outputs/                 # Simulation results

Documentation

Testing

Backend Tests

cd web/backend
poetry run pytest tests/ -v

Frontend Tests

cd web/frontend
npm test                    # Run Playwright tests
npm run test:ui            # Run tests with UI
npm run test:report        # View test report

Simulation Tests

# Unit tests (no OSRM required)
poetry run pytest tests/unit/ -v

# Integration tests (requires OSRM running)
docker compose -f docker-compose.osrm.yml up -d
poetry run pytest tests/integration/ -v

Technology Stack

Backend:

  • Python 3.11+ with Poetry
  • FastAPI for REST API
  • SimPy for discrete-event simulation
  • Pandas for data processing
  • Pytest for testing

Frontend:

  • React 18 with TypeScript
  • Vite for build tooling
  • Tailwind CSS v3 for styling
  • @vis.gl/react-google-maps for mapping
  • Recharts for data visualization
  • Playwright for E2E testing

Data & Routing:

  • CMS Hospital Compare datasets
  • Google Maps Geocoding API
  • OSRM (Open Source Routing Machine) for road network routing
  • OpenStreetMap data for Montana

Current Status

Implemented ✅

  • Hospital data pipeline with real CMS data
  • Core simulation engine with discrete-event logic
  • OSRM integration for realistic road network routing
  • Weather integration with NOAA API (travel time impacts, air transport restrictions)
  • Multiple ambulance types (BLS/ALS/CCT ground, air ambulances with operational radius)
  • FastAPI backend with REST endpoints
  • React frontend with interactive map visualization
  • Simulation playback with animated ambulance tracking (0.5x-20x speed)
  • Performance metrics dashboard with real-time KPIs
  • Analytics dashboard with charts and statistics (Recharts)
  • PDF report generation (executive summary, detailed analysis, comparison reports)
  • Tailwind CSS custom theme with resizable panels
  • E2E test suite with Playwright (15+ test files)
  • Comprehensive unit and integration tests (244+ tests, 65% coverage)
  • Historical data validation with statistical tests
  • Sensitivity analysis framework with confidence intervals
  • PostgreSQL database persistence with async operations (asyncpg)
  • Alembic migrations for schema versioning
  • Multi-region support with comparative analysis
  • Region templates for rural and urban networks
  • Policy optimization with multi-objective analysis
  • Cost-benefit analysis with economic evaluation
  • Machine learning demand forecasting (SMA, ETS, ARIMA)
  • Resource utilization prediction with queueing theory
  • Optimal ambulance positioning with hybrid strategies
  • Proactive capacity management and bottleneck detection
  • What-if scenario analysis with scenario builder and comparison UI

In Progress 🚧

  • Advanced LSTM models for complex seasonal patterns
  • Anomaly detection for unusual demand patterns
  • E2E test stability improvements for CI environment

Planned 📋

  • Automated parameter calibration
  • Integration with real-time EMS data feeds
  • WebSocket support for real-time simulation streaming
  • Crew scheduling constraints modeling

Contributing

Contributions are welcome! Please see our Development Guide for details on:

  • Setting up your development environment
  • Running tests
  • Code style guidelines
  • Submitting pull requests

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Hospital data from Centers for Medicare & Medicaid Services (CMS)
  • Mapping powered by Google Maps Platform
  • Simulation framework built with SimPy

Contact

For questions or collaboration inquiries, please open an issue on GitHub.


Note: This is a research and educational project. Simulation results should be validated with domain experts before implementation in real-world healthcare settings.

About

Discrete-event simulation system for analyzing and optimizing inter-hospital patient transfer coordination. Features real-time visualization, animated ambulance tracking, and performance analytics to improve outcomes for rural and underserved populations.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors