-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulator.py
More file actions
447 lines (389 loc) · 14.5 KB
/
Copy pathsimulator.py
File metadata and controls
447 lines (389 loc) · 14.5 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"""
simulator.py — Venue seeding, attendee state machine, crowd density tracking.
All state lives in module-level dicts; no database.
"""
import random
import asyncio
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional
# ---------------------------------------------------------------------------
# Venue definition — Wankhede Stadium, Mumbai
# ---------------------------------------------------------------------------
VENUE_NAME = "Wankhede Stadium"
EVENT_NAME = "IPL Final 2025 — Mumbai Indians vs Chennai Super Kings"
VENUE_CENTER = {"lat": 18.9388, "lng": 72.8252}
# 8 gates placed around the stadium perimeter (~150 m radius)
GATES: Dict[str, dict] = {
"G1": {
"name": "Gate 1 — North Stand",
"lat": 18.9403,
"lng": 72.8252,
"capacity": 2200,
"direction": "North",
"transit": "metro",
},
"G2": {
"name": "Gate 2 — NE Corner",
"lat": 18.9399,
"lng": 72.8268,
"capacity": 1600,
"direction": "NE",
"transit": "metro",
},
"G3": {
"name": "Gate 3 — East Stand",
"lat": 18.9388,
"lng": 72.8272,
"capacity": 2000,
"direction": "East",
"transit": "metro",
},
"G4": {
"name": "Gate 4 — SE Corner",
"lat": 18.9377,
"lng": 72.8268,
"capacity": 1500,
"direction": "SE",
"transit": "bus",
},
"G5": {
"name": "Gate 5 — South Stand",
"lat": 18.9373,
"lng": 72.8252,
"capacity": 2400,
"direction": "South",
"transit": "bus",
},
"G6": {
"name": "Gate 6 — SW Corner",
"lat": 18.9377,
"lng": 72.8236,
"capacity": 1400,
"direction": "SW",
"transit": "bus",
},
"G7": {
"name": "Gate 7 — West Stand",
"lat": 18.9388,
"lng": 72.8232,
"capacity": 2000,
"direction": "West",
"transit": "taxi",
},
"G8": {
"name": "Gate 8 — NW Corner",
"lat": 18.9399,
"lng": 72.8236,
"capacity": 1700,
"direction": "NW",
"transit": "taxi",
},
}
TRANSIT_NODES: Dict[str, dict] = {
"metro": {
"name": "Churchgate Metro Station",
"lat": 18.9352,
"lng": 72.8259,
"capacity": 6000,
"walk_min": 8,
"icon": "🚇",
},
"bus": {
"name": "Marine Lines Bus Depot",
"lat": 18.9330,
"lng": 72.8245,
"capacity": 4000,
"walk_min": 12,
"icon": "🚌",
},
"taxi": {
"name": "Wankhede Taxi Stand",
"lat": 18.9410,
"lng": 72.8268,
"capacity": 2500,
"walk_min": 5,
"icon": "🚕",
},
}
# 20 sections A–T with gate assignments
SECTIONS: Dict[str, dict] = {
"A": {"gate": "G1", "size": 750, "stand": "North"},
"B": {"gate": "G1", "size": 750, "stand": "North"},
"C": {"gate": "G1", "size": 750, "stand": "North"},
"D": {"gate": "G2", "size": 750, "stand": "North-East"},
"E": {"gate": "G2", "size": 750, "stand": "North-East"},
"F": {"gate": "G3", "size": 750, "stand": "East"},
"G": {"gate": "G3", "size": 750, "stand": "East"},
"H": {"gate": "G3", "size": 750, "stand": "East"},
"I": {"gate": "G4", "size": 750, "stand": "South-East"},
"J": {"gate": "G4", "size": 750, "stand": "South-East"},
"K": {"gate": "G5", "size": 750, "stand": "South"},
"L": {"gate": "G5", "size": 750, "stand": "South"},
"M": {"gate": "G5", "size": 750, "stand": "South"},
"N": {"gate": "G6", "size": 750, "stand": "South-West"},
"O": {"gate": "G6", "size": 750, "stand": "South-West"},
"P": {"gate": "G7", "size": 750, "stand": "West"},
"Q": {"gate": "G7", "size": 750, "stand": "West"},
"R": {"gate": "G7", "size": 750, "stand": "West"},
"S": {"gate": "G8", "size": 750, "stand": "North-West"},
"T": {"gate": "G8", "size": 750, "stand": "North-West"},
}
# Gate → departure wave (0–7). Adjacent sections staggered so no pile-up at T+0.
GATE_WAVE: Dict[str, int] = {
"G1": 0, "G2": 3, "G3": 1, "G4": 4,
"G5": 2, "G6": 5, "G7": 3, "G8": 6,
}
# Wave start offsets in minutes from event end
WAVE_OFFSET_MIN = [0, 6, 12, 18, 24, 30, 36, 42]
# ---------------------------------------------------------------------------
# Attendee dataclass
# ---------------------------------------------------------------------------
@dataclass
class Attendee:
ticket_id: str
section: str
gate_id: str
seat_row: int
wave: int
transit: str
depart_offset_min: float # minutes after event end to leave seat
state: str = "seated" # seated | walking | at_gate | dispersed
state_entered_at: float = field(default_factory=time.monotonic)
# ---------------------------------------------------------------------------
# Shared simulation state (module-level, in-memory)
# ---------------------------------------------------------------------------
attendees: Dict[str, Attendee] = {}
gate_state: Dict[str, dict] = {}
transit_state: Dict[str, dict] = {}
dispersal_stats: dict = {}
active_alerts: List[dict] = []
dispersal_strategy_text: str = "" # Cached Gemini output
sim_start_time: float = 0.0
sim_tick: int = 0
# Track how long each gate has been dense (for alert rule)
_gate_dense_ticks: Dict[str, int] = {}
_alert_seen: Dict[str, float] = {} # gate_id → last alert timestamp
# ---------------------------------------------------------------------------
# Seeding
# ---------------------------------------------------------------------------
def seed(strategy_override: Optional[dict] = None) -> None:
"""Seed 15,000 attendees and initialise crowd state."""
global sim_start_time, sim_tick
random.seed(42)
attendees.clear()
gate_state.clear()
transit_state.clear()
active_alerts.clear()
_gate_dense_ticks.clear()
_alert_seen.clear()
sim_start_time = time.monotonic()
sim_tick = 0
# Initialise gate crowd state
for gid, gdata in GATES.items():
gate_state[gid] = {
"gate_id": gid,
"name": gdata["name"],
"lat": gdata["lat"],
"lng": gdata["lng"],
"capacity": gdata["capacity"],
"current_count": 0,
"density_pct": 0.0,
"color": "green",
"transit": gdata["transit"],
}
_gate_dense_ticks[gid] = 0
# Initialise transit crowd state
for tid, tdata in TRANSIT_NODES.items():
transit_state[tid] = {
"transit_id": tid,
"name": tdata["name"],
"lat": tdata["lat"],
"lng": tdata["lng"],
"capacity": tdata["capacity"],
"current_count": 0,
"density_pct": 0.0,
"color": "green",
"walk_min": tdata["walk_min"],
}
# Seed attendees
ticket_counter = 1
for section, sdata in SECTIONS.items():
gate_id = sdata["gate"]
transit_id = GATES[gate_id]["transit"]
base_wave = GATE_WAVE[gate_id]
# Allow strategy override to adjust wave
if strategy_override and gate_id in strategy_override:
base_wave = strategy_override[gate_id].get("wave", base_wave)
for i in range(sdata["size"]):
ticket_id = f"TKT-{ticket_counter:05d}"
ticket_counter += 1
wave = base_wave
# Small jitter within wave (±2 min) to avoid hard spikes
offset = WAVE_OFFSET_MIN[wave] + random.uniform(-2, 2)
offset = max(0, offset)
attendees[ticket_id] = Attendee(
ticket_id=ticket_id,
section=section,
gate_id=gate_id,
seat_row=random.randint(1, 30),
wave=wave,
transit=transit_id,
depart_offset_min=offset,
state="seated",
state_entered_at=sim_start_time,
)
_update_stats()
def get_demo_ticket() -> str:
"""Return a consistent demo ticket ID for the landing page."""
return "TKT-00042"
def get_attendee_context(ticket_id: str) -> Optional[dict]:
"""Return a rich dict describing the attendee's plan (for Gemini system prompt)."""
a = attendees.get(ticket_id)
if not a:
return None
gate = GATES[a.gate_id]
transit = TRANSIT_NODES[a.transit]
wave_offset = WAVE_OFFSET_MIN[a.wave]
return {
"ticket_id": ticket_id,
"section": a.section,
"seat_row": a.seat_row,
"gate_id": a.gate_id,
"gate_name": gate["name"],
"gate_direction": gate["direction"],
"transit_name": transit["name"],
"transit_icon": transit["icon"],
"transit_walk_min": transit["walk_min"],
"wave": a.wave,
"depart_offset_min": round(a.depart_offset_min, 1),
"state": a.state,
"transit_id": a.transit,
"event_name": EVENT_NAME,
"venue_name": VENUE_NAME,
"gate_density_pct": gate_state[a.gate_id]["density_pct"],
"gate_color": gate_state[a.gate_id]["color"],
}
# ---------------------------------------------------------------------------
# Simulation tick
# ---------------------------------------------------------------------------
SECONDS_PER_SIM_MINUTE = 3 # 1 sim-minute = 3 real seconds → 45 sim-min = 135 s
def _elapsed_sim_minutes() -> float:
elapsed_real_sec = time.monotonic() - sim_start_time
return elapsed_real_sec / SECONDS_PER_SIM_MINUTE
def tick() -> None:
"""Advance simulation state. Called every 5 real seconds."""
global sim_tick
sim_tick += 1
elapsed = _elapsed_sim_minutes()
# Reset gate/transit counts
for gs in gate_state.values():
gs["current_count"] = 0
for ts in transit_state.values():
ts["current_count"] = 0
for a in attendees.values():
if a.state == "seated":
if elapsed >= a.depart_offset_min:
a.state = "walking"
a.state_entered_at = time.monotonic()
elif a.state == "walking":
# Walking takes 2–4 sim minutes
walk_time = (time.monotonic() - a.state_entered_at) / SECONDS_PER_SIM_MINUTE
if walk_time >= random.uniform(2, 4):
a.state = "at_gate"
a.state_entered_at = time.monotonic()
gate_state[a.gate_id]["current_count"] += 1
elif a.state == "at_gate":
gate_state[a.gate_id]["current_count"] += 1
# Processing at gate takes 3–7 sim minutes
gate_time = (time.monotonic() - a.state_entered_at) / SECONDS_PER_SIM_MINUTE
if gate_time >= random.uniform(3, 7):
a.state = "dispersed"
a.state_entered_at = time.monotonic()
transit_state[a.transit]["current_count"] += 1
elif a.state == "dispersed":
# Still contribute to transit count briefly (5 sim-min)
disp_time = (time.monotonic() - a.state_entered_at) / SECONDS_PER_SIM_MINUTE
if disp_time < 5:
transit_state[a.transit]["current_count"] += 1
# Update density %
for gid, gs in gate_state.items():
raw = gs["current_count"] / gs["capacity"]
# Add Gaussian noise for realism
noisy = max(0.0, min(1.0, raw + random.gauss(0, 0.02)))
gs["density_pct"] = round(noisy, 3)
gs["color"] = _density_color(noisy)
# Track dense ticks for alert rule
if noisy > 0.85:
_gate_dense_ticks[gid] += 1
else:
_gate_dense_ticks[gid] = 0
for tid, ts in transit_state.items():
raw = ts["current_count"] / ts["capacity"]
noisy = max(0.0, min(1.0, raw + random.gauss(0, 0.01)))
ts["density_pct"] = round(noisy, 3)
ts["color"] = _density_color(noisy)
_update_alerts()
_update_stats()
def _density_color(density: float) -> str:
if density < 0.60:
return "green"
if density < 0.85:
return "yellow"
return "red"
def _update_alerts() -> None:
"""Apply the >85% for >2 ticks rule. Does NOT call Gemini (done in main.py)."""
seen_gates = {a["gate_id"] for a in active_alerts}
for gid, dense_ticks in _gate_dense_ticks.items():
if dense_ticks >= 2 and gid not in seen_gates:
gs = gate_state[gid]
# Find affected sections
affected = [s for s, sd in SECTIONS.items() if sd["gate"] == gid]
pending = sum(
1 for a in attendees.values()
if a.gate_id == gid and a.state in ("seated", "walking", "at_gate")
)
active_alerts.append({
"alert_id": f"ALT-{gid}-{sim_tick}",
"gate_id": gid,
"gate_name": gs["name"],
"density_pct": gs["density_pct"],
"dense_ticks": dense_ticks,
"affected_sections": affected,
"pending_attendees": pending,
"suggestion": None, # Filled by gemini_client in main.py
"created_at": time.time(),
})
# Remove stale alerts where gate is now green or resolved
to_remove = []
for alert in active_alerts:
gid = alert["gate_id"]
if gate_state[gid]["color"] == "green" and (time.time() - alert["created_at"]) > 60:
to_remove.append(alert)
for a in to_remove:
active_alerts.remove(a)
def _update_stats() -> None:
total = len(attendees)
seated = sum(1 for a in attendees.values() if a.state == "seated")
walking = sum(1 for a in attendees.values() if a.state == "walking")
at_gate = sum(1 for a in attendees.values() if a.state == "at_gate")
dispersed = sum(1 for a in attendees.values() if a.state == "dispersed")
dispersal_stats["total"] = total
dispersal_stats["seated"] = seated
dispersal_stats["walking"] = walking
dispersal_stats["at_gate"] = at_gate
dispersal_stats["dispersed"] = dispersed
dispersal_stats["pct_dispersed"] = round(dispersed / total * 100, 1) if total else 0
dispersal_stats["elapsed_sim_min"] = round(_elapsed_sim_minutes(), 1)
# Average wait estimate: remaining attendees × factor
remaining = total - dispersed
dispersal_stats["avg_wait_min"] = round((remaining / total) * 22, 1) if total else 0
def get_crowd_state_snapshot() -> dict:
"""Serialisable snapshot for /api/crowd_state."""
return {
"tick": sim_tick,
"elapsed_sim_min": dispersal_stats.get("elapsed_sim_min", 0),
"gates": list(gate_state.values()),
"transit": list(transit_state.values()),
"stats": dict(dispersal_stats),
}