Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_build_part3.rs
poi_build_part3.rs392 lines · 14.2 KiBRaw
| 1 | // ---- Region links: boundary assembly and per-POI containment --------------- |
| 2 | // |
| 3 | // Both halves run on the crate pool (`par::install`), and both are |
| 4 | // byte-neutral by construction: |
| 5 | // |
| 6 | // * `assemble_boundaries` maps each boundary independently and collects in the |
| 7 | // same id order the serial loop walked, so `assembled[i]` — and therefore |
| 8 | // every grid cell's candidate list — is unchanged. |
| 9 | // * `stamp_regions` decides each POI from that POI and read-only shared state |
| 10 | // only, so splitting `pois` into chunks cannot change any POI's answer. |
| 11 | // |
| 12 | // The containment test itself is `rings::point_in_ring`'s ray cast, restricted |
| 13 | // to the edges that can straddle the probe's latitude ([`RingIndex`]). The |
| 14 | // crossing parity is an XOR over edges, so visiting a subset in a different |
| 15 | // order gives the same bit as long as the skipped edges could never toggle it — |
| 16 | // which is exactly what the band assignment guarantees. |
| 17 | |
| 18 | /// One assembled boundary: its polygons, each exterior ring's absolute area |
| 19 | /// (smallest-wins needs no sign), its bbox, and its tagged link. |
| 20 | struct BoundaryPoly { |
| 21 | tagged: u64, |
| 22 | admin_level: u8, |
| 23 | polys: Vec<rings::Polygon>, |
| 24 | /// `index[p][r]` accelerates `polys[p][r]`. |
| 25 | index: Vec<Vec<RingIndex>>, |
| 26 | areas: Vec<f64>, |
| 27 | min_lon: f64, |
| 28 | min_lat: f64, |
| 29 | max_lon: f64, |
| 30 | max_lat: f64, |
| 31 | } |
| 32 | |
| 33 | /// Latitude-band edge index over one closed ring, so a containment probe walks |
| 34 | /// only the edges whose latitude span covers the probe instead of all of them. |
| 35 | /// |
| 36 | /// Admin rings run to 10^5 vertices (a coastline-hugging state or country), and |
| 37 | /// the serial ray cast walked every one of them for every POI in the 1° cell — |
| 38 | /// 80% of a California run. |
| 39 | /// |
| 40 | /// Exactness: edge `i` can toggle the ray-cast parity only when |
| 41 | /// `(y1 > y) != (y2 > y)`, i.e. `min(y1, y2) <= y < max(y1, y2)`. `band()` is a |
| 42 | /// monotone non-decreasing function of `y` (an IEEE subtract and a multiply by a |
| 43 | /// positive constant both round monotonically, as do `floor` and the clamp), so |
| 44 | /// for any such `y`, `band(min) <= band(y) <= band(max)` — and the edge is filed |
| 45 | /// under every band in that closed range. No edge that could toggle is ever |
| 46 | /// skipped; the toggle test on the edges visited is the original expression, |
| 47 | /// operand for operand. |
| 48 | struct RingIndex { |
| 49 | min_y: f64, |
| 50 | max_y: f64, |
| 51 | inv: f64, |
| 52 | bands: usize, |
| 53 | /// CSR: edges of band `b` are `edges[offs[b]..offs[b + 1]]`. |
| 54 | offs: Vec<u32>, |
| 55 | edges: Vec<u32>, |
| 56 | } |
| 57 | |
| 58 | /// Edges per band the index aims for. Smaller is faster to probe and bigger to |
| 59 | /// store; four keeps the index well under the ring's own 16 bytes a vertex. |
| 60 | const EDGES_PER_BAND: usize = 4; |
| 61 | /// Upper bound on bands per ring, so a pathological ring cannot blow up memory. |
| 62 | const MAX_BANDS: usize = 1 << 16; |
| 63 | |
| 64 | impl RingIndex { |
| 65 | fn new(ring: &[Coord]) -> RingIndex { |
| 66 | let n = ring.len(); |
| 67 | let (mut min_y, mut max_y) = (f64::INFINITY, f64::NEG_INFINITY); |
| 68 | for &(_, y) in ring { |
| 69 | min_y = min_y.min(y); |
| 70 | max_y = max_y.max(y); |
| 71 | } |
| 72 | let span = max_y - min_y; |
| 73 | let bands = if n < 3 || span.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { |
| 74 | 1 |
| 75 | } else { |
| 76 | (n / EDGES_PER_BAND).clamp(1, MAX_BANDS) |
| 77 | }; |
| 78 | let inv = if span > 0.0 { bands as f64 / span } else { 0.0 }; |
| 79 | let mut idx = RingIndex { |
| 80 | min_y, |
| 81 | max_y, |
| 82 | inv, |
| 83 | bands, |
| 84 | offs: Vec::new(), |
| 85 | edges: Vec::new(), |
| 86 | }; |
| 87 | if n < 3 { |
| 88 | idx.offs = vec![0; bands + 1]; |
| 89 | return idx; |
| 90 | } |
| 91 | // Two passes (count, then fill) so the CSR is allocated exactly once. |
| 92 | let mut counts = vec![0u32; bands + 1]; |
| 93 | let span_of = |i: usize| -> Option<(usize, usize)> { |
| 94 | let (_, y1) = ring[i]; |
| 95 | let (_, y2) = ring[(i + 1) % n]; |
| 96 | // A horizontal edge never satisfies `(y1 > y) != (y2 > y)`. |
| 97 | if y1 == y2 { |
| 98 | return None; |
| 99 | } |
| 100 | Some((idx.band(y1.min(y2)), idx.band(y1.max(y2)))) |
| 101 | }; |
| 102 | for i in 0..n { |
| 103 | if let Some((lo, hi)) = span_of(i) { |
| 104 | for c in &mut counts[lo..=hi] { |
| 105 | *c += 1; |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | let mut offs = vec![0u32; bands + 1]; |
| 110 | for b in 0..bands { |
| 111 | offs[b + 1] = offs[b] + counts[b]; |
| 112 | } |
| 113 | let mut fill = offs.clone(); |
| 114 | let mut edges = vec![0u32; offs[bands] as usize]; |
| 115 | for i in 0..n { |
| 116 | if let Some((lo, hi)) = span_of(i) { |
| 117 | for f in &mut fill[lo..=hi] { |
| 118 | edges[*f as usize] = i as u32; |
| 119 | *f += 1; |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | idx.offs = offs; |
| 124 | idx.edges = edges; |
| 125 | idx |
| 126 | } |
| 127 | |
| 128 | #[inline] |
| 129 | fn band(&self, y: f64) -> usize { |
| 130 | let b = ((y - self.min_y) * self.inv).floor(); |
| 131 | // `as usize` saturates a negative to 0; clamp the top edge. |
| 132 | (b as usize).min(self.bands - 1) |
| 133 | } |
| 134 | |
| 135 | /// `rings::point_in_ring((x, y), ring)`, bit for bit. |
| 136 | #[inline] |
| 137 | fn contains(&self, (x, y): Coord, ring: &[Coord]) -> bool { |
| 138 | let n = ring.len(); |
| 139 | if n < 3 { |
| 140 | return false; |
| 141 | } |
| 142 | // No edge has `min <= y < max` outside this range, so no toggle. |
| 143 | if !(y >= self.min_y && y < self.max_y) { |
| 144 | return false; |
| 145 | } |
| 146 | let b = self.band(y); |
| 147 | let mut inside = false; |
| 148 | for &i in &self.edges[self.offs[b] as usize..self.offs[b + 1] as usize] { |
| 149 | let i = i as usize; |
| 150 | let (x1, y1) = ring[i]; |
| 151 | let (x2, y2) = ring[(i + 1) % n]; |
| 152 | if (y1 > y) != (y2 > y) { |
| 153 | let t = (y - y1) / (y2 - y1); |
| 154 | if x < x1 + t * (x2 - x1) { |
| 155 | inside = !inside; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | inside |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// Assemble every boundary's polygons (in boundary-id order) and index their |
| 164 | /// rings for [`stamp_regions`]. Boundaries that close nothing are dropped. |
| 165 | fn assemble_boundaries<L>( |
| 166 | boundaries: &[BoundaryRel], |
| 167 | outer_refs: &HashMap<i64, Vec<i64>>, |
| 168 | location: &L, |
| 169 | ) -> Vec<BoundaryPoly> |
| 170 | where |
| 171 | L: Fn(i64) -> Option<(i32, i32)> + Sync, |
| 172 | { |
| 173 | use rayon::prelude::*; |
| 174 | let mut ordered: Vec<&BoundaryRel> = boundaries.iter().collect(); |
| 175 | ordered.sort_by_key(|b| b.id); |
| 176 | let locate = |id: i64| -> Option<Coord> { |
| 177 | location(id).map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7)) |
| 178 | }; |
| 179 | let one = |b: &BoundaryRel| -> Option<BoundaryPoly> { |
| 180 | let members: Vec<MemberWay> = b |
| 181 | .member_ways |
| 182 | .iter() |
| 183 | .map(|(w, outer)| MemberWay { |
| 184 | refs: outer_refs.get(w).cloned().unwrap_or_default(), |
| 185 | outer: *outer, |
| 186 | }) |
| 187 | .collect(); |
| 188 | // The stats are a per-call report nobody reads on this path. |
| 189 | let polys = rings::assemble(&members, locate, &mut RingStats::default()); |
| 190 | if polys.is_empty() { |
| 191 | return None; |
| 192 | } |
| 193 | let (mut min_lon, mut min_lat) = (f64::INFINITY, f64::INFINITY); |
| 194 | let (mut max_lon, mut max_lat) = (f64::NEG_INFINITY, f64::NEG_INFINITY); |
| 195 | let mut areas = Vec::with_capacity(polys.len()); |
| 196 | for poly in &polys { |
| 197 | areas.push(rings::ring_area(&poly[0]).abs()); |
| 198 | for ring in poly { |
| 199 | for &(lon, lat) in ring { |
| 200 | min_lon = min_lon.min(lon); |
| 201 | min_lat = min_lat.min(lat); |
| 202 | max_lon = max_lon.max(lon); |
| 203 | max_lat = max_lat.max(lat); |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | let index = polys |
| 208 | .iter() |
| 209 | .map(|poly| poly.iter().map(|r| RingIndex::new(r)).collect()) |
| 210 | .collect(); |
| 211 | Some(BoundaryPoly { |
| 212 | tagged: poi_side::tag_relation(b.id), |
| 213 | admin_level: b.admin_level, |
| 214 | polys, |
| 215 | index, |
| 216 | areas, |
| 217 | min_lon, |
| 218 | min_lat, |
| 219 | max_lon, |
| 220 | max_lat, |
| 221 | }) |
| 222 | }; |
| 223 | // `with_max_len(1)`: a handful of country-sized boundaries dominate, so let |
| 224 | // each be stolen on its own. `collect` keeps the input (id) order. |
| 225 | let out: Vec<Option<BoundaryPoly>> = crate::par::install(|| { |
| 226 | ordered.par_iter().with_max_len(1).map(|b| one(b)).collect() |
| 227 | }); |
| 228 | out.into_iter().flatten().collect() |
| 229 | } |
| 230 | |
| 231 | /// POIs per containment work unit. |
| 232 | const STAMP_CHUNK: usize = 1024; |
| 233 | |
| 234 | /// Stamp every POI's [`Poi::region`]: self-links are already set, a node carried |
| 235 | /// as a boundary's `label`/`admin_centre` member takes that boundary's tagged id, |
| 236 | /// otherwise the smallest-area containing admin at or above the POI's |
| 237 | /// place-implied cap wins. Returns the stamped count. |
| 238 | /// |
| 239 | /// `pois[..from_nodes]` are nodes, which is the only slice the member-link map |
| 240 | /// can hit — node ids and way/relation ids share a namespace per element type, |
| 241 | /// and a way id equal to a label node id is a different object. |
| 242 | /// |
| 243 | /// Containment runs through a coarse 1°-cell grid over boundary bboxes, so a |
| 244 | /// planet build tests each POI only against the boundaries whose bbox covers it |
| 245 | /// instead of every admin relation on earth. |
| 246 | fn stamp_regions( |
| 247 | pois: &mut [Poi], |
| 248 | from_nodes: usize, |
| 249 | boundaries: &[BoundaryRel], |
| 250 | assembled: &[BoundaryPoly], |
| 251 | ) -> usize { |
| 252 | use rayon::prelude::*; |
| 253 | // Deterministic on double-labelling: the lowest boundary id wins. |
| 254 | let mut ordered: Vec<&BoundaryRel> = boundaries.iter().collect(); |
| 255 | ordered.sort_by_key(|b| b.id); |
| 256 | let mut labels: HashMap<i64, u64> = HashMap::new(); |
| 257 | for b in &ordered { |
| 258 | let tagged = poi_side::tag_relation(b.id); |
| 259 | for n in &b.label_nodes { |
| 260 | labels.entry(*n).or_insert(tagged); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new(); |
| 265 | for (i, b) in assembled.iter().enumerate() { |
| 266 | for cx in b.min_lon.floor() as i32..=b.max_lon.floor() as i32 { |
| 267 | for cy in b.min_lat.floor() as i32..=b.max_lat.floor() as i32 { |
| 268 | grid.entry((cx, cy)).or_default().push(i); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // One POI's answer, from that POI and read-only state alone. |
| 274 | let stamp = |i: usize, p: &mut Poi| -> bool { |
| 275 | if p.region != poi_side::REGION_NONE { |
| 276 | return true; |
| 277 | } |
| 278 | // Member links win over containment. |
| 279 | if i < from_nodes { |
| 280 | if let Some(tagged) = labels.get(&p.osm_id) { |
| 281 | p.region = *tagged; |
| 282 | return true; |
| 283 | } |
| 284 | } |
| 285 | let lon = p.lon_e7 as f64 * 1e-7; |
| 286 | let lat = p.lat_e7 as f64 * 1e-7; |
| 287 | let Some(cands) = grid.get(&(lon.floor() as i32, lat.floor() as i32)) else { |
| 288 | return false; |
| 289 | }; |
| 290 | let mut best: Option<(f64, u64)> = None; |
| 291 | for bi in cands { |
| 292 | let b = &assembled[*bi]; |
| 293 | if b.admin_level > p.place_cap { |
| 294 | continue; |
| 295 | } |
| 296 | for ((poly, idx), area) in b.polys.iter().zip(&b.index).zip(&b.areas) { |
| 297 | // The serial loop's three conjuncts, cheapest first. All three are |
| 298 | // pure, so their order cannot change whether `best` moves. |
| 299 | if best.is_none_or(|(a, _)| *area < a) |
| 300 | && idx[0].contains((lon, lat), &poly[0]) |
| 301 | // Holes excluded: inside an inner ring is not inside the admin. |
| 302 | && !poly[1..] |
| 303 | .iter() |
| 304 | .zip(&idx[1..]) |
| 305 | .any(|(h, hi)| hi.contains((lon, lat), h)) |
| 306 | { |
| 307 | best = Some((*area, b.tagged)); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | match best { |
| 312 | Some((_, tagged)) => { |
| 313 | p.region = tagged; |
| 314 | true |
| 315 | } |
| 316 | None => false, |
| 317 | } |
| 318 | }; |
| 319 | |
| 320 | crate::par::install(|| { |
| 321 | pois.par_chunks_mut(STAMP_CHUNK) |
| 322 | .enumerate() |
| 323 | .map(|(c, chunk)| { |
| 324 | let base = c * STAMP_CHUNK; |
| 325 | chunk |
| 326 | .iter_mut() |
| 327 | .enumerate() |
| 328 | .map(|(j, p)| stamp(base + j, p)) |
| 329 | .filter(|hit| *hit) |
| 330 | .count() |
| 331 | }) |
| 332 | .sum() |
| 333 | }) |
| 334 | } |
| 335 | |
| 336 | #[cfg(test)] |
| 337 | mod region_index_tests { |
| 338 | use super::*; |
| 339 | |
| 340 | /// A deterministic xorshift, so the property test needs no crate. |
| 341 | fn rng(seed: &mut u64) -> f64 { |
| 342 | *seed ^= *seed << 13; |
| 343 | *seed ^= *seed >> 7; |
| 344 | *seed ^= *seed << 17; |
| 345 | (*seed >> 11) as f64 / (1u64 << 53) as f64 |
| 346 | } |
| 347 | |
| 348 | /// The banded probe must agree with `rings::point_in_ring` on every point, |
| 349 | /// including probes exactly on vertex latitudes and outside the bbox. |
| 350 | #[test] |
| 351 | fn the_banded_probe_matches_the_full_ray_cast() { |
| 352 | let mut seed = 0x9E37_79B9_7F4A_7C15u64; |
| 353 | for n in [3usize, 4, 5, 17, 64, 1000, 5000] { |
| 354 | // A star-shaped (very concave) closed ring around (10, 50). |
| 355 | let mut ring: Vec<Coord> = (0..n) |
| 356 | .map(|k| { |
| 357 | let a = k as f64 / n as f64 * std::f64::consts::TAU; |
| 358 | let r = 0.2 + rng(&mut seed); |
| 359 | (10.0 + r * a.cos(), 50.0 + r * a.sin()) |
| 360 | }) |
| 361 | .collect(); |
| 362 | ring.push(ring[0]); |
| 363 | let idx = RingIndex::new(&ring); |
| 364 | let mut probes: Vec<Coord> = (0..4000) |
| 365 | .map(|_| (8.5 + 3.0 * rng(&mut seed), 48.5 + 3.0 * rng(&mut seed))) |
| 366 | .collect(); |
| 367 | // Exactly on vertex latitudes and on vertices themselves. |
| 368 | for &(vx, vy) in ring.iter().take(200) { |
| 369 | probes.push((vx, vy)); |
| 370 | probes.push((vx - 0.01, vy)); |
| 371 | probes.push((10.0, vy)); |
| 372 | } |
| 373 | for p in probes { |
| 374 | assert_eq!( |
| 375 | idx.contains(p, &ring), |
| 376 | rings::point_in_ring(p, &ring), |
| 377 | "n={n} p={p:?}" |
| 378 | ); |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn degenerate_rings_contain_nothing() { |
| 385 | let flat = vec![(0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (0.0, 1.0)]; |
| 386 | let idx = RingIndex::new(&flat); |
| 387 | assert!(!idx.contains((1.0, 1.0), &flat)); |
| 388 | assert!(!rings::point_in_ring((1.0, 1.0), &flat)); |
| 389 | let tiny = vec![(0.0, 0.0), (1.0, 1.0)]; |
| 390 | assert!(!RingIndex::new(&tiny).contains((0.5, 0.5), &tiny)); |
| 391 | } |
| 392 | } |