File size: 11,486 Bytes
81cfe79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Delhi Pulse β€” Technical Note

## 1. System overview

**What we built:** a travel-time model and journey planner that treats every
DTC bus as a moving traffic sensor, processing **31 days of October GPS**
(912.9M raw pings, 560.6M kept) through a four-stage pipeline into a
quantile-edge model β€” **853,480 (route, edge, hour) cells with real

p10/p50/p90 quantiles, trained on 39.2M edge traversals from 1,073,526

observed bus trips** β€” served by an API with transfers, headway-aware waits,
time-travel replay, and a live GTFS-RT blend layer.

## 2. Data volume

| Layer | Volume |
|---|---|
| Raw GPS observations | 912.9 million pings / 31 days |
| Kept after cleaning | 560.6 million (59.5-66.3% per day) |
| Edge traversal records | 39.2 million |
| Trips matched to shapes | 1,073,526 (92% match rate) |
| Routes modeled | 2,303 (99.4% route match to GTFS) |
| Edge x hour quantile cells | 853,480 |
| Route x hour speed cells | 40,211 |
| Route x hour headway cells | 41,844 |

## 3. Pipeline architecture

```

Stage 01  Extract: single-day SQLite from 7z archive (16.25 GB)

Stage 02  Clean: one parallel columnar SQL statement (DuckDB sqlite-scanner)

          - dedupe, bbox, teleport filter -> ~26 s per 28.7M-ping day

Stage 03  Project: best-shape-fit map matching + gap segmentation

          - 8-worker parallel, runtime-label trip_id (`route_HH_MM`)

Stage 04  Train: quantile aggregates (p10/p50/p90 per route, edge, hour)

Stage 04f Ping-pair speeds (no GTFS needed) + depot-creep filter

Stage 04g Headways from trip labels (services/hour -> wait = h/2)

Stage 05  Network-wide speed aggregates

```

## 4. Key discovery: trip_id is a runtime label



The GPS `trip_id` is `route_HH_MM[_n]` (e.g. `1795_19_31`), NOT a static

GTFS trip_id. Stage 03 handles this by keying on `route_id`, trying each of

the route's real shapes (both directions), and picking the best fit by

median ping-to-shape distance. Gap segmentation (>10 min between pings)

splits the 24-hour "trip" spans caused by label reuse across service blocks.



## 5. Travel-time model



```

(route, from_stop, to_stop, hour) -> p10/p50/p90 seconds     853,480 cells

(route, hour)                     -> speed km/h               40,211 cells

(route)                           -> speed km/h                2,303 rows

(hour)                            -> city speed km/h               24 rows

(route, hour)                     -> services -> wait         41,844 cells

```



Cells are trained with a **minimum of 5 observations**; sparse cells

(5 ≀ n < 24) are **shrunk toward the time implied by their route's

hour-of-day speed** with a pseudo-count of 10, and their p10-p90 widths

scale by n/(n+10). A cell cannot be an extreme median from a handful of

noisy traversals. (Model version `v1.1-quantiles-shrunk`.)



Dwell (stop waiting) is included in passage-to-passage time spans β€” that is

what a rider experiences β€” and the data decomposition allows reporting it

separately. The ping-pair layer (which operates without GTFS) applies a

3 km/h floor to filter depot/creep contamination and a 90 km/h ceiling

for GPS noise.



Waiting times are extracted from the feed's own trip labels: distinct

`route_HH_MM` labels per hour, averaged across days, equals services/hour.

Headway = 3600/n, wait = headway/2, clamped to [0.75, 15] minutes.



## 6. Combining live and historical



One code path: `est = alpha * recent + (1-alpha) * historical`. Sources:

- **live**: GTFS-RT poller (10s cadence), 45-minute rolling window

- **replay**: `?asOf=` with a date (day-level) or timestamp (45-min window)



The replay mode exercises the identical blend code against the October

archive, enabling verification of real-time accuracy against ground truth.



## 7. Validation results (leave-one-day-out, 31 folds)



> **Correction (2026-11-16):** the first deployed model's hour bins were

> misaligned by 5.5 hours. `hour(to_timestamp(ts + 19800))` applies the IST
> offset a second time whenever the DuckDB session timezone is IST β€” which
> every locally-run training pass was. The deployed Worker actually serves
> with UTC-session semantics, so its bins were correct; the artifacts built
> locally were shifted, flattening the by-hour signal. All binning is now
> pure integer arithmetic (`((ts+19800)//3600)%24`), regression-tested under
> three session timezones (`tests/test_time_bins.py`), and the full-month
> retrain ran on UTC infrastructure with the fix verified live: the city
> speed curve now peaks at 18.8 km/h at 18:00 IST against 31.0 km/h at
> 03:00 IST.

### 7.1 Speed model (route x hour)

| Metric | Value |
|---|---|
| Days cleaned | **31 (day 16 excluded from edge cells; its pings feed speeds)** |
| Pings kept | **560.6M of 912.9M (61.4%)** |
| Cells evaluated | 801,551 |
| **Model MAE** | **1.96 km/h** |
| City-hour baseline | 3.07 km/h |
| **Lift** | **36.1%** |

A day-of-week variant was retested at the full month, as the harness
prescribes: the dow arm degraded MAE by 9.8% against the pooled model
(weekends are still too thin to model separately), so route-hour pooling
remains the served model arm. The retest, the rejection, and the arm's
permanently-off switch (`USE_DOW = False`) are decided by the same
leave-one-day-out harness that produces the numbers above.

### 7.2 Journey replay (stop-to-stop, real traversals)

| Metric | Day 13 (365 samples) | Days 28-30 (72 samples) |
|---|---|---|
| Ride MAE | 1.66 min | 1.22 min |
| Within 5 min | 93.3% | 94.4% |
| Within 10 min | 98.1% | 100% |
| Coverage (actual route in top-6) | 57% | 50% |
| **No-option rate** | **0%** | **0%** |

The 43-50% where the planner didn't reproduce the sampled route means
it offered a *different* (typically faster or fewer-transfer) option β€”
the planner always answers.

### 7.3 Google Maps comparison (20 Delhi landmark pairs)

Live comparison against the **Google Routes API v2** (`computeRoutes`,
travelMode `DRIVE`, routingPreference `TRAFFIC_AWARE`) at the exact same
departure instant our planner is queried at β€” Wednesday 2026-11-18, 09:00 IST
(rush) and 15:00 IST (quiet). All values are real API responses collected by
`validation/gmaps_routes.py`; detailed table: `docs/od_comparison.json`.
Our side is the live Cloudflare Worker (`/api/journeys`), not a local copy.

| OD pair | Our bus (min) | Google car + traffic (min) | Ratio |
|---|---|---|---|
| Kashmere Gate ISBT β†’ Nehru Place | 54.6 | 46.5 | 1.17Γ— |
| Anand Vihar ISBT β†’ Dhaula Kuan | 66.6 | 70.2 | 0.95Γ— |
| AIIMS β†’ Rohini West | 100.9 | 51.2 | 1.97Γ— |
| IIT Delhi β†’ India Gate | 47.1 | 21.1 | 2.23Γ— |
| Sarojini Nagar β†’ IHC | 33.4 | 16.8 | 1.99Γ— |
| Kalkaji Mandir β†’ Karol Bagh | 95.5 | 53.1 | 1.80Γ— |

Across all 20 pairs the bus:car ratio at rush hour is **0.95×–2.23Γ—

(median 1.62Γ—)** β€” physically correct: buses share road space with cars and
add dwell (stops) and signal overhead, which compounds on cross-town
journeys. Note our planner *beats* the car on Anand Vihar β†’ Dhaula Kuan
because the bus takes the direct Ring Road pattern while Google's car route
detours (26.7 km for a 16 km crow-fly). 20/20 pairs answered by the deployed
planner (9 of them require a transfer, which the edge worker rebuilds via
its 1-transfer search). Re-measured 2026-11-16 against the full-month model
after the hour-bin fix; median moved from 1.60Γ— to 1.62Γ— because the served
route speeds barely changed β€” the local artifacts carried the bug, the
sensible deployed curve did not. All values reproducible via
`validation/gmaps_routes.py --reuse-google`.

**Why the Google comparison is driving, not transit (documented honestly):**
the Routes API v2 has **no transit coverage for Delhi** β€” TRANSIT requests
return a walking fallback (zero transit legs) even for pure metro pairs
such as Kashmere Gate β†’ Rajiv Chowk (3 stops on the Yellow Line). The
legacy Directions/Distance Matrix APIs, which historically carried Delhi
transit, cannot be enabled on new Google Maps projects (HTTP 403
LegacyApiNotActivatedMapError). So the reproducible, audited comparison at
scale is Google's traffic-aware driving time; this limitation (and the
walk-fallback probe) is recorded in `validation/gmaps_routes.py`.

### 7.4 Google Maps Platform integration (product feature)

The planner isn't just *validated* against Google β€” it now uses Google's
advanced APIs as a first-class part of the product:

* **Places search.** The planner UI searches any Delhi landmark, market,
  mall or hospital, not just the 6,862 DTC stops. Typing shows two groups:
  `🚏 Bus stops` (our GTFS index, instant) and `πŸ“ Places Β· Google`
  (Places API (New) autocomplete, scoped to a Delhi-NCR bounding box).
  Choosing a place resolves it to coordinates via the Places details
  endpoint and feeds it into the journey search.
* **Live traffic comparison.** Every result set is annotated with Google's
  traffic-aware driving time (Routes API v2, `TRAFFIC_AWARE`) for the same
  departure β€” the planner displays "πŸš— Google Maps drive: X min Β· 🚌 our
  best bus: Y min Β· ratio". Verified end-to-end: Nehru Planetarium β†’
  Select Citywalk Mall renders 61 min by bus vs 56 min by car (1.08Γ—).
* **Key security.** Two Google keys, both stored as Cloudflare Worker
  *secrets*. The server key (`GOOGLE_MAPS_KEY`, restricted to Places and
  Routes) is only used inside the Worker and the browser never sees it; all
  server-side Google calls are proxied through three documented endpoints:
  `/api/places/autocomplete`, `/api/places/resolve`, `/api/gmaps-drive`.
  The Maps JavaScript API cannot run without a key in the page, so the
  basemap uses a separate browser key (`GOOGLE_MAPS_BROWSER_KEY`) limited to
  the Maps JavaScript API and this site's HTTP referrer, served only to
  same-origin requests by `/api/maps-config`.

Two engineering notes for reproducibility: (1) Google's field masks must be
delivered via the `$fields` **query parameter** through Cloudflare Workers β€”
the `X-Goog-FieldMask` header is silently dropped by the Worker runtime for
these endpoints, which Google surfaces as "FieldMask is a required
parameter"; (2) the Routes API rejects `departureTime` values in the past
(even seconds stale), so the proxy clamps out-of-window departures and lets
Google fall back to live traffic.

## 8. Limitations

- Walk legs are straight-line x1.33 (OSRM upgrade pending)
- ETA p10/p90 sum per-leg quantiles (independence approximation)
- Day-of-week keying armed but disabled (requires >1 month)
- Day 16 excluded from stop-level model (pathological archive member);
  its GPS data still enters the speed/aggregate layers
- 7z global SHA256 does not verify on our copy (concurrent resume
  corruption; individual members validated at extraction)

## 9. Deployment

- **Edge (laptop-free):** Cloudflare Workers + D1 in APAC
  `https://delhi-pulse.prayaas.workers.dev` β€” real route shapes, speeds,
  headways, City Pulse map
- **Full planner (tunneled):** FastAPI on the machine, Cloudflare Tunnel
  for public URL β€” full journey planner with transfers, replay, live blend
- **Reproducibility:** `pip install -r requirements.txt` + full pipeline runs
  from scratch; synthetic fixture for end-to-end testing without downloads
- **Open source:** `github.com/crystalcoderz/delhi-pulse`