|
| 1 | +"""Caching helpers for the map rendering pipeline. |
| 2 | +
|
| 3 | +Network fetches via osmnx are slow (seconds each, internet required). This |
| 4 | +module persists fetched graphs to disk and renders/persists tiles for an |
| 5 | +entire dataset in one batch so the DataLoader only ever reads PNGs. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +import math |
| 12 | +import pickle |
| 13 | +from pathlib import Path |
| 14 | +from typing import Mapping, Sequence |
| 15 | + |
| 16 | +import networkx as nx |
| 17 | + |
| 18 | +from .gps_to_map import ( |
| 19 | + DEFAULT_IMAGE_SIZE, |
| 20 | + DEFAULT_RADIUS_M, |
| 21 | + EARTH_RADIUS_M, |
| 22 | + fetch_road_network, |
| 23 | + map_match_waypoints, |
| 24 | + render_map_tile, |
| 25 | +) |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +def cache_network(graph: nx.MultiDiGraph, filepath: str | Path) -> None: |
| 31 | + """Pickle a road-network graph to disk.""" |
| 32 | + path = Path(filepath) |
| 33 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 34 | + with path.open("wb") as f: |
| 35 | + pickle.dump(graph, f) |
| 36 | + |
| 37 | + |
| 38 | +def load_cached_network(filepath: str | Path) -> nx.MultiDiGraph | None: |
| 39 | + """Load a pickled road-network graph, or `None` if the file is missing.""" |
| 40 | + path = Path(filepath) |
| 41 | + if not path.exists(): |
| 42 | + return None |
| 43 | + try: |
| 44 | + with path.open("rb") as f: |
| 45 | + return pickle.load(f) |
| 46 | + except (OSError, pickle.UnpicklingError) as exc: |
| 47 | + logger.warning("failed to load cached network %s: %s", path, exc) |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +def render_and_cache_tiles( |
| 52 | + dataset_gps_data: Mapping[str, tuple[Sequence[float], Sequence[float]]], |
| 53 | + output_dir: str | Path, |
| 54 | + radius_m: int = DEFAULT_RADIUS_M, |
| 55 | + image_size: tuple[int, int] = DEFAULT_IMAGE_SIZE, |
| 56 | + network_cache_dir: str | Path | None = None, |
| 57 | + skip_existing: bool = True, |
| 58 | +) -> list[Path]: |
| 59 | + """Pre-render and persist a BEV map tile for every clip in a dataset. |
| 60 | +
|
| 61 | + Args: |
| 62 | + dataset_gps_data: mapping of `clip_id -> (latitudes, longitudes)`. |
| 63 | + output_dir: where rendered PNG tiles are written (`{clip_id}.png`). |
| 64 | + radius_m: render radius around each clip's centroid. |
| 65 | + image_size: output `(W, H)`. |
| 66 | + network_cache_dir: if given, fetched graphs are persisted here keyed by |
| 67 | + centroid so neighbouring clips share a cached download. |
| 68 | + skip_existing: do not re-render clips whose PNG already exists. |
| 69 | +
|
| 70 | + Returns: |
| 71 | + List of paths to the rendered tile files (including pre-existing ones). |
| 72 | + """ |
| 73 | + out = Path(output_dir) |
| 74 | + out.mkdir(parents=True, exist_ok=True) |
| 75 | + net_cache = Path(network_cache_dir) if network_cache_dir else None |
| 76 | + if net_cache is not None: |
| 77 | + net_cache.mkdir(parents=True, exist_ok=True) |
| 78 | + |
| 79 | + rendered: list[Path] = [] |
| 80 | + for clip_id, (lats, lons) in dataset_gps_data.items(): |
| 81 | + tile_path = out / f"{clip_id}.png" |
| 82 | + if skip_existing and tile_path.exists(): |
| 83 | + rendered.append(tile_path) |
| 84 | + continue |
| 85 | + |
| 86 | + if not lats: |
| 87 | + logger.warning("clip %s has no GPS samples; skipping", clip_id) |
| 88 | + continue |
| 89 | + |
| 90 | + ego_lat = float(lats[-1]) |
| 91 | + ego_lon = float(lons[-1]) |
| 92 | + ego_heading = _heading_from_trace(lats, lons, ego_lat) |
| 93 | + |
| 94 | + graph = _load_or_fetch_network( |
| 95 | + ego_lat, ego_lon, radius_m, net_cache |
| 96 | + ) |
| 97 | + if graph is None: |
| 98 | + logger.warning("clip %s: failed to obtain road network; skipping", clip_id) |
| 99 | + continue |
| 100 | + |
| 101 | + _, route = map_match_waypoints(graph, list(lats), list(lons)) |
| 102 | + raw_points = list(zip(lats, lons)) |
| 103 | + try: |
| 104 | + image = render_map_tile( |
| 105 | + graph, |
| 106 | + route_nodes=route, |
| 107 | + ego_lat=ego_lat, |
| 108 | + ego_lon=ego_lon, |
| 109 | + ego_heading=ego_heading, |
| 110 | + raw_gps_points=raw_points, |
| 111 | + radius_m=radius_m, |
| 112 | + image_size=image_size, |
| 113 | + ) |
| 114 | + except Exception as exc: # noqa: BLE001 — matplotlib/osmnx errors vary |
| 115 | + logger.warning( |
| 116 | + "clip %s: render failed (%s); skipping", |
| 117 | + clip_id, |
| 118 | + exc, |
| 119 | + exc_info=True, |
| 120 | + ) |
| 121 | + continue |
| 122 | + |
| 123 | + image.save(tile_path) |
| 124 | + rendered.append(tile_path) |
| 125 | + |
| 126 | + return rendered |
| 127 | + |
| 128 | + |
| 129 | +def _heading_from_trace( |
| 130 | + lats: Sequence[float], lons: Sequence[float], ref_lat: float |
| 131 | +) -> float: |
| 132 | + """Estimate ego heading (radians) from the last segment of the GPS trace. |
| 133 | +
|
| 134 | + Uses atan2(east, north) so 0 rad ≡ north and the value matches the |
| 135 | + `ego_heading` convention in `render_map_tile`. Falls back to 0 when the |
| 136 | + trace has fewer than two distinct samples. |
| 137 | + """ |
| 138 | + if len(lats) < 2: |
| 139 | + return 0.0 |
| 140 | + cos_lat = math.cos(math.radians(ref_lat)) |
| 141 | + deg_to_m = EARTH_RADIUS_M * math.pi / 180.0 |
| 142 | + dx = (lons[-1] - lons[-2]) * cos_lat * deg_to_m |
| 143 | + dy = (lats[-1] - lats[-2]) * deg_to_m |
| 144 | + if dx == 0.0 and dy == 0.0: |
| 145 | + return 0.0 |
| 146 | + return math.atan2(dx, dy) |
| 147 | + |
| 148 | + |
| 149 | +def _load_or_fetch_network( |
| 150 | + center_lat: float, |
| 151 | + center_lon: float, |
| 152 | + radius_m: int, |
| 153 | + cache_dir: Path | None, |
| 154 | +) -> nx.MultiDiGraph | None: |
| 155 | + """Return a cached graph if available, otherwise fetch and cache it. |
| 156 | +
|
| 157 | + Centroids are quantized to ~100 m so nearby clips reuse the same download. |
| 158 | + """ |
| 159 | + if cache_dir is not None: |
| 160 | + key = f"{round(center_lat, 3)}_{round(center_lon, 3)}_{radius_m}.pkl" |
| 161 | + cache_path = cache_dir / key |
| 162 | + cached = load_cached_network(cache_path) |
| 163 | + if cached is not None: |
| 164 | + return cached |
| 165 | + else: |
| 166 | + cache_path = None |
| 167 | + |
| 168 | + try: |
| 169 | + graph = fetch_road_network(center_lat, center_lon, radius_m=radius_m) |
| 170 | + except Exception as exc: # noqa: BLE001 — network/Overpass failures |
| 171 | + logger.warning( |
| 172 | + "fetch_road_network(%.4f, %.4f) failed: %s", |
| 173 | + center_lat, |
| 174 | + center_lon, |
| 175 | + exc, |
| 176 | + ) |
| 177 | + return None |
| 178 | + |
| 179 | + if cache_path is not None: |
| 180 | + cache_network(graph, cache_path) |
| 181 | + return graph |
0 commit comments