Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / extract_part2.rs
extract_part2.rs307 lines · 10.1 KiBRaw
| 1 | fn build_admin_city( |
| 2 | input: &Path, |
| 3 | blobs: &[pbf::BlobLoc], |
| 4 | out: &Path, |
| 5 | opts: &Options, |
| 6 | ) -> Result<Stats> { |
| 7 | let select = Select::parse(&admin::FILTERS)?; |
| 8 | |
| 9 | // Pass 1: relations, which decide which ways matter. |
| 10 | let (chunks, blob_kinds) = pbf::run_pass( |
| 11 | input, |
| 12 | blobs, |
| 13 | None, |
| 14 | KIND_RELATIONS, |
| 15 | "Pass 1: relations", |
| 16 | Vec::<AdminRow>::new, |
| 17 | |state: &mut Vec<AdminRow>, block| admin_relation_blob(state, block, &select), |
| 18 | )?; |
| 19 | let mut rows: Vec<AdminRow> = Vec::new(); |
| 20 | for chunk in chunks { |
| 21 | rows.extend(chunk); |
| 22 | } |
| 23 | let mut wanted_ways: Vec<i64> = rows.iter().flat_map(|r| r.members.iter().map(|m| m.0)).collect(); |
| 24 | wanted_ways.sort_unstable(); |
| 25 | wanted_ways.dedup(); |
| 26 | println!( |
| 27 | "{} admin_level=8 relation(s), {} member way(s)", |
| 28 | rows.len(), |
| 29 | wanted_ways.len() |
| 30 | ); |
| 31 | |
| 32 | // Pass 2: the member ways' node refs, IN ORDER. Nothing sorts or dedups them: |
| 33 | // vertex order is the geometry. See the `rings` module docs. |
| 34 | let (chunks, _) = pbf::run_pass( |
| 35 | input, |
| 36 | blobs, |
| 37 | Some(&blob_kinds), |
| 38 | KIND_WAYS, |
| 39 | "Pass 2: ways", |
| 40 | AdminWayPass::default, |
| 41 | |state, block| admin_way_blob(state, block, &wanted_ways), |
| 42 | )?; |
| 43 | let mut member_refs: HashMap<i64, Vec<i64>> = HashMap::new(); |
| 44 | for chunk in chunks { |
| 45 | member_refs.extend(chunk.wanted); |
| 46 | } |
| 47 | |
| 48 | // Pass 3: node coordinates. |
| 49 | let table = NodeLocations::new( |
| 50 | member_refs.values().flat_map(|r| r.iter().copied()).collect(), |
| 51 | )?; |
| 52 | println!("{} node location(s) needed", table.len()); |
| 53 | let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?; |
| 54 | |
| 55 | let locate = |id: i64| -> Option<Coord> { |
| 56 | table |
| 57 | .get(id) |
| 58 | .map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7)) |
| 59 | }; |
| 60 | |
| 61 | let mut lines: Vec<LineFeature> = Vec::new(); |
| 62 | let mut stats = RingStats::default(); |
| 63 | let mut outside_bbox = 0usize; |
| 64 | let mut no_geometry = 0usize; |
| 65 | for row in &rows { |
| 66 | let members: Vec<MemberWay> = row |
| 67 | .members |
| 68 | .iter() |
| 69 | .filter_map(|(way, outer)| { |
| 70 | member_refs.get(way).map(|refs| MemberWay { |
| 71 | refs: refs.clone(), |
| 72 | outer: *outer, |
| 73 | }) |
| 74 | }) |
| 75 | .collect(); |
| 76 | let polygons = rings::assemble(&members, locate, &mut stats); |
| 77 | if polygons.is_empty() { |
| 78 | no_geometry += 1; |
| 79 | continue; |
| 80 | } |
| 81 | if !parts_touch_bbox( |
| 82 | &polygons.iter().flatten().cloned().collect::<Vec<_>>(), |
| 83 | opts.bbox.as_ref(), |
| 84 | ) { |
| 85 | outside_bbox += 1; |
| 86 | continue; |
| 87 | } |
| 88 | // A relation with one ring is a Polygon; several are a MultiPolygon. Both |
| 89 | // are what `keep_geometry` accepted, and the tiler takes either. |
| 90 | let geometry = if polygons.len() == 1 { |
| 91 | Geometry::Polygon(polygons.into_iter().next().expect("non-empty")) |
| 92 | } else { |
| 93 | Geometry::MultiPolygon(polygons) |
| 94 | }; |
| 95 | let t = AdminTags { |
| 96 | name: row.name.as_deref(), |
| 97 | name_en_tag: row.name_en.as_deref(), |
| 98 | ..Default::default() |
| 99 | }; |
| 100 | let Some(f) = admin::feature(&t, geometry, row.id) else { |
| 101 | continue; |
| 102 | }; |
| 103 | lines.push(LineFeature { |
| 104 | sort: ("relation", row.id), |
| 105 | rendered: render(&f), |
| 106 | }); |
| 107 | } |
| 108 | |
| 109 | let written = write_lines(out, lines)?; |
| 110 | println!( |
| 111 | "Wrote {written} admin_city feature(s) to {} ({} outer, {} inner ring(s))", |
| 112 | out.display(), |
| 113 | stats.outer_rings, |
| 114 | stats.inner_rings |
| 115 | ); |
| 116 | // Loud, because an unclosed ring is a data problem the operator can act on -- |
| 117 | // usually a member missing from the extract. |
| 118 | if stats.unclosed > 0 || stats.orphan_inner > 0 || no_geometry > 0 { |
| 119 | println!( |
| 120 | "{} ring(s) would not close, {} orphan hole(s) dropped, {} relation(s) yielded no geometry", |
| 121 | stats.unclosed, stats.orphan_inner, no_geometry |
| 122 | ); |
| 123 | } |
| 124 | if outside_bbox > 0 { |
| 125 | println!("{outside_bbox} feature(s) dropped by --bbox"); |
| 126 | } |
| 127 | Ok(Stats { |
| 128 | features: written, |
| 129 | from_nodes: 0, |
| 130 | from_ways: 0, |
| 131 | from_relations: written, |
| 132 | outside_bbox, |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | fn admin_relation_blob( |
| 137 | state: &mut Vec<AdminRow>, |
| 138 | block: &pbf::PrimitiveBlock, |
| 139 | select: &Select, |
| 140 | ) -> Result<u8> { |
| 141 | let mut kinds = 0u8; |
| 142 | visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| { |
| 143 | if let Element::Relation(r) = el { |
| 144 | if !select.matches(|k| r.tags.get_str(k)) { |
| 145 | return Ok(()); |
| 146 | } |
| 147 | let t = AdminTags { |
| 148 | boundary: r.tags.get_str("boundary"), |
| 149 | admin_level: r.tags.get_str("admin_level"), |
| 150 | name_en_tag: r.tags.get_str("name:en"), |
| 151 | name: r.tags.get_str("name"), |
| 152 | type_: r.tags.get_str("type"), |
| 153 | }; |
| 154 | if !admin::is_city(&t) { |
| 155 | return Ok(()); |
| 156 | } |
| 157 | // An empty role means outer, per the OSM boundary convention: most real |
| 158 | // members are unroled, and treating them as holes would leave nearly |
| 159 | // every boundary with no exterior at all. |
| 160 | let members: Vec<(i64, bool)> = r |
| 161 | .members |
| 162 | .iter() |
| 163 | .filter(|m: &&Member| m.kind == MEMBER_WAY) |
| 164 | .filter_map(|m| match m.role { |
| 165 | b"outer" | b"" => Some((m.id, true)), |
| 166 | b"inner" => Some((m.id, false)), |
| 167 | // Anything else (`label`, `admin_centre`, a subarea) is not part |
| 168 | // of the edge. |
| 169 | _ => None, |
| 170 | }) |
| 171 | .collect(); |
| 172 | if members.is_empty() { |
| 173 | return Ok(()); |
| 174 | } |
| 175 | state.push(AdminRow { |
| 176 | id: r.id, |
| 177 | name: t.name.map(str::to_string), |
| 178 | name_en: t.name_en_tag.map(str::to_string), |
| 179 | members, |
| 180 | }); |
| 181 | } |
| 182 | Ok(()) |
| 183 | })?; |
| 184 | Ok(kinds) |
| 185 | } |
| 186 | |
| 187 | fn admin_way_blob( |
| 188 | state: &mut AdminWayPass, |
| 189 | block: &pbf::PrimitiveBlock, |
| 190 | wanted: &[i64], |
| 191 | ) -> Result<u8> { |
| 192 | let mut kinds = 0u8; |
| 193 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| { |
| 194 | if let Element::Way(w) = el { |
| 195 | if w.refs.len() >= 2 && wanted.binary_search(&w.id).is_ok() { |
| 196 | state.wanted.push((w.id, w.refs.to_vec())); |
| 197 | } |
| 198 | } |
| 199 | Ok(()) |
| 200 | })?; |
| 201 | Ok(kinds) |
| 202 | } |
| 203 | |
| 204 | // --- shared output -------------------------------------------------------- |
| 205 | |
| 206 | /// A rendered feature plus the key it sorts on. |
| 207 | /// |
| 208 | /// Rendering before the sort means the sort moves one `Vec<u8>` per feature rather |
| 209 | /// than a geometry, and the writer then has nothing left to decide. |
| 210 | struct LineFeature { |
| 211 | sort: (&'static str, i64), |
| 212 | rendered: Vec<u8>, |
| 213 | } |
| 214 | |
| 215 | fn render(f: &Feature) -> Vec<u8> { |
| 216 | let mut line = Vec::new(); |
| 217 | geojson::render_feature(f, &mut line); |
| 218 | line |
| 219 | } |
| 220 | |
| 221 | /// `true` when there is no bbox, or any vertex of any part is inside it. |
| 222 | /// |
| 223 | /// Whole-element, matching `osmium extract`'s default `complete_ways` strategy: a |
| 224 | /// way with one node in the box is kept entire, overspill included. Truncating it |
| 225 | /// at the boundary would invent a vertex that is not in OSM, and the tiler clips |
| 226 | /// properly per tile later anyway. |
| 227 | fn parts_touch_bbox(parts: &[Vec<Coord>], bbox: Option<&BBox>) -> bool { |
| 228 | let Some(b) = bbox else { return true }; |
| 229 | parts |
| 230 | .iter() |
| 231 | .flatten() |
| 232 | .any(|(lon, lat)| b.contains(*lon, *lat)) |
| 233 | } |
| 234 | |
| 235 | /// Sort by `(element kind, id)` and write. Deterministic, so two runs of the same |
| 236 | /// input are byte-identical and a diff against the previous build shows only real |
| 237 | /// changes. |
| 238 | fn write_lines(out: &Path, mut lines: Vec<LineFeature>) -> Result<usize> { |
| 239 | lines.sort_by_key(|l| l.sort); |
| 240 | let mut writer = BufWriter::new(create(out)?); |
| 241 | for l in &lines { |
| 242 | writer.write_all(&l.rendered).map_err(io_err)?; |
| 243 | } |
| 244 | writer.flush().map_err(io_err)?; |
| 245 | Ok(lines.len()) |
| 246 | } |
| 247 | |
| 248 | fn create(path: &Path) -> Result<File> { |
| 249 | File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) |
| 250 | } |
| 251 | |
| 252 | fn io_err(e: std::io::Error) -> Error { |
| 253 | Error(e.to_string()) |
| 254 | } |
| 255 | |
| 256 | // --- CLI ------------------------------------------------------------------ |
| 257 | |
| 258 | pub struct Args { |
| 259 | pub input: PathBuf, |
| 260 | pub out: PathBuf, |
| 261 | pub layer: Layer, |
| 262 | pub bbox: Option<BBox>, |
| 263 | /// `None` leaves the pool at whatever `par::threads()` decides. |
| 264 | pub threads: Option<usize>, |
| 265 | } |
| 266 | |
| 267 | /// `osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX] [--threads N]` |
| 268 | pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { |
| 269 | let mut input: Option<PathBuf> = None; |
| 270 | let mut out: Option<PathBuf> = None; |
| 271 | let mut layer: Option<Layer> = None; |
| 272 | let mut bbox: Option<BBox> = None; |
| 273 | let mut threads: Option<usize> = None; |
| 274 | let mut i = 0; |
| 275 | while i < args.len() { |
| 276 | match args[i].as_str() { |
| 277 | flag @ ("--out" | "--layer" | "--bbox" | "--threads") => { |
| 278 | i += 1; |
| 279 | let value = args |
| 280 | .get(i) |
| 281 | .ok_or_else(|| format!("{flag} needs a value"))? |
| 282 | .as_str(); |
| 283 | match flag { |
| 284 | "--out" => out = Some(PathBuf::from(value)), |
| 285 | "--layer" => layer = Some(Layer::parse(value)?), |
| 286 | "--threads" => threads = Some(crate::par::parse_threads(value)?), |
| 287 | _ => bbox = Some(BBox::parse(value).map_err(|e| e.0)?), |
| 288 | } |
| 289 | } |
| 290 | a if a.starts_with('-') => return Err(format!("unknown option: {a}")), |
| 291 | a => { |
| 292 | if input.is_some() { |
| 293 | return Err(format!("unexpected extra argument: {a}")); |
| 294 | } |
| 295 | input = Some(PathBuf::from(a)); |
| 296 | } |
| 297 | } |
| 298 | i += 1; |
| 299 | } |
| 300 | Ok(Args { |
| 301 | input: input.ok_or_else(|| "missing IN.osm.pbf".to_string())?, |
| 302 | out: out.ok_or_else(|| "--out is required".to_string())?, |
| 303 | layer: layer.ok_or_else(|| "--layer is required".to_string())?, |
| 304 | bbox, |
| 305 | threads, |
| 306 | }) |
| 307 | } |