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

Modern-Apps.git / scripts / maps / osm_ingest / src / poi_build_part4.rs

poi_build_part4.rs234 lines · 9.9 KiBRaw
1// ---- poi_admin.bin: names, levels and parents of the linked boundaries -------
2//
3// `stamp_regions` gives each POI one boundary; this walks those boundaries up
4// to the top so the app can say "City, State, Country" without a polygon. The
5// table carries only boundaries some POI links to plus their ancestors, not
6// every admin relation on earth: that is everything a reader can reach from a
7// POI, at a fraction of the size.
8
9/// Degrees in one cell of the boundary-candidate grid (as in `stamp_regions`).
10const ADMIN_GRID_DEG: f64 = 1.0;
11
12/// The boundary table for `poi_admin.bin`: one entry per assembled boundary that
13/// a POI in `pois` links to, and per ancestor of those.
14///
15/// The parent of boundary B is the boundary of a LOWER `admin_level` that
16/// contains a point strictly inside B ([`interior_point`]) — the deepest such
17/// level, smallest area on a tie. Vertices are useless as probes: a city's
18/// border runs along its county's, so a vertex is on the parent's edge, where
19/// the ray cast may answer either way.
20fn admin_table(
21 boundaries: &[BoundaryRel],
22 assembled: &[BoundaryPoly],
23 pois: &[Poi],
24) -> Vec<crate::poi_admin::AdminEntry> {
25 use rayon::prelude::*;
26 let by_tag: HashMap<u64, usize> = assembled.iter().enumerate().map(|(i, b)| (b.tagged, i)).collect();
27 let names: HashMap<u64, &BoundaryRel> =
28 boundaries.iter().map(|b| (poi_side::tag_relation(b.id), b)).collect();
29 let grid = boundary_grid(assembled);
30
31 // Parent of every assembled boundary, computed only for the ones reached.
32 let parent_of = |i: usize| -> u64 {
33 let b = &assembled[i];
34 let Some(probe) = b.polys.iter().zip(&b.areas).max_by(|x, y| x.1.total_cmp(y.1)).and_then(|(p, _)| interior_point(p))
35 else {
36 return poi_side::REGION_NONE;
37 };
38 let cell = ((probe.0 / ADMIN_GRID_DEG).floor() as i32, (probe.1 / ADMIN_GRID_DEG).floor() as i32);
39 let mut best: Option<(u8, f64, u64)> = None;
40 for &ci in grid.get(&cell).map(Vec::as_slice).unwrap_or(&[]) {
41 let c = &assembled[ci];
42 if c.admin_level >= b.admin_level {
43 continue;
44 }
45 for ((poly, idx), area) in c.polys.iter().zip(&c.index).zip(&c.areas) {
46 let better = best.is_none_or(|(lvl, a, _)| c.admin_level > lvl || (c.admin_level == lvl && *area < a));
47 if better && polygon_contains(poly, idx, probe) {
48 best = Some((c.admin_level, *area, c.tagged));
49 }
50 }
51 }
52 best.map_or(poi_side::REGION_NONE, |(_, _, t)| t)
53 };
54
55 // Breadth-first from the linked boundaries; each round resolves one level of parents.
56 let mut parents: HashMap<u64, u64> = HashMap::new();
57 let mut frontier: Vec<u64> = pois.iter().map(|p| p.region).filter(|t| by_tag.contains_key(t)).collect();
58 frontier.sort_unstable();
59 frontier.dedup();
60 while !frontier.is_empty() {
61 let resolved: Vec<(u64, u64)> = crate::par::install(|| {
62 frontier.par_iter().with_max_len(1).map(|t| (*t, parent_of(by_tag[t]))).collect()
63 });
64 let mut next = Vec::new();
65 for (t, p) in resolved {
66 parents.insert(t, p);
67 if p != poi_side::REGION_NONE && !parents.contains_key(&p) && by_tag.contains_key(&p) {
68 next.push(p);
69 }
70 }
71 next.sort_unstable();
72 next.dedup();
73 frontier = next;
74 }
75
76 let mut out: Vec<crate::poi_admin::AdminEntry> = parents
77 .iter()
78 .map(|(t, p)| {
79 let rel = names.get(t);
80 crate::poi_admin::AdminEntry {
81 tagged: *t,
82 parent: *p,
83 admin_level: assembled[by_tag[t]].admin_level,
84 name: rel.map(|r| r.name.clone()).unwrap_or_default(),
85 name_en: rel.map(|r| r.name_en.clone()).unwrap_or_default(),
86 }
87 })
88 .collect();
89 out.sort_by_key(|e| e.tagged);
90 out
91}
92
93/// Boundary indices per [`ADMIN_GRID_DEG`] cell of their bbox.
94fn boundary_grid(assembled: &[BoundaryPoly]) -> HashMap<(i32, i32), Vec<usize>> {
95 let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
96 for (i, b) in assembled.iter().enumerate() {
97 for cx in b.min_lon.floor() as i32..=b.max_lon.floor() as i32 {
98 for cy in b.min_lat.floor() as i32..=b.max_lat.floor() as i32 {
99 grid.entry((cx, cy)).or_default().push(i);
100 }
101 }
102 }
103 grid
104}
105
106/// Whether `p` is inside the polygon's exterior ring and outside all its holes.
107fn polygon_contains(poly: &rings::Polygon, idx: &[RingIndex], p: Coord) -> bool {
108 idx[0].contains(p, &poly[0]) && !poly[1..].iter().zip(&idx[1..]).any(|(h, hi)| hi.contains(p, h))
109}
110
111/// A point strictly inside `poly` (exterior minus holes), or `None` for a
112/// degenerate polygon.
113///
114/// Scanline: a horizontal line between two distinct vertex latitudes near the
115/// middle of the ring (so it passes through no vertex) crosses the rings an
116/// even number of times; by the even-odd rule the stretches between crossings
117/// 1-2, 3-4, ... are inside, holes included. The midpoint of the widest one is
118/// as far from the border as that line allows.
119fn interior_point(poly: &rings::Polygon) -> Option<Coord> {
120 let outer = poly.first()?;
121 let mut ys: Vec<f64> = outer.iter().map(|c| c.1).collect();
122 ys.sort_by(f64::total_cmp);
123 ys.dedup();
124 if ys.len() < 2 {
125 return None;
126 }
127 let k = (ys.len() - 1) / 2;
128 let y = (ys[k] + ys[k + 1]) / 2.0;
129 let mut xs: Vec<f64> = Vec::new();
130 for ring in poly {
131 let n = ring.len();
132 for i in 0..n {
133 let (x1, y1) = ring[i];
134 let (x2, y2) = ring[(i + 1) % n];
135 if (y1 > y) != (y2 > y) {
136 xs.push(x1 + (y - y1) / (y2 - y1) * (x2 - x1));
137 }
138 }
139 }
140 xs.sort_by(f64::total_cmp);
141 xs.chunks_exact(2)
142 .max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0])))
143 .filter(|w| w[1] > w[0])
144 .map(|w| ((w[0] + w[1]) / 2.0, y))
145}
146
147#[cfg(test)]
148mod admin_tests {
149 use super::*;
150 use crate::poi_admin::{ADMIN_ENTRY_BYTES, ADMIN_HEADER_BYTES, ADMIN_MAGIC, ADMIN_NO_NAME};
151 use crate::testpbf;
152
153 struct Admin {
154 parent: u64,
155 level: u8,
156 name: String,
157 name_en: Option<String>,
158 }
159
160 /// Decode `poi_admin.bin` the way [`crate::poi_admin`] documents it.
161 fn read_admin(dir: &Path) -> HashMap<u64, Admin> {
162 let b = std::fs::read(dir.join("poi_admin.bin")).unwrap();
163 assert_eq!(&b[0..4], ADMIN_MAGIC);
164 let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap());
165 let u64_at = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().unwrap());
166 let count = u32_at(8) as usize;
167 let pool = &b[ADMIN_HEADER_BYTES + count * ADMIN_ENTRY_BYTES..];
168 let cstr = |off: u32| {
169 let s = &pool[off as usize..];
170 String::from_utf8(s[..s.iter().position(|c| *c == 0).unwrap()].to_vec()).unwrap()
171 };
172 (0..count)
173 .map(|i| {
174 let at = ADMIN_HEADER_BYTES + i * ADMIN_ENTRY_BYTES;
175 let en = u32_at(at + 20);
176 (
177 u64_at(at),
178 Admin {
179 parent: u64_at(at + 8),
180 level: b[at + 24],
181 name: cstr(u32_at(at + 16)),
182 name_en: (en != ADMIN_NO_NAME).then(|| cstr(en)),
183 },
184 )
185 })
186 .collect()
187 }
188
189 fn tagged(id: i64) -> u64 {
190 poi_side::tag_relation(id)
191 }
192
193 /// Country > state > city on a synthetic PBF: each POI links to its smallest
194 /// boundary, the table walks every linked boundary to the top, and a
195 /// boundary no POI reaches is left out.
196 #[test]
197 fn the_admin_table_walks_linked_boundaries_to_the_top() {
198 let (pbf_path, dir) = testpbf::write_admin_sample("poi_admin");
199 let stats = build(Paths { input: &pbf_path, geojson: &dir.join("pois.geojsonseq"), names: &dir.join("poi_names.bin"), index: &dir.join("poi_index.bin"), attrs: &dir.join("poi_attrs.bin"), spatial: &dir.join("poi_spatial.bin"), name_index: &dir.join("poi_name_index.bin"), region: &dir.join("poi_region.bin") })
200 .unwrap();
201 let admin = read_admin(&dir);
202 assert_eq!(stats.admin_entries, 3);
203 assert_eq!(admin.len(), 3, "country, state, city; the unreached town is not written");
204
205 let city = &admin[&tagged(testpbf::ADMIN_CITY_ID)];
206 assert_eq!((city.level, city.name.as_str()), (8, "Testcity"));
207 assert_eq!(city.parent, tagged(testpbf::ADMIN_STATE_ID));
208 assert_eq!(city.name_en, None);
209
210 let state = &admin[&tagged(testpbf::ADMIN_STATE_ID)];
211 assert_eq!((state.level, state.name.as_str()), (4, "Teststate"));
212 assert_eq!(state.parent, tagged(testpbf::ADMIN_COUNTRY_ID));
213
214 let country = &admin[&tagged(testpbf::ADMIN_COUNTRY_ID)];
215 assert_eq!((country.level, country.name.as_str()), (2, "Testlandia"));
216 assert_eq!(country.name_en.as_deref(), Some("Testland"));
217 assert_eq!(country.parent, 0, "the country is the top");
218 assert!(!admin.contains_key(&tagged(testpbf::ADMIN_GHOST_ID)));
219 }
220
221 #[test]
222 fn the_interior_point_avoids_holes_and_borders() {
223 // A 4x4 square with a 2x2 hole in its middle: the probe must land in the
224 // ring around the hole, never in the hole or on an edge.
225 let outer = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];
226 let hole = vec![(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0), (1.0, 1.0)];
227 let poly: rings::Polygon = vec![outer.clone(), hole.clone()];
228 let (x, y) = interior_point(&poly).unwrap();
229 assert!(rings::point_in_ring((x, y), &outer));
230 assert!(!rings::point_in_ring((x, y), &hole));
231 assert!(x > 0.0 && x < 4.0 && y > 0.0 && y < 4.0);
232 assert!(interior_point(&vec![vec![(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]]).is_none());
233 }
234}