Back to blogVolver al blog

Bus Headways Analysis for Anomaly DetectionAnálisis de Headways de Autobús y Anomalías

Finished Bachelor in Telecomm. Engineering at UPM (Madrid) · Published in IEEE T-ITSTerminé el Grado en Ing. Telecom. en la UPM (Madrid) · Publicado en IEEE T-ITS

Anyone who regularly takes the city bus knows the feeling: you wait at the stop for twenty minutes with no sign of a bus, and then three of them arrive simultaneously, bumper-to-bumper. In public transit engineering, this phenomenon is known as bus bunching. But bunching is just one symptom of a broader challenge: how can transit authorities detect breakdowns, abnormal delays, schedule drift, and service anomalies in real time without having to install proprietary, expensive telemetry systems on thousands of vehicles? Quien coge el autobús urbano a diario conoce la sensación: esperas veinte minutos en la parada sin que llegue ninguno y, de pronto, aparecen tres a la vez, uno tras otro. En ingeniería del transporte público este fenómeno se conoce como bus bunching. Pero el bunching es solo un síntoma de un reto mayor: ¿cómo detectar averías, retrasos anómalos, desviaciones de horario y anomalías del servicio en tiempo real sin instalar sistemas de telemetría propietarios y caros en miles de vehículos?

That was the central question of my Bachelor's Thesis at Universidad Politécnica de Madrid (UPM) — developed during my first year as a Data Science Researcher intern at Cabify in Madrid — under the supervision of Prof. Pedro J. Zufiria and in collaboration with Carlos García-Mauriño. The work first produced two CSCI 2020 conference papers — “Headway Estimation in Urban Buses based on Available Arrival Time Estimators” and “Bus Pass Time Estimation based on Efficient Data Gathering from a Slow Mobility Server” — and later expanded into the full journal paper published in the IEEE Transactions on Intelligent Transportation Systems (T-ITS) (available in Early Access at the time):"Bus Headways Analysis for Anomaly Detection". Esa era la pregunta central de mi TFG en la Universidad Politécnica de Madrid (UPM) — desarrollado durante mi primer año como becario de investigación en Data Science en Cabify en Madrid — bajo la supervisión del Prof. Pedro J. Zufiria y en colaboración con Carlos García-Mauriño. El trabajo primero produjo dos papers de la conferencia CSCI 2020“Headway Estimation in Urban Buses based on Available Arrival Time Estimators” y “Bus Pass Time Estimation based on Efficient Data Gathering from a Slow Mobility Server” — y luego se amplió al artículo de revista completo publicado en IEEE Transactions on Intelligent Transportation Systems (T-ITS) (entonces en Early Access):"Bus Headways Analysis for Anomaly Detection".

🎤 Presenting at CSCI 2020🎤 Presentación CSCI 2020

Both CSCI 2020 papers were presented at the conference in December 2020, and the recorded talks live on the Cátedra Cabify-UPM YouTube channel — the university-industry chair created in October 2020 by Cabify and ETSIT-UPM to fund research scholarships in intelligent technologies and data science for sustainable mobility, co-directed by my thesis supervisor Prof. Pedro J. Zufiria. Ambos papers de CSCI 2020 se presentaron en la conferencia en diciembre de 2020; las charlas grabadas están en el canal de YouTube de la Cátedra Cabify-UPM, creada en octubre de 2020 por Cabify y ETSIT-UPM para financiar becas en tecnologías inteligentes y data science para la movilidad sostenible, y codirigida por mi supervisor de tesis, el Prof. Pedro J. Zufiria.

📺 Recorded conference talks from the Cátedra Cabify-UPM YouTube channel (CSCI 2020, virtual edition).📺 Charlas grabadas en el canal de YouTube de la Cátedra Cabify-UPM (CSCI 2020, edición virtual).

The Headway Paradigm: Why Arrival Gaps Tell the Whole StoryEl Paradigma del Headway: los Intervalos lo Dicen Todo

Most traditional approaches try to track individual bus trajectories using GPS coordinates or arrival timestamps. However, GPS pings in dense urban corridors suffer from multipath reflections, signal dropouts, and noisy stop matching. Instead, our core insight was to shift the modeling focus entirely to time headways. La mayoría de los enfoques tradicionales siguen trayectorias individuales con coordenadas GPS o marcas de llegada. Pero los pings GPS en corredores urbanos densos sufren reflexiones multicamino, pérdidas de señal y emparejado de paradas ruidoso. Nuestra idea clave fue centrar el modelado en los time headways.

A headway $h_k$ is defined as the elapsed time between the arrival of bus $k-1$ and bus $k$ on the same line at a specific stop (Figure 1). When a bus gets delayed, it encounters more passengers at subsequent stops, which increases dwell times and slows it down further. Meanwhile, the trailing bus encounters fewer passengers and speeds up until it catches the leader. This creates a strong statistical coupling between consecutive headways $(h_k, h_{k+1})$. Un headway $h_k$ se define como el tiempo transcurrido entre la llegada del autobús $k-1$ y el autobús $k$ en la misma línea y parada (Figura 1). Cuando un autobús se retrasa, encuentra más pasajeros en las paradas siguientes, lo que aumenta los tiempos de servicio y lo frena más. El que le sigue encuentra menos pasajeros y acelera hasta alcanzarlo. Esto crea un fuerte acoplamiento estadístico entre headways consecutivos $(h_k, h_{k+1})$.

Bus headway definition and consecutive arrival time modeling in urban transit corridors
Figure 1Figura 1Sequential bus headway formulation: tracking the time intervals between successive arrivals at a target bus stop to capture queue dynamics and operational deviations.Formulación secuencial del headway: intervalos entre llegadas sucesivas a una parada para capturar dinámicas de colas y desviaciones operativas.

Stochastic Bivariate Modeling & Operational Time SlicesModelado Bivariante Estocástico y Franjas de Operación

Urban traffic dynamics change drastically throughout the day. A 10-minute headway might be completely normal during the 3:00 PM off-peak window, but an indicator of major congestion during the 8:00 AM morning rush hour. To capture these non-stationary patterns, we partitioned the operating day into discrete time slices (morning peak, midday valley, afternoon peak, evening, night). La dinámica del tráfico urbano cambia drásticamente durante el día. Un headway de 10 minutos puede ser normal en el valle de las 3:00 PM, pero un indicador de congestión en hora punta de las 8:00 AM. Para capturar estos patrones no estacionarios dividimos el día en franjas discretas (punta de mañana, valle de mediodía, punta de tarde, noche).

Within each time slice, we model consecutive headway pairs $(h_k, h_{k+1})$ as samples from a joint bivariate distribution. From this stochastic framework, we compute bivariate sample means, covariance matrices, and confidence ellipses ($p = 95\%, 99\%$) as shown in Figure 2 for both the Madrid (EMT) and London (TfL) bus networks. En cada franja modelamos pares de headways consecutivos $(h_k, h_{k+1})$ como muestras de una distribución bivariante conjunta. Con este marco calculamos medias bivariantes, matrices de covarianza y elipses de confianza ($p = 95\%, 99\%$), como muestra la Figura 2 para Madrid (EMT) y Londres (TfL).

Bivariate confidence ellipses across operational time slices for Madrid EMT bus routes
Figure 2Figura 2Bivariate statistical confidence ellipses for consecutive headway pairs $(h_k, h_{k+1})$ across different operational time slices on Madrid EMT Line 27.Elipses de confianza bivariantes para pares de headways consecutivos $(h_k, h_{k+1})$ en distintas franjas operativas de la Línea 27 de EMT Madrid.

Real-Time Anomaly Scoring via Mahalanobis DistanceScoring de Anomalías en Tiempo Real (Mahalanobis)

With the baseline confidence ellipses established, real-time anomaly detection becomes elegant and computationally lightweight: Con las elipses de referencia establecidas, detectar anomalías en tiempo real es elegante y ligero computacionalmente:

  1. When a new bus arrives at a stop, the system computes the current headway pair $\mathbf{h} = [h_k, h_{k+1}]^T$.Cuando llega un autobús a una parada, se calcula el par de headways actual $\mathbf{h} = [h_k, h_{k+1}]^T$.
  2. It looks up the corresponding baseline mean $oldsymbol{\mu}_s$ and covariance matrix $oldsymbol{\Sigma}_s$ for that time slice.Busca la media de referencia $oldsymbol{\mu}_s$ y la matriz de covarianza $oldsymbol{\Sigma}_s$ de esa franja.
  3. It calculates the Mahalanobis distance:Calcula la distancia de Mahalanobis: $$D_M(\mathbf{h}) = \sqrt{(\mathbf{h} - oldsymbol{\mu}_s)^T oldsymbol{\Sigma}_s^{-1} (\mathbf{h} - oldsymbol{\mu}_s)}$$
  4. If $D_M(\mathbf{h})$ exceeds the calibrated threshold $\chi^2_{2, 1-lpha}$, the event is flagged as an operational anomaly with a tunable false-alarm rate $lpha$.Si $D_M(\mathbf{h})$ supera el umbral calibrado $\chi^2_{2, 1-lpha}$, el evento se marca como anomalía operativa con una tasa de falsa alarma ajustable $lpha$.
Anomaly detection time series showing flagged headway deviations and service irregularities
Figure 3Figura 3Real-time anomaly detection scoring on Madrid Line 27: the red markers highlight severe headway deviations, prolonged passenger waits, and bunching events.Scoring de anomalías en tiempo real en la Línea 27 de Madrid: los marcadores rojos señalan desviaciones graves de headway, esperas largas y bunching.

Validation on Madrid (EMT), London (TfL), and Black Swan EventsValidación en Madrid (EMT), Londres (TfL) y Eventos Black Swan

We deployed and validated our data processing pipeline on live open-data APIs from two of Europe's largest bus transit systems: EMT Madrid (analyzing the high-frequency Line 27 along Paseo de la Castellana) and Transport for London (TfL) (analyzing Route 25 through central London). Desplegamos y validamos nuestro pipeline sobre APIs open-data en vivo de dos de los mayores sistemas de autobuses de Europa: EMT Madrid (Línea 27 de alta frecuencia por el Paseo de la Castellana) y Transport for London (TfL) (Ruta 25 por el centro de Londres).

Beyond daily transit bunching and driver-relief gaps, the framework demonstrated remarkable sensitivity during macro-disruptions. As shown in Figure 4, our system clearly captured the radical structural transition in transit frequency during the initial onset of the March 2020 COVID-19 pandemic lockdown in Madrid, where headway distributions shifted drastically away from historical clusters. Más allá del bunching diario y los relevos de conductores, el framework mostró una sensibilidad notable ante macrocrisis. Como muestra la Figura 4, capturó la transición estructural radical en la frecuencia del servicio al inicio del confinamiento por COVID-19 en marzo de 2020 en Madrid, donde las distribuciones de headways se alejaron de los clústeres históricos.

Drastic shift in headway distribution during the COVID-19 lockdown transition in Madrid
Figure 4Figura 4Bivariate density shift of bus headways during the COVID-19 lockdown transition in Madrid, showing the departure from regular pre-pandemic operating regimes.Desplazamiento de la densidad bivariante de los headways en el confinamiento por COVID-19 en Madrid, fuera de los regímenes operativos prepandémicos.

The repository ships a full interactive web dashboard so you can inspect the whole pipeline in action. Figure 5 shows the London (TfL) live cockpit with its 2D trajectory rotation view, letting operators observe how consecutive headway pairs drift through the bivariate confidence state space in real time. El repositorio incluye un dashboard web interactivo para ver el pipeline en acción. La Figura 5 muestra la cabina en vivo de Londres (TfL) con su vista 2D rotatoria, para observar cómo los pares de headways consecutivos se desplazan por el espacio de estados de confianza bivariante en tiempo real.

London TfL headway dashboard with 2D rotation view of bivariate state space
Figure 5Figura 5The London (TfL) monitoring cockpit: real-time 2D-rotated view of consecutive headway pairs traversing the bivariate confidence state space.Cabina de Londres (TfL): vista 2D rotada en tiempo real de pares de headways consecutivos en el espacio de estados de confianza bivariante.

All data ingestion scripts, stochastic modeling pipelines, and evaluation notebooks are open source on GitHub. Los scripts de ingesta, los pipelines de modelado y los notebooks de evaluación son open source en GitHub.

July 2020 · BSc Thesis & IEEE T-ITSJulio 2020 · TFG & IEEE T-ITSGitHubCSCI 2020 · Headway EstimationCSCI 2020 · Bus Pass TimeCátedra Cabify-UPMTalk · Headway EstimationTalk · Headway EstimationTalk · Bus Pass TimeTalk · Bus Pass TimeUPM Thesis PDFTesis UPM PDFUPM

Alejandro Jarabo-Peñas, Pedro J. Zufiria, Carlos García-Mauriño