File size: 11,066 Bytes
888cb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
---
title: Smart Routing System
emoji: ๐Ÿš‘
colorFrom: red
colorTo: gray
sdk: docker
app_port: 7860
pinned: false
---
# ๐Ÿš‘ SmartER โ€” AI-Powered Healthcare Routing & Emergency Management

> **Hackathon:** Meta PyTorch OpenEnv Hackathon x SST 2026
> **Framework:** Meta's OpenEnv + PyTorch DQN
> **Tech Stack:** Python ยท FastAPI ยท React ยท Leaflet ยท Gymnasium

---

## ๐Ÿ“‹ Table of Contents

1. [Project Overview](#project-overview)
2. [Folder Structure](#folder-structure)
3. [Quick Start (3 minutes)](#quick-start)
4. [RL Environment Details](#rl-environment)
5. [Backend API](#backend-api)
6. [Frontend Pages](#frontend-pages)
7. [Training the DQN Model](#training)
8. [Simulation & Live Demo](#simulation)
9. [Deployment](#deployment)
10. [OpenEnv Submission](#openenv-submission)

---

## ๐Ÿง  Project Overview

SmartER uses **Reinforcement Learning** to solve real-world emergency healthcare routing:

| Problem | RL Solution |
|---------|-------------|
| Which hospital has capacity? | State includes live bed counts |
| Which ambulance is nearest? | State includes all GPS positions |
| Critical patient needs ICU? | Reward function weights ICU access |
| Minimize response time? | Distance + ETA encoded as penalties |

**Core RL Setup (OpenEnv-compatible):**
- **Environment:** `HealthcareRoutingEnv` (Gymnasium API)
- **State:** Patient severity + location + hospital beds + ambulance positions
- **Actions:** Discrete โ€” choose (hospital, ambulance) pair
- **Reward:** +100 admit, +70 ICU for critical, +50 fast response, penalties for bad choices
- **Agent:** Deep Q-Network (DQN) with PyTorch

---

## ๐Ÿ“ Folder Structure

```
healthcare_rl/
โ”œโ”€โ”€ openenv_env/            โ† ๐Ÿ† Core OpenEnv submission
โ”‚   โ”œโ”€โ”€ healthcare_env.py   โ† Gymnasium RL environment
โ”‚   โ”œโ”€โ”€ task.py             โ† OpenEnv Task + Grader
โ”‚   โ”œโ”€โ”€ register.py         โ† gym.make() registration
โ”‚   โ””โ”€โ”€ requirements.txt
โ”‚
โ”œโ”€โ”€ rl/                     โ† PyTorch DQN agent
โ”‚   โ”œโ”€โ”€ dqn_agent.py        โ† DQN network + replay buffer
โ”‚   โ”œโ”€โ”€ train.py            โ† Training loop
โ”‚   โ””โ”€โ”€ models/             โ† Saved model weights (created on train)
โ”‚
โ”œโ”€โ”€ backend/                โ† FastAPI REST + WebSocket server
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ main.py         โ† All endpoints + simulation engine
โ”‚   โ”œโ”€โ”€ requirements.txt
โ”‚   โ””โ”€โ”€ Dockerfile
โ”‚
โ”œโ”€โ”€ frontend/               โ† React dashboard
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ App.jsx
โ”‚   โ”‚   โ”œโ”€โ”€ App.css
โ”‚   โ”‚   โ””โ”€โ”€ pages/
โ”‚   โ”‚       โ”œโ”€โ”€ Dashboard.jsx    โ† KPIs + charts
โ”‚   โ”‚       โ”œโ”€โ”€ MapView.jsx      โ† Live Leaflet map
โ”‚   โ”‚       โ”œโ”€โ”€ PatientForm.jsx  โ† Emergency intake
โ”‚   โ”‚       โ””โ”€โ”€ AdminPanel.jsx   โ† Hospital/ambulance management
โ”‚   โ”œโ”€โ”€ index.html          โ† Leaflet CDN loaded here
โ”‚   โ”œโ”€โ”€ package.json
โ”‚   โ”œโ”€โ”€ vite.config.js
โ”‚   โ””โ”€โ”€ Dockerfile
โ”‚
โ”œโ”€โ”€ data/
โ”‚   โ””โ”€โ”€ sample_data.json    โ† Seed data (hospitals, ambulances, patients)
โ”‚
โ”œโ”€โ”€ demo.py                 โ† Terminal demo (no server needed)
โ”œโ”€โ”€ docker-compose.yml
โ””โ”€โ”€ README.md
```

---

## โšก Quick Start

### Option A โ€” Terminal Demo (no setup needed)

```bash
# 1. Install Python dependencies
pip install gymnasium numpy torch

# 2. Run the demo
python demo.py

# Options:
python demo.py --episodes 5 --steps 20   # longer demo
python demo.py --random                  # compare with random policy
python demo.py --fast                    # no delay between steps
```

### Option B โ€” Full Stack (Backend + Frontend)

**Step 1: Backend**
```bash
cd backend
pip install -r requirements.txt

# Copy RL modules to backend path
export PYTHONPATH=../openenv_env:../rl:$PYTHONPATH

cd api
uvicorn main:app --reload --port 8000
```
> API is now live at http://localhost:8000
> Interactive docs: http://localhost:8000/docs

**Step 2: Frontend**
```bash
cd frontend
cp .env.example .env          # sets VITE_API_URL=http://localhost:8000
npm install
npm run dev
```
> UI is now live at http://localhost:5173

### Option C โ€” Docker (one command)

```bash
docker-compose up --build
```
> Frontend: http://localhost:3000
> Backend:  http://localhost:8000

---

## ๐Ÿค– RL Environment

### State Space
The environment builds a flat numpy array with:
- Patient: severity (normalised), latitude, longitude, traffic factor
- Per hospital (ร—5): bed availability, ICU availability, distance, wait time
- Per ambulance (ร—4): distance to patient, availability flag

**Total observation size: 4 + 5ร—4 + 4ร—2 = 32 floats**

### Action Space
`Discrete(20)` โ€” one action per (hospital, ambulance) combination.
```python
action = hospital_id * num_ambulances + ambulance_id
```

### Reward Function
```
+100  patient admitted
+70   critical patient (severity โ‰ฅ 8) assigned ICU bed
+50   ambulance ETA < 10 minutes
+20   ambulance ETA < 20 minutes
-100  no bed available at hospital
-50   ambulance is busy
- distance_penalty (up to -40)
- wait_time_penalty (up to -30)
- severity_delay_penalty (critical patient + high ETA)
```

### Usage
```python
from openenv_env.healthcare_env import HealthcareRoutingEnv

env = HealthcareRoutingEnv(render_mode="human")
obs, info = env.reset()

for _ in range(100):
    action = env.get_greedy_action()      # or your RL policy
    obs, reward, terminated, truncated, info = env.step(action)
    if terminated or truncated:
        obs, info = env.reset()
```

---

## ๐Ÿš€ Training the DQN Model

```bash
cd rl

# Quick training (300 episodes)
python train.py

# Production training
python train.py --episodes 1000 --steps 150 --lr 0.0005

# With console rendering
python train.py --episodes 100 --render
```

The trained model is saved to `rl/models/dqn_healthcare.pth`.

**Once trained**, the backend API will automatically load it and use DQN instead of the greedy fallback.

---

## ๐ŸŒ Backend API

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET  | `/` | Health check |
| POST | `/add_patient` | Register patient + get RL assignment |
| GET  | `/get_hospitals` | Live hospital bed counts |
| GET  | `/get_ambulances` | Live ambulance GPS positions |
| POST | `/assign_resources` | RL assignment without persisting |
| PUT  | `/update_ambulance_location` | Update GPS position |
| PUT  | `/update_hospital_beds` | Update bed availability |
| GET  | `/get_live_tracking` | Full snapshot (map view) |
| GET  | `/stats` | Dashboard statistics |
| GET  | `/simulation/start` | Start auto simulation |
| GET  | `/simulation/stop` | Stop simulation |
| WS   | `/ws/live` | Real-time WebSocket push |

**Example โ€” Add a patient:**
```bash
curl -X POST http://localhost:8000/add_patient \
  -H "Content-Type: application/json" \
  -d '{"name":"Ravi Kumar","severity":9.2,"lat":12.972,"lon":77.601}'
```

---

## ๐Ÿ—บ๏ธ Frontend Pages

| Page | Description |
|------|-------------|
| **Dashboard** | KPI cards, bed occupancy bar chart, ambulance status pie, recent patients, simulation toggle |
| **Live Map** | Leaflet map with moving ๐Ÿš‘ ambulances, ๐Ÿฅ hospitals (color-coded by occupancy), ๐Ÿค• patients. WebSocket updates every 2 seconds |
| **New Emergency** | Patient intake form with severity slider โ†’ instant RL dispatch result with reasoning |
| **Admin Panel** | Edit hospital beds/ICU/wait times inline, view ambulance statuses, full assignment history |

---

## ๐ŸŽฎ Simulation & Live Demo

1. Open the Dashboard tab
2. Click **โ–ถ๏ธ Start Simulation**
3. Switch to **Live Map** โ€” watch ambulances move in real-time
4. New simulated patients appear every ~6 seconds
5. Each patient is automatically assigned by the RL agent

For judges: the simulation creates realistic emergency scenarios with varying severity levels and traffic conditions to showcase the RL decision-making.

# ๐ŸŒŸ Core Features

### ๐Ÿง  AI-Powered Routing (PyTorch DQN)
The system's dispatch engine is powered by a custom-trained **Deep Q-Network (DQN)** built with PyTorch. 
- **Smart Dispatch:** Instead of using basic distance-based greedy algorithms, the AI evaluates patient severity, hospital bed/ICU availability, and real-time distance to make optimal routing decisions.
- **Seamless Integration:** The FastAPI backend automatically detects and loads the trained model weights (`rl/models/dqn_healthcare.pth`) at startup.

### ๐Ÿ™๏ธ 3D Cyberpunk Radar (Three.js)
The live tracking map features a fully interactive, real-time 3D cityscape of Solapur built with **Three.js**.
- **Dynamic Visuals:** Procedurally generated hospital buildings, pulsing patient spheres, and hovering ambulances with directional aiming.
- **Two-Phase Routing:** Visualizes the complete emergency lifecycle in real-timeโ€”blue dotted paths when en-route to the patient, and green paths during hospital transport.
- **Interactive:** Full drag, rotate, and zoom capabilities to monitor the dispatch grid.

---

## โ˜๏ธ Deployment

### Frontend โ†’ Vercel
```bash
cd frontend
npm run build
# Deploy dist/ folder to Vercel
vercel deploy
```

### Backend โ†’ Render
1. Create new Web Service on Render
2. Set build command: `pip install -r backend/requirements.txt`
3. Set start command: `uvicorn backend.api.main:app --host 0.0.0.0 --port $PORT`
4. Set env var: `PYTHONPATH=./openenv_env:./rl`

---

## ๐Ÿ† OpenEnv Submission

The `openenv_env/` folder contains the complete OpenEnv-spec submission:

```python
# Verify submission
cd openenv_env
python register.py         # test gym.make() works
python task.py             # run grader on random + greedy policies
```

**Grading criteria (100 pts total):**
- 40 pts โ€” Mean episode reward
- 30 pts โ€” Success rate (% assignments that succeed)
- 20 pts โ€” ICU assignment rate for critical patients
- 10 pts โ€” Ambulance utilisation

**Expected scores:**
- Random policy:  ~25โ€“35 pts
- Greedy policy:  ~55โ€“65 pts
- Trained DQN:    ~75โ€“90 pts

---

## ๐Ÿงช Running Tests

```bash
# Test RL environment
python -c "
from openenv_env.healthcare_env import HealthcareRoutingEnv
env = HealthcareRoutingEnv()
obs, _ = env.reset()
print('Obs shape:', obs.shape)
obs, r, term, trunc, info = env.step(0)
print('Reward:', r, '| Info:', info)
print('โœ… Environment OK')
"

# Test grader
cd openenv_env && python task.py

# Test backend (requires uvicorn running)
curl http://localhost:8000/stats
```

---

## ๐Ÿ‘ฅ Team & Acknowledgements

Built for **Meta PyTorch OpenEnv Hackathon x SST 2026**.

Team Members:
1. Rohan Belsare
2. Rajat Sahuji
3. Sanchita Patil

Tech Stack:
- [Meta OpenEnv](https://github.com/meta-pytorch/OpenEnv) โ€” environment spec
- [HuggingFace openenv-course](https://github.com/huggingface/openenv-course) โ€” reference implementation
- [PyTorch](https://pytorch.org) โ€” DQN training
- [Gymnasium](https://gymnasium.farama.org) โ€” RL API
- [FastAPI](https://fastapi.tiangolo.com) โ€” backend
- [React](https://react.dev) + [Leaflet](https://leafletjs.com) โ€” frontend