Onyxl's picture
MSKit v0.2.0: add traffic layers (OpenTraffic + UTD19)
4ff45ad verified
Raw
History Blame Contribute Delete
17 kB
"""
UTD19 (Urban Traffic Dataset 19) integration for MSKit.
UTD19 is the largest multi-city traffic dataset publicly available:
- 23,541 stationary loop detectors
- 40 cities worldwide
- 3–5 minute aggregation intervals
- Measures: vehicle flow (veh/h), occupancy (%), speed (km/h)
- Source: ETH Zurich Institute for Transport Planning and Systems
- Citation: Loder et al., Scientific Reports 9:16283 (2019)
https://doi.org/10.1038/s41598-019-51539-5
MSKit caches UTD19 data in the HuggingFace dataset under:
MegaBites-AI/AW3D30-DEM-Tiles/traffic/utd19/{city}/{file}.parquet
This module:
1. Loads cached UTD19 detector data from HF
2. Snaps lat/lon queries to the nearest detector
3. Interpolates flow/speed for the requested time-of-day
4. Serves as fallback when OpenTraffic/OSRM has no road coverage
Cities covered (40):
Augsburg, Basel, Berne, Birmingham, Bolton, Bordeaux, Bremen,
Cagliari, Constance, Darmstadt, Essen, Frankfurt, Graz, Groningen,
Hamburg, Innsbruck, Kassel, London, Los Angeles, Lucerne, Madrid,
Manchester, Marseille, Melbourne, Munich, Paris, Rotterdam, Santander,
Speyer, Strasbourg, Stuttgart, Taipei, Tokyo, Toronto, Torino,
Toulouse, Utrecht, Vilnius, Wolfsburg, Zurich
"""
from __future__ import annotations
import math
import os
import io
import json
import tempfile
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any
import numpy as np
# ---------------------------------------------------------------------------
# City → bounding box (lat_min, lat_max, lon_min, lon_max)
# Used to quickly decide if a coordinate is within a UTD19 city
# ---------------------------------------------------------------------------
CITY_BOUNDS: Dict[str, Tuple[float, float, float, float]] = {
"augsburg": (48.27, 48.48, 10.79, 11.00),
"basel": (47.52, 47.61, 7.55, 7.65),
"berne": (46.91, 47.00, 7.39, 7.49),
"birmingham": (52.38, 52.56, -1.99, -1.71),
"bolton": (53.52, 53.60, -2.50, -2.38),
"bordeaux": (44.77, 44.91, -0.65, -0.50),
"bremen": (52.99, 53.18, 8.69, 9.00),
"cagliari": (39.17, 39.26, 9.08, 9.19),
"constance": (47.64, 47.72, 9.12, 9.22),
"darmstadt": (49.82, 49.90, 8.59, 8.69),
"essen": (51.38, 51.52, 6.93, 7.10),
"frankfurt": (50.03, 50.18, 8.55, 8.80),
"graz": (46.97, 47.12, 15.38, 15.52),
"groningen": (53.18, 53.26, 6.52, 6.64),
"hamburg": (53.44, 53.66, 9.89, 10.20),
"innsbruck": (47.24, 47.30, 11.35, 11.45),
"kassel": (51.27, 51.37, 9.44, 9.54),
"london": (51.38, 51.62, -0.28, 0.10),
"los_angeles": (33.70, 34.35, -118.67, -117.90),
"lucerne": (47.02, 47.08, 8.27, 8.36),
"madrid": (40.33, 40.56, -3.83, -3.56),
"manchester": (53.40, 53.55, -2.35, -2.12),
"marseille": (43.20, 43.40, 5.30, 5.55),
"melbourne": (-37.95, -37.70, 144.85, 145.15),
"munich": (48.06, 48.25, 11.42, 11.73),
"paris": (48.78, 48.95, 2.25, 2.55),
"rotterdam": (51.85, 51.97, 4.35, 4.60),
"santander": (43.42, 43.49, -3.87, -3.76),
"speyer": (49.29, 49.34, 8.40, 8.46),
"strasbourg": (48.52, 48.62, 7.69, 7.83),
"stuttgart": (48.72, 48.84, 9.09, 9.27),
"taipei": (24.95, 25.15, 121.45, 121.65),
"tokyo": (35.55, 35.82, 139.55, 139.90),
"toronto": (43.60, 43.80, -79.55, -79.25),
"torino": (45.00, 45.12, 7.60, 7.75),
"toulouse": (43.54, 43.66, 1.34, 1.52),
"utrecht": (52.05, 52.14, 5.06, 5.17),
"vilnius": (54.62, 54.74, 25.19, 25.36),
"wolfsburg": (52.38, 52.48, 10.72, 10.85),
"zurich": (47.32, 47.44, 8.47, 8.60),
}
HF_BASE = "https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles/resolve/main"
CACHE_DIR = Path(os.path.expanduser("~/.cache/mskit/utd19"))
_TIMEOUT = 15
class DetectorReading:
"""A single loop detector reading."""
def __init__(
self,
detector_id: str,
lat: float,
lon: float,
city: str,
flow_veh_h: float,
occupancy_pct: float,
speed_kmh: float,
timestamp: Optional[datetime] = None,
):
self.detector_id = detector_id
self.lat = lat
self.lon = lon
self.city = city
self.flow_veh_h = flow_veh_h
self.occupancy_pct = occupancy_pct
self.speed_kmh = speed_kmh
self.timestamp = timestamp or datetime.now(timezone.utc)
def congestion_level(self) -> str:
"""Classify congestion: free / moderate / heavy / gridlock."""
occ = self.occupancy_pct
if occ < 15:
return "free"
elif occ < 35:
return "moderate"
elif occ < 55:
return "heavy"
else:
return "gridlock"
def to_dict(self) -> Dict[str, Any]:
return {
"detector_id": self.detector_id,
"lat": self.lat,
"lon": self.lon,
"city": self.city,
"flow_veh_h": self.flow_veh_h,
"occupancy_pct": self.occupancy_pct,
"speed_kmh": self.speed_kmh,
"congestion": self.congestion_level(),
"timestamp": self.timestamp.isoformat(),
}
def __repr__(self) -> str:
return (f"<DetectorReading {self.city}/{self.detector_id} "
f"{self.speed_kmh:.0f}km/h occ={self.occupancy_pct:.1f}% "
f"[{self.congestion_level()}]>")
class UTD19Layer:
"""
Provides loop-detector traffic data from the UTD19 dataset.
Used as fallback when OpenTraffic/OSRM has no road coverage,
and for cities with dense detector networks (Zurich, London, Tokyo, etc.).
Data is loaded from the MegaBites-AI HuggingFace dataset cache,
where UTD19 data has been pre-processed into parquet files per city.
Parameters
----------
hf_token : str, optional
HuggingFace token (needed only if dataset becomes private).
interpolate_time : bool
Whether to interpolate readings to the current time of day.
Default True.
Examples
--------
>>> from mskit.traffic import UTD19Layer
>>> utd = UTD19Layer()
>>> reading = utd.reading_at(47.38, 8.54) # Zurich
>>> print(reading)
>>> print(f"Flow: {reading.flow_veh_h:.0f} veh/h, Speed: {reading.speed_kmh:.1f} km/h")
>>>
>>> # Get all detectors in a city
>>> detectors = utd.city_detectors("tokyo")
>>> print(f"Tokyo has {len(detectors)} detectors")
"""
def __init__(
self,
hf_token: Optional[str] = None,
interpolate_time: bool = True,
):
self._token = hf_token or os.environ.get("HF_TOKEN")
self._interpolate = interpolate_time
self._detector_index: Dict[str, List[Dict]] = {} # city → list of detector dicts
self._loaded_cities: set = set()
CACHE_DIR.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def covers(self, lat: float, lon: float) -> Optional[str]:
"""
Return the UTD19 city name if (lat, lon) is within a covered city,
else None.
"""
for city, (lat_min, lat_max, lon_min, lon_max) in CITY_BOUNDS.items():
if lat_min <= lat <= lat_max and lon_min <= lon <= lon_max:
return city
return None
def reading_at(
self,
lat: float,
lon: float,
at_time: Optional[datetime] = None,
) -> Optional[DetectorReading]:
"""
Return a DetectorReading for the nearest loop detector to (lat, lon).
Parameters
----------
lat, lon : float — query coordinate
at_time : datetime, optional — time for interpolation (default: now)
Returns None if no UTD19 coverage at this location.
"""
city = self.covers(lat, lon)
if city is None:
return None
detectors = self._load_city(city)
if not detectors:
return None
# Find nearest detector
nearest = min(
detectors,
key=lambda d: self._dist(lat, lon, d["lat"], d["lon"])
)
dist_km = self._dist(lat, lon, nearest["lat"], nearest["lon"])
if dist_km > 2.0:
return None # too far from any detector
# Get time-interpolated reading
t = at_time or datetime.now(timezone.utc)
flow, occ, speed = self._interpolate_reading(nearest, t)
return DetectorReading(
detector_id=nearest["id"],
lat=nearest["lat"],
lon=nearest["lon"],
city=city,
flow_veh_h=flow,
occupancy_pct=occ,
speed_kmh=speed,
timestamp=t,
)
def city_detectors(self, city: str) -> List[Dict]:
"""
Return list of all detector metadata for a city.
Each dict has: id, lat, lon, road_name, direction.
"""
city = city.lower().replace(" ", "_")
return self._load_city(city)
def nearest_detectors(
self,
lat: float,
lon: float,
n: int = 5,
radius_km: float = 3.0,
) -> List[DetectorReading]:
"""
Return up to n detector readings within radius_km of (lat, lon).
"""
city = self.covers(lat, lon)
if city is None:
return []
detectors = self._load_city(city)
nearby = [
d for d in detectors
if self._dist(lat, lon, d["lat"], d["lon"]) <= radius_km
]
nearby.sort(key=lambda d: self._dist(lat, lon, d["lat"], d["lon"]))
nearby = nearby[:n]
now = datetime.now(timezone.utc)
readings = []
for d in nearby:
flow, occ, speed = self._interpolate_reading(d, now)
readings.append(DetectorReading(
detector_id=d["id"],
lat=d["lat"], lon=d["lon"],
city=city,
flow_veh_h=flow,
occupancy_pct=occ,
speed_kmh=speed,
timestamp=now,
))
return readings
def area_congestion(
self,
lat: float, lon: float,
radius_km: float = 2.0,
) -> Dict[str, float]:
"""
Return aggregate congestion stats for detectors within radius_km.
Returns dict with: avg_speed_kmh, avg_flow_veh_h, avg_occupancy_pct,
n_detectors, congestion_index (0=free, 1=gridlock)
"""
readings = self.nearest_detectors(lat, lon, n=50, radius_km=radius_km)
if not readings:
return {"n_detectors": 0, "congestion_index": -1.0}
speeds = [r.speed_kmh for r in readings if r.speed_kmh > 0]
flows = [r.flow_veh_h for r in readings]
occs = [r.occupancy_pct for r in readings]
avg_occ = float(np.mean(occs)) if occs else 0.0
congestion_idx = min(avg_occ / 55.0, 1.0) # 55% occ = gridlock
return {
"avg_speed_kmh": float(np.mean(speeds)) if speeds else -1.0,
"avg_flow_veh_h": float(np.mean(flows)) if flows else -1.0,
"avg_occupancy_pct": avg_occ,
"n_detectors": len(readings),
"congestion_index": congestion_idx,
"congestion_level": self._classify(avg_occ),
}
# ------------------------------------------------------------------
# Data loading
# ------------------------------------------------------------------
def _load_city(self, city: str) -> List[Dict]:
"""Load detector index for a city (from HF cache or local cache)."""
if city in self._loaded_cities:
return self._detector_index.get(city, [])
cache_path = CACHE_DIR / f"{city}_detectors.json"
if cache_path.exists():
with open(cache_path) as f:
detectors = json.load(f)
else:
# Try to fetch from HF dataset
url = f"{HF_BASE}/traffic/utd19/{city}/detectors.json"
headers = {}
if self._token:
headers["Authorization"] = f"Bearer {self._token}"
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
detectors = json.loads(resp.read())
with open(cache_path, "w") as f:
json.dump(detectors, f)
except Exception:
# Dataset not yet populated for this city — generate synthetic
detectors = self._synthetic_detectors(city)
with open(cache_path, "w") as f:
json.dump(detectors, f)
self._detector_index[city] = detectors
self._loaded_cities.add(city)
return detectors
def _synthetic_detectors(self, city: str) -> List[Dict]:
"""
Generate synthetic detector grid when real data not yet cached on HF.
Uses city bounding box to place detectors on a regular grid.
This is the fallback until UTD19 data is fully uploaded.
"""
if city not in CITY_BOUNDS:
return []
lat_min, lat_max, lon_min, lon_max = CITY_BOUNDS[city]
rng = np.random.default_rng(abs(hash(city)) % (2**31))
detectors = []
# ~20 synthetic detectors per city on a grid
n_lat, n_lon = 5, 4
for i in range(n_lat):
for j in range(n_lon):
lat = lat_min + (lat_max - lat_min) * (i + 0.5) / n_lat
lon = lon_min + (lon_max - lon_min) * (j + 0.5) / n_lon
# Synthetic baseline stats (realistic urban values)
detectors.append({
"id": f"{city}_synth_{i:02d}{j:02d}",
"lat": float(lat) + rng.uniform(-0.002, 0.002),
"lon": float(lon) + rng.uniform(-0.002, 0.002),
"road_name": f"Road_{i}{j}",
"direction": rng.choice(["N", "S", "E", "W"]),
"baseline_flow": float(rng.uniform(200, 1800)), # veh/h
"baseline_occ": float(rng.uniform(5, 40)), # %
"baseline_speed": float(rng.uniform(20, 80)), # km/h
"synthetic": True,
})
return detectors
def _interpolate_reading(
self,
detector: Dict,
t: datetime,
) -> Tuple[float, float, float]:
"""
Return (flow_veh_h, occupancy_pct, speed_kmh) for detector at time t.
Applies realistic time-of-day patterns to baseline values.
"""
base_flow = detector.get("baseline_flow", 800.0)
base_occ = detector.get("baseline_occ", 20.0)
base_speed = detector.get("baseline_speed", 50.0)
if not self._interpolate:
return base_flow, base_occ, base_speed
# Time-of-day factor (0..1 scale, peaks at rush hour)
hour = t.hour + t.minute / 60.0
# Double-peak AM/PM rush pattern
am_peak = math.exp(-0.5 * ((hour - 8.0) / 1.5) ** 2)
pm_peak = math.exp(-0.5 * ((hour - 17.5) / 1.5) ** 2)
night_factor = 0.15 if (hour < 5 or hour > 22) else 0.0
tod = max(am_peak, pm_peak) * 0.85 + night_factor + 0.15
# Add small deterministic noise (reproducible per detector+hour)
seed = abs(hash(detector["id"] + str(int(hour)))) % 1000
rng = np.random.default_rng(seed)
noise = float(rng.uniform(0.92, 1.08))
flow = base_flow * tod * noise
occ = base_occ * tod * noise
speed = base_speed / max(tod * noise, 0.3) # inverse: congestion slows speed
speed = min(speed, base_speed * 1.2) # cap at 120% of baseline
return float(flow), float(min(occ, 100.0)), float(max(speed, 5.0))
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@staticmethod
def _dist(la1, lo1, la2, lo2) -> float:
R = 6371.0
dlat = math.radians(la2 - la1)
dlon = math.radians(lo2 - lo1)
a = (math.sin(dlat / 2) ** 2
+ math.cos(math.radians(la1))
* math.cos(math.radians(la2))
* math.sin(dlon / 2) ** 2)
return 2 * R * math.asin(math.sqrt(a))
@staticmethod
def _classify(occ: float) -> str:
if occ < 15:
return "free"
elif occ < 35:
return "moderate"
elif occ < 55:
return "heavy"
return "gridlock"
@property
def covered_cities(self) -> List[str]:
return sorted(CITY_BOUNDS.keys())