Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / extract_fallback.rs

extract_fallback.rs377 lines · 15.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
55use std::collections::HashMap;
56
57use osm_ingest::proto::Result;
58use osm_ingest::rings::{point_in_ring, ring_area, Polygon};
59use rayon::prelude::*;
60use tile_build::geom::Geometry;
61use tile_build::par;
62use tile_build::progress::Progress;
63use tilecodec::mamaps::body::ID_NONE;
64use 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)]
68pub 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.
123pub 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 =
130 area_deg2.max(0.0) * M_PER_DEG * M_PER_DEG * mid_lat_deg.to_radians().cos().max(0.05);
131 let score = area_m2.log10() + AOI_COVERAGE_WEIGHT * (population as f64 + 1.0).log10();
132 if score >= 26.0 {
133 0
134 } else if score >= 23.5 {
135 1
136 } else if score >= 20.0 {
137 2
138 } else if score >= 14.5 {
139 3
140 } else {
141 4
142 }
143}
144
145/// Which admin-level band a place or a boundary belongs to.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147enum Band {
148 Country,
149 Region,
150 Locality,
151}
152
153/// The admin levels a place kind may link to. `None` means the kind never links by containment
154/// (county levels and sub-locality places — see the module docs).
155fn band_for_place_kind(kind: &str) -> Option<Band> {
156 match kind {
157 "country" => Some(Band::Country),
158 "region" => Some(Band::Region),
159 "locality" => Some(Band::Locality),
160 _ => None,
161 }
162}
163
164/// The band an admin level belongs to. Levels 5–6 deliberately belong to no band.
165fn band_for_level(level: u16) -> Option<Band> {
166 match level {
167 1..=2 => Some(Band::Country),
168 3..=4 => Some(Band::Region),
169 7..=12 => Some(Band::Locality),
170 _ => None,
171 }
172}
173
174/// A boundary candidate: one `region_area` shape with everything the selector needs precomputed.
175struct Boundary {
176 /// Tagged relation id, the link value the tiler stamps.
177 id: u64,
178 /// `admin_level` from the region shape's class (`kind_detail`).
179 level: u16,
180 /// Sum of `|ring_area|` over the shape's exterior rings — the same metric `RegionMesh`
181 /// compares on device (a consistent planar measure, not ground area; only ever compared).
182 area: f64,
183 /// `(min_lon, min_lat, max_lon, max_lat)` over the shape, for the prefilter. `None` when the
184 /// shape holds no vertices at all.
185 bbox: Option<(f64, f64, f64, f64)>,
186 /// Assembled polygons, exterior first then holes, lon/lat.
187 polygons: Vec<Polygon>,
188}
189
190impl Boundary {
191 fn new(id: u64, level: u16, polygons: Vec<Polygon>) -> Boundary {
192 let area: f64 =
193 polygons.iter().filter_map(|poly| poly.first()).map(|ext| ring_area(ext).abs()).sum();
194 let mut bbox: Option<(f64, f64, f64, f64)> = None;
195 for ring in polygons.iter().flatten() {
196 for &(lon, lat) in ring {
197 bbox = Some(match bbox {
198 None => (lon, lat, lon, lat),
199 Some((x0, y0, x1, y1)) => (x0.min(lon), y0.min(lat), x1.max(lon), y1.max(lat)),
200 });
201 }
202 }
203 Boundary { id, level, area, bbox, polygons }
204 }
205}
206
207/// A place kind name from its interned `Class.kind` (1-based into [`KINDS`]).
208fn place_kind_name(kind: u16) -> Option<&'static str> {
209 if kind == 0 {
210 return None;
211 }
212 KINDS.get(kind as usize - 1).copied()
213}
214
215/// Grid cells are 4 degrees square: 90 over lon, 45 over lat.
216const GRID_NX: usize = 90;
217const GRID_NY: usize = 45;
218/// A boundary covering more cells than this goes on the overflow list, tested for every place.
219/// 4-degree cells make even Russia (~250 cells) indexable; this only catches degenerate bboxes.
220const MAX_CELLS_PER_BOUNDARY: usize = 1024;
221
222/// Boundaries partitioned spatially so one place tests a cellful, not the planet.
223struct Grid {
224 cells: Vec<Vec<usize>>,
225 overflow: Vec<usize>,
226}
227
228fn cell_of(lon: f64, lat: f64) -> usize {
229 let ix = (((lon + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1) as usize;
230 let iy = (((lat + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1) as usize;
231 iy * GRID_NX + ix
232}
233
234impl Grid {
235 fn build(boundaries: &[Boundary]) -> Grid {
236 let mut grid = Grid { cells: vec![Vec::new(); GRID_NX * GRID_NY], overflow: Vec::new() };
237 for (i, b) in boundaries.iter().enumerate() {
238 let Some((x0, y0, x1, y1)) = b.bbox else {
239 continue;
240 };
241 let (cx0, cy0) = (
242 (((x0 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1),
243 (((y0 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1),
244 );
245 let (cx1, cy1) = (
246 (((x1 + 180.0) / 4.0).floor() as i32).clamp(0, GRID_NX as i32 - 1),
247 (((y1 + 90.0) / 4.0).floor() as i32).clamp(0, GRID_NY as i32 - 1),
248 );
249 let count = (cx1 - cx0 + 1) as usize * (cy1 - cy0 + 1) as usize;
250 if count > MAX_CELLS_PER_BOUNDARY {
251 grid.overflow.push(i);
252 continue;
253 }
254 for cy in cy0..=cy1 {
255 for cx in cx0..=cx1 {
256 grid.cells[cy as usize * GRID_NX + cx as usize].push(i);
257 }
258 }
259 }
260 grid
261 }
262
263 /// Boundary indices that may contain `point`: its cell plus the overflow list.
264 fn candidates_for(&self, point: (f64, f64)) -> impl Iterator<Item = usize> + '_ {
265 self.cells[cell_of(point.0, point.1)].iter().copied().chain(self.overflow.iter().copied())
266 }
267}
268
269/// Is `point` inside `polygons`? Inside some exterior and in none of its holes.
270fn point_in_boundary(point: (f64, f64), polygons: &[Polygon]) -> bool {
271 polygons.iter().any(|poly| {
272 let Some((exterior, holes)) = poly.split_first() else {
273 return false;
274 };
275 point_in_ring(point, exterior) && !holes.iter().any(|hole| point_in_ring(point, hole))
276 })
277}
278
279/// Point-to-segment distance at or below one e7 grid step (~1 cm) counts as on the edge.
280///
281/// e7-quantised coordinates snap to a 1e-7 grid, so anything closer than that is
282/// indistinguishable from exactly on the line — and ray-casting there is a coin flip.
283fn point_on_segment(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool {
284 const EPS: f64 = 1e-7;
285 let (px, py) = point;
286 let dx = b.0 - a.0;
287 let dy = b.1 - a.1;
288 let len2 = dx * dx + dy * dy;
289 if len2 == 0.0 {
290 return (px - a.0).abs() <= EPS && (py - a.1).abs() <= EPS;
291 }
292 // Perpendicular distance, scale-aware: |cross| / |segment|. Compared
293 // without the square root (|cross|^2 <= EPS^2 * len2, all sides
294 // non-negative) — same predicate, no sqrt per segment on the hottest
295 // inner loop of the link pass.
296 let cross = dx * (py - a.1) - dy * (px - a.0);
297 if cross * cross > EPS * EPS * len2 {
298 return false;
299 }
300 px >= a.0.min(b.0) - EPS
301 && px <= a.0.max(b.0) + EPS
302 && py >= a.1.min(b.1) - EPS
303 && py <= a.1.max(b.1) + EPS
304}
305
306/// Is `point` on any ring edge of `polygons`? Rings are explicitly closed, but the wrap edge is
307/// checked too so an unclosed ring cannot hide one.
308fn point_on_boundary_edge(point: (f64, f64), polygons: &[Polygon]) -> bool {
309 polygons.iter().flat_map(|poly| poly.iter()).any(|ring| {
310 if ring.len() < 2 {
311 return false;
312 }
313 (0..ring.len()).any(|i| point_on_segment(point, ring[i], ring[(i + 1) % ring.len()]))
314 })
315}
316
317/// Pick the link for one place: smallest in-band container wins, ties and edges link nothing.
318fn select_link(point: (f64, f64), band: Band, candidates: &[&Boundary]) -> Option<u64> {
319 // In-band, bbox-passing candidates only — the bbox is what keeps this off the PIP path.
320 let mut passing: Vec<&Boundary> = Vec::new();
321 for b in candidates {
322 if band_for_level(b.level) != Some(band) {
323 continue;
324 }
325 let Some((x0, y0, x1, y1)) = b.bbox else {
326 continue;
327 };
328 if point.0 < x0 || point.0 > x1 || point.1 < y0 || point.1 > y1 {
329 continue;
330 }
331 passing.push(*b);
332 }
333 // On any in-band edge the ray cast cannot be trusted — mask nothing.
334 if passing.iter().any(|b| point_on_boundary_edge(point, &b.polygons)) {
335 return None;
336 }
337 let mut best: Option<&Boundary> = None;
338 let mut second = f64::INFINITY;
339 for b in passing {
340 if b.area <= 0.0 || !point_in_boundary(point, &b.polygons) {
341 continue;
342 }
343 match best {
344 None => best = Some(b),
345 Some(cur) if b.area < cur.area => {
346 second = cur.area;
347 best = Some(b);
348 }
349 Some(_) => {
350 second = second.min(b.area);
351 }
352 }
353 }
354 let best = best?;
355 // Two containers within ~1% of each other is a coin flip (overlapping claims, duplicate
356 // relations) — mask nothing rather than the wrong one.
357 if second.is_finite() && (second - best.area) / best.area < 0.01 {
358 return None;
359 }
360 Some(best.id)
361}
362
363/// Extend `region_links` with containment fallback links for member-less place labels.
364///
365/// Reads the finished store twice (boundaries, then places), inserts only keys still missing so
366/// member links always win, and returns the counts the build log reports. The tiler reads the
367/// extended map unchanged.
368#[cfg(test)]
369pub fn extend_region_links(
370 store: &crate::store::Store,
371 region_links: &mut HashMap<u64, u64>,
372) -> Result<FallbackStats> {
373 extend_region_links_with(store, region_links, &mut HashMap::new(), &HashMap::new())
374}
375
376include!("extract_fallback_s1.rs");
377include!("extract_fallback_part1.rs");