Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part2.rs
extract_part2.rs335 lines · 13.7 KiBRaw
| 1 | /// Pass 2: refs of every relation member way. Moved whole from `extract`. |
| 2 | fn load_member_ways( |
| 3 | input: &Path, |
| 4 | blobs: &[pbf::BlobLoc], |
| 5 | blob_kinds: &[u8], |
| 6 | relations: &[Relation], |
| 7 | ) -> Result<MemberWays> { |
| 8 | // --- pass 2: the refs of every relation member way ------------------------------------ |
| 9 | // |
| 10 | // **Every** member, not just the ones pass 1 did not classify. A relation reaches its members by |
| 11 | // id, in the order it lists them, which is the one random access in this stage and the one thing |
| 12 | // a sequential spill file cannot serve. So the members — and only the members — stay resident, |
| 13 | // and that is what lets the other several million classified ways go to disk. California has |
| 14 | // 63 156 relations, so this table is small next to the one it replaces; planet has 8.4 M, so |
| 15 | // it is a sorted vector rather than a hash map (see [`MemberWays`]). |
| 16 | let wanted: Vec<i64> = { |
| 17 | let mut wanted: Vec<i64> = relations |
| 18 | .iter() |
| 19 | .flat_map(|r| r.members.iter().map(|(id, _)| *id)) |
| 20 | .collect(); |
| 21 | wanted.sort_unstable(); |
| 22 | wanted.dedup(); |
| 23 | wanted |
| 24 | }; |
| 25 | let mut members = MemberWays::empty(); |
| 26 | if !wanted.is_empty() { |
| 27 | let (chunks, _) = pbf::run_pass( |
| 28 | input, |
| 29 | blobs, |
| 30 | Some(blob_kinds), |
| 31 | KIND_WAYS, |
| 32 | "Pass 2: member ways", |
| 33 | Vec::<(i64, Vec<i64>)>::new, |
| 34 | |state, block| { |
| 35 | let mut kinds = 0u8; |
| 36 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el| { |
| 37 | if let Element::Way(way) = el { |
| 38 | if wanted.binary_search(&way.id).is_ok() { |
| 39 | state.push((way.id, way.refs.to_vec())); |
| 40 | } |
| 41 | } |
| 42 | Ok(()) |
| 43 | })?; |
| 44 | Ok(kinds) |
| 45 | }, |
| 46 | )?; |
| 47 | // Chunks arrive in file order and ways are sorted by id, so concatenation is sorted as |
| 48 | // long as no way id appears in two chunks (ids are unique in the PBF). Sortedness is |
| 49 | // asserted, not assumed: `MemberWays::build` sorts anyway, which is also what absorbs |
| 50 | // the (impossible in practice) duplicate across chunks. |
| 51 | let all: Vec<(i64, Vec<i64>)> = chunks.into_iter().flatten().collect(); |
| 52 | members = MemberWays::build(all); |
| 53 | } |
| 54 | |
| 55 | Ok(members) |
| 56 | } |
| 57 | |
| 58 | /// Relation member ways by id: the one random access in stage A. |
| 59 | /// |
| 60 | /// A `HashMap<i64, Vec<i64>>` costs ~48 B overhead per entry plus the hasher's table slack -- |
| 61 | /// at planet's 8.4 M member ways that is hundreds of MB beside the ref bytes themselves. This is |
| 62 | /// a sorted `Vec` with binary search instead: lookups are `O(log n)` rather than `O(1)`, but a |
| 63 | /// lookup is followed by cloning a ref vec and resolving every ref through the coordinate table, |
| 64 | /// so the search is noise next to the use. Built sorted once; every reader shares the shape. |
| 65 | pub struct MemberWays { |
| 66 | entries: Vec<(i64, Vec<i64>)>, |
| 67 | } |
| 68 | |
| 69 | impl MemberWays { |
| 70 | fn empty() -> MemberWays { |
| 71 | MemberWays { entries: Vec::new() } |
| 72 | } |
| 73 | |
| 74 | /// Build from `(way id, refs)` pairs in any order. Sorts by id; a duplicated id keeps its |
| 75 | /// first occurrence (ids are unique in the PBF, so this is defence, not logic). |
| 76 | fn build(mut all: Vec<(i64, Vec<i64>)>) -> MemberWays { |
| 77 | all.sort_by_key(|(id, _)| *id); |
| 78 | all.dedup_by_key(|(id, _)| *id); |
| 79 | MemberWays { entries: all } |
| 80 | } |
| 81 | |
| 82 | /// The refs of member way `id`, or `None` if pass 2 never saw it (an extract cut it away). |
| 83 | pub fn get(&self, id: i64) -> Option<&Vec<i64>> { |
| 84 | self.entries |
| 85 | .binary_search_by_key(&id, |(id, _)| *id) |
| 86 | .ok() |
| 87 | .map(|at| &self.entries[at].1) |
| 88 | } |
| 89 | |
| 90 | /// Every member's refs, for the ref collectors (order irrelevant: both collectors only add). |
| 91 | pub fn values(&self) -> impl Iterator<Item = &Vec<i64>> { |
| 92 | self.entries.iter().map(|(_, refs)| refs) |
| 93 | } |
| 94 | |
| 95 | /// How many member ways are held. |
| 96 | #[cfg(test)] |
| 97 | pub fn len(&self) -> usize { |
| 98 | self.entries.len() |
| 99 | } |
| 100 | |
| 101 | #[cfg(test)] |
| 102 | pub fn is_empty(&self) -> bool { |
| 103 | self.entries.is_empty() |
| 104 | } |
| 105 | |
| 106 | #[cfg(test)] |
| 107 | pub fn from_map(map: HashMap<i64, Vec<i64>>) -> MemberWays { |
| 108 | MemberWays::build(map.into_iter().collect()) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[cfg(test)] |
| 113 | mod member_ways_tests { |
| 114 | use super::*; |
| 115 | |
| 116 | /// The whole contract: lookups answer like the map, whatever order the pairs arrived in, and |
| 117 | /// a duplicated id keeps its first occurrence. |
| 118 | #[test] |
| 119 | fn lookups_match_the_map_regardless_of_input_order() { |
| 120 | let table = MemberWays::build(vec![ |
| 121 | (9, vec![10_000, 9_999]), |
| 122 | (1, vec![7, 8]), |
| 123 | (9, vec![1, 2, 3]), |
| 124 | (5, vec![]), |
| 125 | ]); |
| 126 | assert_eq!(table.len(), 3, "the duplicate id is absorbed"); |
| 127 | assert_eq!(table.get(1), Some(&vec![7, 8])); |
| 128 | assert_eq!(table.get(5), Some(&vec![]), "an empty ref list is still a member"); |
| 129 | assert_eq!(table.get(9), Some(&vec![10_000, 9_999]), "first occurrence wins"); |
| 130 | assert_eq!(table.get(2), None, "not a member at all"); |
| 131 | assert_eq!(table.get(-1), None, "negative ids never resolve"); |
| 132 | assert_eq!(table.get(i64::MAX), None, "past the end"); |
| 133 | // `values` covers every entry exactly once, for the ref collectors. |
| 134 | let mut seen: Vec<i64> = table.values().flatten().copied().collect(); |
| 135 | seen.sort_unstable(); |
| 136 | assert_eq!(seen, vec![7, 8, 9_999, 10_000]); |
| 137 | assert!(MemberWays::empty().is_empty(), "empty is empty"); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// Pass 3: id index plus resolved coordinates, with `places`/`poi` label nodes classified and |
| 142 | /// spilled in the same pass. Grew the sink, select and layers params when pass 4 was folded in. |
| 143 | /// |
| 144 | /// `region` filters `poi` label NODES to the bbox. `places` nodes are always |
| 145 | /// kept. Ways and relations are filtered later at materialise time, where the |
| 146 | /// resolved coordinates are in hand. |
| 147 | #[allow(clippy::too_many_arguments)] |
| 148 | fn build_resolved_table( |
| 149 | input: &Path, |
| 150 | blobs: &[pbf::BlobLoc], |
| 151 | blob_kinds: &[u8], |
| 152 | members: &MemberWays, |
| 153 | needed: NeededBits, |
| 154 | select: &Select, |
| 155 | layers: Layers, |
| 156 | region: Option<&osm_ingest::bbox::BBox>, |
| 157 | sink: &mut Sink, |
| 158 | stats: &mut Stats, |
| 159 | timer: &mut crate::timing::PhaseTimer, |
| 160 | ) -> Result<NodeLocations> { |
| 161 | // The fused bitset already holds every classified way's refs (set in pass |
| 162 | // 1's drain); member ways join here. No ways-spill re-scan: the refs were |
| 163 | // decoded and in hand where they were set. |
| 164 | let mut needed = needed; |
| 165 | for refs in members.values() { |
| 166 | for &id in refs { |
| 167 | needed.set_growable(id)?; |
| 168 | } |
| 169 | } |
| 170 | // Small extracts take the exact vector; planet-scale takes the bitset the |
| 171 | // words move straight into. The threshold now counts distinct ids (the old |
| 172 | // one counted duplicates), which only moves borderline extracts toward the |
| 173 | // vector path — whose input arrives sorted-unique, so its sort is trivial. |
| 174 | let table = if needed.len() <= REFS_IN_MEMORY { |
| 175 | let ids: Vec<i64> = needed.ids().collect(); |
| 176 | timer.switch("id-index"); |
| 177 | NodeLocations::new(ids)? |
| 178 | } else { |
| 179 | timer.switch("id-index"); |
| 180 | // The bitset's words move into the rank index directly (`from_bitset`), |
| 181 | // not through `ids()`: walking them out as ids and re-setting them |
| 182 | // would hold two ~1.5 GB words arrays at once. |
| 183 | let (words, count) = needed.into_words(); |
| 184 | NodeLocations::from_bitset(words, count)? |
| 185 | }; |
| 186 | timer.switch("coords-resolve"); |
| 187 | stats.nodes_needed = table.len() as u64; |
| 188 | // The node region is the bulk of a planet PBF, so it is inflated once: the coordinate resolve |
| 189 | // and the label-node classification share this pass. `classify` runs in the block visitor across |
| 190 | // the pool and is pure -- it is exactly what the old pass 4 body did per node -- and the labels |
| 191 | // it returns are drained to the sink **in chunk order**, ahead of every way and relation, which |
| 192 | // is the order pass 4 spilled them in and what keeps the archive byte-identical. |
| 193 | // |
| 194 | // Only label layers are consulted: a node is never a road, a lake or a building, so running the |
| 195 | // full schema over 2 B nodes would pay the tag scan for nothing. |
| 196 | // |
| 197 | // The region filter drops `poi` label nodes outside the bbox here. `places` |
| 198 | // nodes are always kept — a region build still names its countries. A `poi` |
| 199 | // node carries its own coordinates, so no location table is needed. |
| 200 | let classify = |node: &NodeView| { |
| 201 | if !select.matches(|k| node.tags.get_str(k)) { |
| 202 | return None; |
| 203 | } |
| 204 | // A node no label claimed may still be road furniture. Safety is asked only here, in the |
| 205 | // node pass, so a way or relation can never land in the point-only `safety` layer. |
| 206 | let class = schema::classify(&node.tags, false, layers) |
| 207 | .filter(|c| is_label(c.layer)) |
| 208 | .or_else(|| schema::safety::classify(&node.tags))?; |
| 209 | let safety = class.layer == tilecodec::mamaps::dict::LAYER_SAFETY; |
| 210 | if (safety || class.layer == tilecodec::mamaps::dict::LAYER_POI) |
| 211 | && !osm_ingest::bbox::keep_e7(region, node.lat_e7, node.lon_e7) |
| 212 | { |
| 213 | return None; |
| 214 | } |
| 215 | let name = schema::display_name(&node.tags, class.layer); |
| 216 | Some(( |
| 217 | class, |
| 218 | node.lon_e7 as f64 * 1e-7, |
| 219 | node.lat_e7 as f64 * 1e-7, |
| 220 | name, |
| 221 | if safety { tilecodec::mamaps::body::ID_NONE } else { tagged_id(node.id, ELEMENT_NODE) }, |
| 222 | )) |
| 223 | }; |
| 224 | let drain = |hits: Vec<(Class, f64, f64, Option<String>, u64)>| -> Result<()> { |
| 225 | for (class, lon, lat, name, id) in hits { |
| 226 | let encoded = |
| 227 | crate::store::EncodedGeom::live(&Geometry::Points(vec![(lon, lat)]))?; |
| 228 | sink.push_named(&class, &encoded, name.as_deref(), id)?; |
| 229 | stats.features += 1; |
| 230 | stats.nodes_classified += 1; |
| 231 | } |
| 232 | Ok(()) |
| 233 | }; |
| 234 | let table = resolve_nodes_with(input, blobs, blob_kinds, "Pass 3: nodes", table, classify, drain)?; |
| 235 | |
| 236 | Ok(table) |
| 237 | } |
| 238 | |
| 239 | /// The region bbox expanded for the lane join, in degrees. |
| 240 | /// |
| 241 | /// A recipient is at most 50 m long (`lanefill::MAX_STUB_M`, enforced again in `push`), |
| 242 | /// and a donor must share an endpoint node with it — so the shared node sits within ~50 m |
| 243 | /// of the recipient, and any donor that can pair with a kept recipient touches the bbox |
| 244 | /// expanded by a small margin. 0.1° (~11 km) is two orders of magnitude past the ~100 m |
| 245 | /// worst case (a 50 m recipient straddling the border sharing its far endpoint), so the |
| 246 | /// fringe keeps every pair materialise can consult while dropping the rest of the planet. |
| 247 | /// `None` (world) disables the filter: every way can pair, everything resolves. |
| 248 | fn expanded_fringe(region: &osm_ingest::bbox::BBox) -> osm_ingest::bbox::BBox { |
| 249 | const MARGIN_DEG: f64 = 0.1; |
| 250 | osm_ingest::bbox::BBox { |
| 251 | min_lon: (region.min_lon - MARGIN_DEG).max(-180.0), |
| 252 | min_lat: (region.min_lat - MARGIN_DEG).max(-90.0), |
| 253 | max_lon: (region.max_lon + MARGIN_DEG).min(180.0), |
| 254 | max_lat: (region.max_lat + MARGIN_DEG).min(90.0), |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// Whether the resolved line touches the fringe box. `None` (world) is always true. |
| 259 | fn fringe_touches( |
| 260 | fringe: Option<&osm_ingest::bbox::BBox>, |
| 261 | line: &[(f64, f64)], |
| 262 | ) -> bool { |
| 263 | let Some(fringe) = fringe else { |
| 264 | return true; |
| 265 | }; |
| 266 | line.iter().any(|&(lon, lat)| fringe.contains(lon, lat)) |
| 267 | } |
| 268 | |
| 269 | #[cfg(test)] |
| 270 | mod fringe_tests { |
| 271 | use super::*; |
| 272 | |
| 273 | fn california() -> osm_ingest::bbox::BBox { |
| 274 | osm_ingest::bbox::BBox { |
| 275 | min_lon: -124.5, |
| 276 | min_lat: 32.5, |
| 277 | max_lon: -114.0, |
| 278 | max_lat: 42.0, |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | fn the_fringe_is_the_bbox_expanded_a_hair_in_every_direction() { |
| 284 | let fringe = expanded_fringe(&california()); |
| 285 | assert!((fringe.min_lon - (-124.6)).abs() < 1e-9); |
| 286 | assert!((fringe.min_lat - 32.4).abs() < 1e-9); |
| 287 | assert!((fringe.max_lon - (-113.9)).abs() < 1e-9); |
| 288 | assert!((fringe.max_lat - 42.1).abs() < 1e-9); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn the_fringe_clamps_at_the_world_edges() { |
| 293 | let world = osm_ingest::bbox::BBox { |
| 294 | min_lon: -180.0, |
| 295 | min_lat: -90.0, |
| 296 | max_lon: 180.0, |
| 297 | max_lat: 90.0, |
| 298 | }; |
| 299 | assert_eq!(expanded_fringe(&world), world, "clamped, not wrapped"); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn world_keeps_everything_and_the_fringe_keeps_only_what_touches() { |
| 304 | let fringe = expanded_fringe(&california()); |
| 305 | let inside = vec![(-122.4, 37.8)]; |
| 306 | let straddling = vec![(-124.55, 39.0)]; |
| 307 | let far = vec![(-100.0, 40.0)]; |
| 308 | assert!(fringe_touches(None, &far), "world disables the filter"); |
| 309 | assert!(fringe_touches(Some(&fringe), &inside)); |
| 310 | assert!( |
| 311 | fringe_touches(Some(&fringe), &straddling), |
| 312 | "a border-straddling recipient is within the margin", |
| 313 | ); |
| 314 | assert!(!fringe_touches(Some(&fringe), &far), "Nevada never pairs with California"); |
| 315 | assert!( |
| 316 | !fringe_touches(Some(&fringe), &[]), |
| 317 | "a way with no resolved geometry joins nothing", |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | /// The soundness case: a ≤50 m recipient straddling the border and its donor's |
| 322 | /// endpoint at their shared node — both within the margin, so the pair survives. |
| 323 | #[test] |
| 324 | fn a_border_pair_survives_the_fringe() { |
| 325 | let fringe = expanded_fringe(&california()); |
| 326 | // Recipient crossing the western edge; shared node 20 m outside. |
| 327 | let recipient = vec![(-124.52, 39.0), (-124.4999, 39.0)]; |
| 328 | // Donor running outward from the shared node. |
| 329 | let donor = vec![(-124.52, 39.0), (-124.53, 39.001)]; |
| 330 | assert!(fringe_touches(Some(&fringe), &recipient)); |
| 331 | assert!(fringe_touches(Some(&fringe), &donor)); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | include!("extract_part2_s1.rs"); |