Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_fallback.rs
extract_fallback.rs576 lines · 24.5 KiBRaw
| 1 | //! Build-time containment fallback for place-label -> boundary links. |
| 2 | //! |
| 3 | //! Tapping a place label should outline its exact admin boundary. The authoritative half of that |
| 4 | //! link is membership: a boundary relation points at its own label node via an `admin_centre` or |
| 5 | //! `label` member, and stage A records that node -> relation pair into `region_links` |
| 6 | //! (`extract_part1.rs`). This module is the second half: for every place label that membership did |
| 7 | //! not link, pick the boundary that contains its centroid. |
| 8 | //! |
| 9 | //! # Matching order: members first, containment second |
| 10 | //! |
| 11 | //! The member map is never overwritten here. Fallback only inserts entries for place tagged-IDs |
| 12 | //! still missing from `region_links`, keyed the same way the tiler looks them up (the place's own |
| 13 | //! tagged node/way/relation id), so the two halves agree and `tiler_part5.rs` needs no change. |
| 14 | //! |
| 15 | //! # Where this runs |
| 16 | //! |
| 17 | //! Called from `main_part1.rs` between `extract()` returning and `tiler::Settings` construction, |
| 18 | //! with the finished [`Store`](crate::store::Store) and the member-built map. The store holds |
| 19 | //! whole lon/lat polygons (pre-tiler, pre-clip), which is the only place a containment test is |
| 20 | //! meaningful — at tiler encode time the geometry is tile-local clipped fragments. Two sequential |
| 21 | //! reads of the spill: one to collect boundary shapes, one to stream places and link them. No new |
| 22 | //! spills, no resident feature table. |
| 23 | //! |
| 24 | //! # Level bands |
| 25 | //! |
| 26 | //! A place kind only matches the admin levels it can actually name: |
| 27 | //! |
| 28 | //! | place kind | admin levels | |
| 29 | //! |---|---| |
| 30 | //! | `country` | 1–2 | |
| 31 | //! | `region` | 3–4 | |
| 32 | //! | `locality` | 7–12 | |
| 33 | //! |
| 34 | //! Levels 5–6 (county) intentionally match nothing. Those boundaries only link via relation |
| 35 | //! members; anything else masks nothing rather than the wrong county. `neighbourhood` and |
| 36 | //! `macrohood` places likewise match nothing — a suburb centroid inside a city boundary must not |
| 37 | //! outline the city. |
| 38 | //! |
| 39 | //! # `REGION_NONE` rules: when in doubt, mask nothing |
| 40 | //! |
| 41 | //! A missing link leaves the tiler's `REGION_NONE` path (mask nothing), so every uncertain case |
| 42 | //! emits nothing: zero in-band candidates, an ambiguous pick (two containers' areas within ~1% of |
| 43 | //! each other), or the place sitting on a ring edge (where ray-casting is a coin flip). Ambiguity |
| 44 | //! favors no-mask over wrong-mask. |
| 45 | //! |
| 46 | //! # Cost cap |
| 47 | //! |
| 48 | //! Boundaries are partitioned by band (a place only ever tests its own band) behind a coarse |
| 49 | //! 4-degree grid, with a bbox reject before any point-in-polygon test, in a single pass per read. |
| 50 | //! Per-place work is then a handful of candidates, not the whole boundary set. If profiling ever |
| 51 | //! shows this dominating, the documented escape hatch is a rank-based skip (only attempt fallback |
| 52 | //! for places above a population-rank floor) — not yet implemented, and the per-kind counts in |
| 53 | //! [`FallbackStats`] are the numbers that would size it. |
| 54 | |
| 55 | use std::collections::HashMap; |
| 56 | |
| 57 | use osm_ingest::proto::Result; |
| 58 | use osm_ingest::rings::{point_in_ring, ring_area, Polygon}; |
| 59 | use rayon::prelude::*; |
| 60 | use tile_build::geom::Geometry; |
| 61 | use tile_build::par; |
| 62 | use tile_build::progress::Progress; |
| 63 | use tilecodec::mamaps::body::ID_NONE; |
| 64 | use tilecodec::mamaps::dict::{KINDS, LAYER_BOUNDARIES, LAYER_PLACES}; |
| 65 | |
| 66 | /// What a run of the fallback did, for the build report. |
| 67 | #[derive(Debug, Default, Clone)] |
| 68 | pub struct FallbackStats { |
| 69 | /// Linkable `places` features seen (tagged id, non-empty point, known kind). |
| 70 | pub places_total: u64, |
| 71 | /// Of those, already linked by relation members before fallback ran. |
| 72 | pub member_linked: u64, |
| 73 | /// Of those, newly linked by containment here. |
| 74 | pub fallback_linked: u64, |
| 75 | /// Of those, still unlinked after both halves (`total - member - fallback`). |
| 76 | pub fallback_missed: u64, |
| 77 | /// `(kind, total, linked)` per place kind, sorted by kind. `linked` counts both halves; |
| 78 | /// the ratio is the per-kind hit rate the build log prints. |
| 79 | pub per_kind: Vec<(String, u64, u64)>, |
| 80 | /// Country zoom overrides assigned (place tagged id count). |
| 81 | pub country_zooms: u64, |
| 82 | } |
| 83 | |
| 84 | /// A country's label zoom from its ground footprint and headcount. |
| 85 | /// |
| 86 | /// Pure area buries Vatican City, Singapore and Monaco until deep zoom; pure |
| 87 | /// population buries Russia, Canada and Mongolia under their own emptiness. The |
| 88 | /// score multiplies the two so a place must be big *or* populous to surface |
| 89 | /// early, and tiny *and* empty to wait: |
| 90 | /// |
| 91 | /// `score = log10(area_m2) + AOI_COVERAGE_WEIGHT * log10(population + 1)` |
| 92 | /// |
| 93 | /// The weight (2.0) is what keeps Singapore (6 M people, 725 km²) and Switzerland |
| 94 | /// off the backstop: with equal weights a microstate's area term (~1e8 → 8) |
| 95 | /// caps its score near 15 no matter the headcount, so population could never |
| 96 | /// lift one. Weighting population double counts headcount the way a reader |
| 97 | /// does — people are the point of a label — while area still separates Russia |
| 98 | /// (20.5) from Nauru (10.7). The `+1` keeps unpopulated Antarctica finite. |
| 99 | /// |
| 100 | /// Bucket edges calibrated against real countries (see |
| 101 | /// `country_zoom_scores_area_times_headcount` — every edge asserted): |
| 102 | /// |
| 103 | /// | score | start zoom | example | |
| 104 | /// |---|---|---| |
| 105 | /// | ≥ 26 | 0 | Russia, USA, France, Germany, Japan, Egypt | |
| 106 | /// | ≥ 23.5 | 1 | Switzerland | |
| 107 | /// | ≥ 20 | 2 | Singapore | |
| 108 | /// | ≥ 14.5 | 3 | Liechtenstein, Nauru, Tuvalu — everything on by z3 | |
| 109 | /// | < 14.5 | 4 | Vatican City (tiny and near-empty) | |
| 110 | /// |
| 111 | /// z3 shows every country whose label cannot collide with another country's: |
| 112 | /// at z3 a tile spans 45° and a country label spans a fraction of a tile, so |
| 113 | /// neighbours are tiles apart. z4 is the backstop for the tail, never later — |
| 114 | /// a country is never street-level detail. |
| 115 | /// |
| 116 | /// Why z0 holds France as well as Russia: at z0 the world is four tiles and a |
| 117 | /// label is a few dozen pixels — France and Russia never share a tile, so they |
| 118 | /// cannot collide. Gating France out would empty the tile, not declutter it. |
| 119 | /// |
| 120 | /// Ground area from planar deg² via equirectangular projection at the shape's |
| 121 | /// own mid-latitude: exact enough for bucketing (adjacent buckets differ ~4x), |
| 122 | /// cheap enough to run over every country once per build. |
| 123 | pub fn country_zoom(area_deg2: f64, mid_lat_deg: f64, population: u64) -> u8 { |
| 124 | const M_PER_DEG: f64 = 111_320.0; |
| 125 | /// How much a doubling of headcount moves the score relative to a doubling |
| 126 | /// of ground area. 2.0: people are the point of a label, and without it no |
| 127 | /// microstate could ever leave the backstop on headcount alone. |
| 128 | const AOI_COVERAGE_WEIGHT: f64 = 2.0; |
| 129 | let area_m2 = area_deg2.max(0.0) * M_PER_DEG * M_PER_DEG * mid_lat_deg.to_radians().cos().max(0.05); |
| 130 | let score = area_m2.log10() + AOI_COVERAGE_WEIGHT * (population as f64 + 1.0).log10(); |
| 131 | if score >= 26.0 { |
| 132 | 0 |
| 133 | } else if score >= 23.5 { |
| 134 | 1 |
| 135 | } else if score >= 20.0 { |
| 136 | 2 |
| 137 | } else if score >= 14.5 { |
| 138 | 3 |
| 139 | } else { |
| 140 | 4 |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// Which admin-level band a place or a boundary belongs to. |
| 145 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 146 | enum Band { |
| 147 | Country, |
| 148 | Region, |
| 149 | Locality, |
| 150 | } |
| 151 | |
| 152 | /// The admin levels a place kind may link to. `None` means the kind never links by containment |
| 153 | /// (county levels and sub-locality places — see the module docs). |
| 154 | fn band_for_place_kind(kind: &str) -> Option<Band> { |
| 155 | match kind { |
| 156 | "country" => Some(Band::Country), |
| 157 | "region" => Some(Band::Region), |
| 158 | "locality" => Some(Band::Locality), |
| 159 | _ => None, |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// The band an admin level belongs to. Levels 5–6 deliberately belong to no band. |
| 164 | fn band_for_level(level: u16) -> Option<Band> { |
| 165 | match level { |
| 166 | 1..=2 => Some(Band::Country), |
| 167 | 3..=4 => Some(Band::Region), |
| 168 | 7..=12 => Some(Band::Locality), |
| 169 | _ => None, |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// A boundary candidate: one `region_area` shape with everything the selector needs precomputed. |
| 174 | struct Boundary { |
| 175 | /// Tagged relation id, the link value the tiler stamps. |
| 176 | id: u64, |
| 177 | /// `admin_level` from the region shape's class (`kind_detail`). |
| 178 | level: u16, |
| 179 | /// Sum of `|ring_area|` over the shape's exterior rings — the same metric `RegionMesh` |
| 180 | /// compares on device (a consistent planar measure, not ground area; only ever compared). |
| 181 | area: f64, |
| 182 | /// `(min_lon, min_lat, max_lon, max_lat)` over the shape, for the prefilter. `None` when the |
| 183 | /// shape holds no vertices at all. |
| 184 | bbox: Option<(f64, f64, f64, f64)>, |
| 185 | /// Assembled polygons, exterior first then holes, lon/lat. |
| 186 | polygons: Vec<Polygon>, |
| 187 | } |
| 188 | |
| 189 | impl Boundary { |
| 190 | fn new(id: u64, level: u16, polygons: Vec<Polygon>) -> Boundary { |
| 191 | let area: f64 = |
| 192 | polygons.iter().filter_map(|poly| poly.first()).map(|ext| ring_area(ext).abs()).sum(); |
| 193 | let mut bbox: Option<(f64, f64, f64, f64)> = None; |
| 194 | for ring in polygons.iter().flatten() { |
| 195 | for &(lon, lat) in ring { |
| 196 | bbox = Some(match bbox { |
| 197 | None => (lon, lat, lon, lat), |
| 198 | Some((x0, y0, x1, y1)) => { |
| 199 | (x0.min(lon), y0.min(lat), x1.max(lon), y1.max(lat)) |
| 200 | } |
| 201 | }); |
| 202 | } |
| 203 | } |
| 204 | Boundary { id, level, area, bbox, polygons } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /// A place kind name from its interned `Class.kind` (1-based into [`KINDS`]). |
| 209 | fn place_kind_name(kind: u16) -> Option<&'static str> { |
| 210 | if kind == 0 { |
| 211 | return None; |
| 212 | } |
| 213 | KINDS.get(kind as usize - 1).copied() |
| 214 | } |
| 215 | |
| 216 | /// Grid cells are 4 degrees square: 90 over lon, 45 over lat. |
| 217 | const GRID_NX: usize = 90; |
| 218 | const GRID_NY: usize = 45; |
| 219 | /// A boundary covering more cells than this goes on the overflow list, tested for every place. |
| 220 | /// 4-degree cells make even Russia (~250 cells) indexable; this only catches degenerate bboxes. |
| 221 | const MAX_CELLS_PER_BOUNDARY: usize = 1024; |
| 222 | |
| 223 | /// Boundaries partitioned spatially so one place tests a cellful, not the planet. |
| 224 | struct Grid { |
| 225 | cells: Vec<Vec<usize>>, |
| 226 | overflow: Vec<usize>, |
| 227 | } |
| 228 | |
| 229 | fn cell_of(lon: f64, lat: f64) -> usize { |
| 230 | let ix = (((lon + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1) as usize; |
| 231 | let iy = (((lat + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1) as usize; |
| 232 | iy * GRID_NX + ix |
| 233 | } |
| 234 | |
| 235 | impl Grid { |
| 236 | fn build(boundaries: &[Boundary]) -> Grid { |
| 237 | let mut grid = Grid { cells: vec![Vec::new(); GRID_NX * GRID_NY], overflow: Vec::new() }; |
| 238 | for (i, b) in boundaries.iter().enumerate() { |
| 239 | let Some((x0, y0, x1, y1)) = b.bbox else { |
| 240 | continue; |
| 241 | }; |
| 242 | let (cx0, cy0) = ( |
| 243 | (((x0 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1), |
| 244 | (((y0 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1), |
| 245 | ); |
| 246 | let (cx1, cy1) = ( |
| 247 | (((x1 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1), |
| 248 | (((y1 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1), |
| 249 | ); |
| 250 | let count = (cx1 - cx0 + 1) as usize * (cy1 - cy0 + 1) as usize; |
| 251 | if count > MAX_CELLS_PER_BOUNDARY { |
| 252 | grid.overflow.push(i); |
| 253 | continue; |
| 254 | } |
| 255 | for cy in cy0..=cy1 { |
| 256 | for cx in cx0..=cx1 { |
| 257 | grid.cells[cy as usize * GRID_NX + cx as usize].push(i); |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | grid |
| 262 | } |
| 263 | |
| 264 | /// Boundary indices that may contain `point`: its cell plus the overflow list. |
| 265 | fn candidates_for(&self, point: (f64, f64)) -> impl Iterator<Item = usize> + '_ { |
| 266 | self.cells[cell_of(point.0, point.1)] |
| 267 | .iter() |
| 268 | .copied() |
| 269 | .chain(self.overflow.iter().copied()) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Is `point` inside `polygons`? Inside some exterior and in none of its holes. |
| 274 | fn point_in_boundary(point: (f64, f64), polygons: &[Polygon]) -> bool { |
| 275 | polygons.iter().any(|poly| { |
| 276 | let Some((exterior, holes)) = poly.split_first() else { |
| 277 | return false; |
| 278 | }; |
| 279 | point_in_ring(point, exterior) && !holes.iter().any(|hole| point_in_ring(point, hole)) |
| 280 | }) |
| 281 | } |
| 282 | |
| 283 | /// Point-to-segment distance at or below one e7 grid step (~1 cm) counts as on the edge. |
| 284 | /// |
| 285 | /// e7-quantised coordinates snap to a 1e-7 grid, so anything closer than that is |
| 286 | /// indistinguishable from exactly on the line — and ray-casting there is a coin flip. |
| 287 | fn point_on_segment(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool { |
| 288 | const EPS: f64 = 1e-7; |
| 289 | let (px, py) = point; |
| 290 | let dx = b.0 - a.0; |
| 291 | let dy = b.1 - a.1; |
| 292 | let len2 = dx * dx + dy * dy; |
| 293 | if len2 == 0.0 { |
| 294 | return (px - a.0).abs() <= EPS && (py - a.1).abs() <= EPS; |
| 295 | } |
| 296 | // Perpendicular distance, scale-aware: |cross| / |segment|. Compared |
| 297 | // without the square root (|cross|^2 <= EPS^2 * len2, all sides |
| 298 | // non-negative) — same predicate, no sqrt per segment on the hottest |
| 299 | // inner loop of the link pass. |
| 300 | let cross = dx * (py - a.1) - dy * (px - a.0); |
| 301 | if cross * cross > EPS * EPS * len2 { |
| 302 | return false; |
| 303 | } |
| 304 | px >= a.0.min(b.0) - EPS |
| 305 | && px <= a.0.max(b.0) + EPS |
| 306 | && py >= a.1.min(b.1) - EPS |
| 307 | && py <= a.1.max(b.1) + EPS |
| 308 | } |
| 309 | |
| 310 | /// Is `point` on any ring edge of `polygons`? Rings are explicitly closed, but the wrap edge is |
| 311 | /// checked too so an unclosed ring cannot hide one. |
| 312 | fn point_on_boundary_edge(point: (f64, f64), polygons: &[Polygon]) -> bool { |
| 313 | polygons.iter().flat_map(|poly| poly.iter()).any(|ring| { |
| 314 | if ring.len() < 2 { |
| 315 | return false; |
| 316 | } |
| 317 | (0..ring.len()).any(|i| point_on_segment(point, ring[i], ring[(i + 1) % ring.len()])) |
| 318 | }) |
| 319 | } |
| 320 | |
| 321 | /// Pick the link for one place: smallest in-band container wins, ties and edges link nothing. |
| 322 | fn select_link(point: (f64, f64), band: Band, candidates: &[&Boundary]) -> Option<u64> { |
| 323 | // In-band, bbox-passing candidates only — the bbox is what keeps this off the PIP path. |
| 324 | let mut passing: Vec<&Boundary> = Vec::new(); |
| 325 | for b in candidates { |
| 326 | if band_for_level(b.level) != Some(band) { |
| 327 | continue; |
| 328 | } |
| 329 | let Some((x0, y0, x1, y1)) = b.bbox else { |
| 330 | continue; |
| 331 | }; |
| 332 | if point.0 < x0 || point.0 > x1 || point.1 < y0 || point.1 > y1 { |
| 333 | continue; |
| 334 | } |
| 335 | passing.push(*b); |
| 336 | } |
| 337 | // On any in-band edge the ray cast cannot be trusted — mask nothing. |
| 338 | if passing.iter().any(|b| point_on_boundary_edge(point, &b.polygons)) { |
| 339 | return None; |
| 340 | } |
| 341 | let mut best: Option<&Boundary> = None; |
| 342 | let mut second = f64::INFINITY; |
| 343 | for b in passing { |
| 344 | if b.area <= 0.0 || !point_in_boundary(point, &b.polygons) { |
| 345 | continue; |
| 346 | } |
| 347 | match best { |
| 348 | None => best = Some(b), |
| 349 | Some(cur) if b.area < cur.area => { |
| 350 | second = cur.area; |
| 351 | best = Some(b); |
| 352 | } |
| 353 | Some(_) => { |
| 354 | second = second.min(b.area); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | let best = best?; |
| 359 | // Two containers within ~1% of each other is a coin flip (overlapping claims, duplicate |
| 360 | // relations) — mask nothing rather than the wrong one. |
| 361 | if second.is_finite() && (second - best.area) / best.area < 0.01 { |
| 362 | return None; |
| 363 | } |
| 364 | Some(best.id) |
| 365 | } |
| 366 | |
| 367 | /// Extend `region_links` with containment fallback links for member-less place labels. |
| 368 | /// |
| 369 | /// Reads the finished store twice (boundaries, then places), inserts only keys still missing so |
| 370 | /// member links always win, and returns the counts the build log reports. The tiler reads the |
| 371 | /// extended map unchanged. |
| 372 | pub fn extend_region_links( |
| 373 | store: &crate::store::Store, |
| 374 | region_links: &mut HashMap<u64, u64>, |
| 375 | ) -> Result<FallbackStats> { |
| 376 | extend_region_links_with(store, region_links, &mut HashMap::new(), &HashMap::new()) |
| 377 | } |
| 378 | |
| 379 | /// [`extend_region_links`], also filling `country_zooms`: place tagged id → label start |
| 380 | /// zoom for `country` places, from each country's ground footprint and headcount (see |
| 381 | /// [`country_zoom`]). `populations` maps place tagged id → `population` tag headcount |
| 382 | /// (relation places; node/way countries are absent and score as unpopulated — the area |
| 383 | /// term still separates Russia from Nauru). The caller hands both maps to the tiler |
| 384 | /// beside `region_links`. |
| 385 | pub fn extend_region_links_with( |
| 386 | store: &crate::store::Store, |
| 387 | region_links: &mut HashMap<u64, u64>, |
| 388 | country_zooms: &mut HashMap<u64, u8>, |
| 389 | populations: &HashMap<u64, u64>, |
| 390 | ) -> Result<FallbackStats> { |
| 391 | // Pass 1: boundary shapes AND places, in one scan. Only `region_area` |
| 392 | // areas (the mask's own shapes, carrying the admin level in `kind_detail`); |
| 393 | // border lines enclose nothing. Places are positional, so node, |
| 394 | // way-centroided and relation-centroided labels all link by the tagged id |
| 395 | // they already carry. |
| 396 | // |
| 397 | // One scan, not two: the store reader is one sequential cursor over tens |
| 398 | // of GB of spill, and both passes filtered it by layer. Collecting both |
| 399 | // vectors in a single streaming pass deletes a full decode. Peak is |
| 400 | // unchanged — boundaries already lived through place collection. |
| 401 | struct PlacePoint { |
| 402 | id: u64, |
| 403 | point: (f64, f64), |
| 404 | kind: Band, |
| 405 | kind_name: String, |
| 406 | } |
| 407 | let mut boundaries: Vec<Boundary> = Vec::new(); |
| 408 | let mut places: Vec<PlacePoint> = Vec::new(); |
| 409 | { |
| 410 | let mut reader = store.reader()?; |
| 411 | while let Some(feature) = reader.next()? { |
| 412 | if feature.id == ID_NONE { |
| 413 | continue; |
| 414 | } |
| 415 | if feature.class.layer == LAYER_BOUNDARIES && feature.class.area { |
| 416 | let Geometry::Polygons(polygons) = feature.geometry else { |
| 417 | continue; |
| 418 | }; |
| 419 | if polygons.is_empty() { |
| 420 | continue; |
| 421 | } |
| 422 | boundaries.push(Boundary::new(feature.id, feature.class.kind_detail, polygons)); |
| 423 | } else if feature.class.layer == LAYER_PLACES { |
| 424 | let Geometry::Points(points) = feature.geometry else { |
| 425 | continue; |
| 426 | }; |
| 427 | let Some(&point) = points.first() else { |
| 428 | continue; |
| 429 | }; |
| 430 | let Some(kind_name) = place_kind_name(feature.class.kind) else { |
| 431 | continue; |
| 432 | }; |
| 433 | let Some(band) = band_for_place_kind(kind_name) else { |
| 434 | continue; |
| 435 | }; |
| 436 | places.push(PlacePoint { |
| 437 | id: feature.id, |
| 438 | point, |
| 439 | kind: band, |
| 440 | kind_name: kind_name.to_string(), |
| 441 | }); |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0); |
| 446 | let grid = Grid::build(&boundaries); |
| 447 | // The `country_zoom` lookup below used to walk `boundaries` linearly per |
| 448 | // linked country; indexed by id so it is a hash lookup instead. Built |
| 449 | // once — the vec never moves again after this. |
| 450 | let boundary_by_id: HashMap<u64, usize> = |
| 451 | boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect(); |
| 452 | |
| 453 | // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all |
| 454 | // link by the tagged id they already carry — the only path that can link non-node places, |
| 455 | // since the member map is node-keyed. Country labels also gain their area+population |
| 456 | // start zoom here (see `country_zoom`): the linked boundary's footprint is in hand, |
| 457 | // so no third pass is needed. The headcount comes from `populations` (relation |
| 458 | // places, filled by the caller while tags were in hand); absent entries score as |
| 459 | // unpopulated — Antarctica's case — never as missing. |
| 460 | // |
| 461 | // Collected serially first — the store reader is one sequential cursor — |
| 462 | // then linked on the pool: `select_link` is pure per-place work over the |
| 463 | // shared grid, and the drain inserts in collection order with member |
| 464 | // links winning, exactly as the serial loop did. `select_link` returns |
| 465 | // at most one target per place, so the drain cannot double-insert and |
| 466 | // the map bytes are identical. |
| 467 | // |
| 468 | // NOTE: `places` now arrives from the fused pass-1 scan above (same |
| 469 | // reader, same filter, same spill order), not from a second scan. What |
| 470 | // follows is unchanged: drain order — and therefore every inserted key, |
| 471 | // value, stat and country zoom — is identical. |
| 472 | let mut stats = FallbackStats::default(); |
| 473 | let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new(); |
| 474 | // Member links always win: counted exactly as the serial loop did, |
| 475 | // and skipped in the link pass so nothing contends on the map. |
| 476 | for place in &places { |
| 477 | stats.places_total += 1; |
| 478 | let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0)); |
| 479 | entry.0 += 1; |
| 480 | if region_links.contains_key(&place.id) { |
| 481 | stats.member_linked += 1; |
| 482 | entry.1 += 1; |
| 483 | } |
| 484 | } |
| 485 | // Parallel link: one candidate-set build + `select_link` per |
| 486 | // member-less place, on the pool; the drain inserts in collection |
| 487 | // order, so the map — and the stats — are identical at every thread |
| 488 | // count. `select_link` returns at most one target per place, so the |
| 489 | // drain cannot double-insert. The bar ticks in the drain per place, so |
| 490 | // it spans the whole pass even though the expensive half runs on the |
| 491 | // pool. |
| 492 | let mut bar = |
| 493 | Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true); |
| 494 | const FALLBACK_BATCH: usize = 16 * 1024; |
| 495 | let mut batch: Vec<usize> = Vec::with_capacity(FALLBACK_BATCH); |
| 496 | let mut built: Vec<Option<u64>> = Vec::with_capacity(FALLBACK_BATCH); |
| 497 | let mut at = 0usize; |
| 498 | while at < places.len() { |
| 499 | batch.clear(); |
| 500 | while at < places.len() && batch.len() < FALLBACK_BATCH { |
| 501 | if region_links.contains_key(&places[at].id) { |
| 502 | // Member-linked: counted above, nothing to compute. The tick |
| 503 | // keeps the bar spanning every place, not just computed ones. |
| 504 | bar.tick("place(s)"); |
| 505 | at += 1; |
| 506 | continue; |
| 507 | } |
| 508 | batch.push(at); |
| 509 | at += 1; |
| 510 | } |
| 511 | if batch.is_empty() { |
| 512 | continue; |
| 513 | } |
| 514 | built.clear(); |
| 515 | par::install(|| { |
| 516 | batch |
| 517 | .par_iter() |
| 518 | .map(|&pi| { |
| 519 | let place = &places[pi]; |
| 520 | let candidates: Vec<&Boundary> = grid |
| 521 | .candidates_for(place.point) |
| 522 | .map(|i| &boundaries[i]) |
| 523 | .collect(); |
| 524 | select_link(place.point, place.kind, &candidates) |
| 525 | }) |
| 526 | .collect_into_vec(&mut built) |
| 527 | }); |
| 528 | for (&pi, target) in batch.iter().zip(built.drain(..)) { |
| 529 | let place = &places[pi]; |
| 530 | if let Some(target) = target { |
| 531 | region_links.insert(place.id, target); |
| 532 | stats.fallback_linked += 1; |
| 533 | if let Some(entry) = per_kind.get_mut(&place.kind_name) { |
| 534 | entry.1 += 1; |
| 535 | } |
| 536 | } |
| 537 | // A country label starts at the zoom its footprint earns. The |
| 538 | // linked boundary (member half inserted before this pass, |
| 539 | // fallback half just above — both visible in `region_links` |
| 540 | // now) carries the ground area; the headcount comes from |
| 541 | // `populations` (relation places, filled by the caller while |
| 542 | // tags were in hand); absent entries score as unpopulated — |
| 543 | // Antarctica's case — never as missing. Unlinked countries keep |
| 544 | // the schema floor (z0): a missing link must never hide a |
| 545 | // country. |
| 546 | if place.kind_name == "country" { |
| 547 | if let Some(target) = region_links.get(&place.id) { |
| 548 | if let Some(&bi) = boundary_by_id.get(target) { |
| 549 | let boundary = &boundaries[bi]; |
| 550 | let mid_lat = |
| 551 | boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0); |
| 552 | let population = populations.get(&place.id).copied().unwrap_or(0); |
| 553 | country_zooms.insert( |
| 554 | place.id, |
| 555 | country_zoom(boundary.area, mid_lat, population), |
| 556 | ); |
| 557 | stats.country_zooms += 1; |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | bar.tick("place(s)"); |
| 562 | } |
| 563 | } |
| 564 | bar.finish("place(s)"); |
| 565 | stats.fallback_missed = |
| 566 | stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked); |
| 567 | let mut kinds: Vec<(String, u64, u64)> = per_kind |
| 568 | .into_iter() |
| 569 | .map(|(kind, (total, linked))| (kind, total, linked)) |
| 570 | .collect(); |
| 571 | kinds.sort_by(|a, b| a.0.cmp(&b.0)); |
| 572 | stats.per_kind = kinds; |
| 573 | Ok(stats) |
| 574 | } |
| 575 | |
| 576 | include!("extract_fallback_part1.rs"); |