Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_fallback_s1.rs
extract_fallback_s1.rs205 lines · 9.5 KiBRaw
| 1 | /// [`extend_region_links`], also filling `country_zooms`: place tagged id → label start |
| 2 | /// zoom for `country` places, from each country's ground footprint and headcount (see |
| 3 | /// [`country_zoom`]). `populations` maps place tagged id → `population` tag headcount |
| 4 | /// (relation places; node/way countries are absent and score as unpopulated — the area |
| 5 | /// term still separates Russia from Nauru). The caller hands both maps to the tiler |
| 6 | /// beside `region_links`. |
| 7 | pub fn extend_region_links_with( |
| 8 | store: &crate::store::Store, |
| 9 | region_links: &mut HashMap<u64, u64>, |
| 10 | country_zooms: &mut HashMap<u64, u8>, |
| 11 | populations: &HashMap<u64, u64>, |
| 12 | ) -> Result<FallbackStats> { |
| 13 | // Pass 1: boundary shapes AND places, in one scan. Only `region_area` |
| 14 | // areas (the mask's own shapes, carrying the admin level in `kind_detail`); |
| 15 | // border lines enclose nothing. Places are positional, so node, |
| 16 | // way-centroided and relation-centroided labels all link by the tagged id |
| 17 | // they already carry. |
| 18 | // |
| 19 | // One scan, not two: the store reader is one sequential cursor over tens |
| 20 | // of GB of spill, and both passes filtered it by layer. Collecting both |
| 21 | // vectors in a single streaming pass deletes a full decode. Peak is |
| 22 | // unchanged — boundaries already lived through place collection. |
| 23 | struct PlacePoint { |
| 24 | id: u64, |
| 25 | point: (f64, f64), |
| 26 | kind: Band, |
| 27 | kind_name: String, |
| 28 | } |
| 29 | enum Kept { |
| 30 | Boundary(Boundary), |
| 31 | Place(PlacePoint), |
| 32 | } |
| 33 | // The scan decodes the whole store across the pool (`Store::par_scan_where`, file order kept), and |
| 34 | // the per-feature filter -- including `Boundary::new`'s area and bbox walk -- runs there too. |
| 35 | // The split into the two vectors below is in file order, so both are exactly what the |
| 36 | // one-cursor loop built. |
| 37 | // Pre-filter on the packed class (no geometry decoded): only an id-carrying boundary area |
| 38 | // or place can pass the filter below. |
| 39 | let kept = store.par_scan_where( |
| 40 | |class, has_id| { |
| 41 | has_id |
| 42 | && ((class.layer == LAYER_BOUNDARIES && class.area) || class.layer == LAYER_PLACES) |
| 43 | }, |
| 44 | |feature| { |
| 45 | if feature.id == ID_NONE { |
| 46 | return None; |
| 47 | } |
| 48 | if feature.class.layer == LAYER_BOUNDARIES && feature.class.area { |
| 49 | let Geometry::Polygons(polygons) = feature.geometry else { |
| 50 | return None; |
| 51 | }; |
| 52 | if polygons.is_empty() { |
| 53 | return None; |
| 54 | } |
| 55 | Some(Kept::Boundary(Boundary::new(feature.id, feature.class.kind_detail, polygons))) |
| 56 | } else if feature.class.layer == LAYER_PLACES { |
| 57 | let Geometry::Points(points) = feature.geometry else { |
| 58 | return None; |
| 59 | }; |
| 60 | let &point = points.first()?; |
| 61 | let kind_name = place_kind_name(feature.class.kind)?; |
| 62 | let band = band_for_place_kind(kind_name)?; |
| 63 | Some(Kept::Place(PlacePoint { |
| 64 | id: feature.id, |
| 65 | point, |
| 66 | kind: band, |
| 67 | kind_name: kind_name.to_string(), |
| 68 | })) |
| 69 | } else { |
| 70 | None |
| 71 | } |
| 72 | }, |
| 73 | )?; |
| 74 | let mut boundaries: Vec<Boundary> = Vec::new(); |
| 75 | let mut places: Vec<PlacePoint> = Vec::new(); |
| 76 | for item in kept { |
| 77 | match item { |
| 78 | Kept::Boundary(b) => boundaries.push(b), |
| 79 | Kept::Place(p) => places.push(p), |
| 80 | } |
| 81 | } |
| 82 | boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0); |
| 83 | let grid = Grid::build(&boundaries); |
| 84 | // The `country_zoom` lookup below used to walk `boundaries` linearly per |
| 85 | // linked country; indexed by id so it is a hash lookup instead. Built |
| 86 | // once — the vec never moves again after this. |
| 87 | let boundary_by_id: HashMap<u64, usize> = |
| 88 | boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect(); |
| 89 | |
| 90 | // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all |
| 91 | // link by the tagged id they already carry — the only path that can link non-node places, |
| 92 | // since the member map is node-keyed. Country labels also gain their area+population |
| 93 | // start zoom here (see `country_zoom`): the linked boundary's footprint is in hand, |
| 94 | // so no third pass is needed. The headcount comes from `populations` (relation |
| 95 | // places, filled by the caller while tags were in hand); absent entries score as |
| 96 | // unpopulated — Antarctica's case — never as missing. |
| 97 | // |
| 98 | // Collected serially first — the store reader is one sequential cursor — |
| 99 | // then linked on the pool: `select_link` is pure per-place work over the |
| 100 | // shared grid, and the drain inserts in collection order with member |
| 101 | // links winning, exactly as the serial loop did. `select_link` returns |
| 102 | // at most one target per place, so the drain cannot double-insert and |
| 103 | // the map bytes are identical. |
| 104 | // |
| 105 | // NOTE: `places` now arrives from the fused pass-1 scan above (same |
| 106 | // reader, same filter, same spill order), not from a second scan. What |
| 107 | // follows is unchanged: drain order — and therefore every inserted key, |
| 108 | // value, stat and country zoom — is identical. |
| 109 | let mut stats = FallbackStats::default(); |
| 110 | let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new(); |
| 111 | // Member links always win: counted exactly as the serial loop did, |
| 112 | // and skipped in the link pass so nothing contends on the map. |
| 113 | for place in &places { |
| 114 | stats.places_total += 1; |
| 115 | let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0)); |
| 116 | entry.0 += 1; |
| 117 | if region_links.contains_key(&place.id) { |
| 118 | stats.member_linked += 1; |
| 119 | entry.1 += 1; |
| 120 | } |
| 121 | } |
| 122 | // Parallel link: one candidate-set build + `select_link` per |
| 123 | // member-less place, on the pool; the drain inserts in collection |
| 124 | // order, so the map — and the stats — are identical at every thread |
| 125 | // count. `select_link` returns at most one target per place, so the |
| 126 | // drain cannot double-insert. The bar ticks in the drain per place, so |
| 127 | // it spans the whole pass even though the expensive half runs on the |
| 128 | // pool. |
| 129 | let mut bar = Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true); |
| 130 | const FALLBACK_BATCH: usize = 16 * 1024; |
| 131 | let mut batch: Vec<usize> = Vec::with_capacity(FALLBACK_BATCH); |
| 132 | let mut built: Vec<Option<u64>> = Vec::with_capacity(FALLBACK_BATCH); |
| 133 | let mut at = 0usize; |
| 134 | while at < places.len() { |
| 135 | batch.clear(); |
| 136 | while at < places.len() && batch.len() < FALLBACK_BATCH { |
| 137 | if region_links.contains_key(&places[at].id) { |
| 138 | // Member-linked: counted above, nothing to compute. The tick |
| 139 | // keeps the bar spanning every place, not just computed ones. |
| 140 | bar.tick("place(s)"); |
| 141 | at += 1; |
| 142 | continue; |
| 143 | } |
| 144 | batch.push(at); |
| 145 | at += 1; |
| 146 | } |
| 147 | if batch.is_empty() { |
| 148 | continue; |
| 149 | } |
| 150 | built.clear(); |
| 151 | par::install(|| { |
| 152 | batch |
| 153 | .par_iter() |
| 154 | .map(|&pi| { |
| 155 | let place = &places[pi]; |
| 156 | let candidates: Vec<&Boundary> = |
| 157 | grid.candidates_for(place.point).map(|i| &boundaries[i]).collect(); |
| 158 | select_link(place.point, place.kind, &candidates) |
| 159 | }) |
| 160 | .collect_into_vec(&mut built) |
| 161 | }); |
| 162 | for (&pi, target) in batch.iter().zip(built.drain(..)) { |
| 163 | let place = &places[pi]; |
| 164 | if let Some(target) = target { |
| 165 | region_links.insert(place.id, target); |
| 166 | stats.fallback_linked += 1; |
| 167 | if let Some(entry) = per_kind.get_mut(&place.kind_name) { |
| 168 | entry.1 += 1; |
| 169 | } |
| 170 | } |
| 171 | // A country label starts at the zoom its footprint earns. The |
| 172 | // linked boundary (member half inserted before this pass, |
| 173 | // fallback half just above — both visible in `region_links` |
| 174 | // now) carries the ground area; the headcount comes from |
| 175 | // `populations` (relation places, filled by the caller while |
| 176 | // tags were in hand); absent entries score as unpopulated — |
| 177 | // Antarctica's case — never as missing. Unlinked countries keep |
| 178 | // the schema floor (z0): a missing link must never hide a |
| 179 | // country. |
| 180 | if place.kind_name == "country" { |
| 181 | if let Some(target) = region_links.get(&place.id) { |
| 182 | if let Some(&bi) = boundary_by_id.get(target) { |
| 183 | let boundary = &boundaries[bi]; |
| 184 | let mid_lat = |
| 185 | boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0); |
| 186 | let population = populations.get(&place.id).copied().unwrap_or(0); |
| 187 | country_zooms |
| 188 | .insert(place.id, country_zoom(boundary.area, mid_lat, population)); |
| 189 | stats.country_zooms += 1; |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | bar.tick("place(s)"); |
| 194 | } |
| 195 | } |
| 196 | bar.finish("place(s)"); |
| 197 | stats.fallback_missed = |
| 198 | stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked); |
| 199 | let mut kinds: Vec<(String, u64, u64)> = |
| 200 | per_kind.into_iter().map(|(kind, (total, linked))| (kind, total, linked)).collect(); |
| 201 | kinds.sort_by(|a, b| a.0.cmp(&b.0)); |
| 202 | stats.per_kind = kinds; |
| 203 | Ok(stats) |
| 204 | } |
| 205 |