Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_build_part1.rs
poi_build_part1.rs330 lines · 12.1 KiBRaw
| 1 | fn make_poi( |
| 2 | (lat, lon): (f64, f64), |
| 3 | type_: u16, |
| 4 | osm_id: i64, |
| 5 | name: &[u8], |
| 6 | attrs: Vec<u8>, |
| 7 | region: u64, |
| 8 | place_cap: u8, |
| 9 | ) -> Poi { |
| 10 | let lat_e7 = (lat * 1e7).round() as i32; |
| 11 | let lon_e7 = (lon * 1e7).round() as i32; |
| 12 | Poi { |
| 13 | lat, |
| 14 | lon, |
| 15 | lat_e7, |
| 16 | lon_e7, |
| 17 | // Derived from the *stored* integers, not the pre-rounding f64, so the |
| 18 | // sort order matches the key a reader recomputes from `poi_index.bin`. |
| 19 | morton: spatial_from_e7(lat_e7, lon_e7), |
| 20 | type_, |
| 21 | osm_id, |
| 22 | name: name.to_vec(), |
| 23 | attrs, |
| 24 | region, |
| 25 | place_cap, |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | struct Written { |
| 30 | records: usize, |
| 31 | unique_names: usize, |
| 32 | name_bytes: u32, |
| 33 | with_attrs: usize, |
| 34 | unique_attrs: usize, |
| 35 | attr_bytes: usize, |
| 36 | spatial_cells: usize, |
| 37 | name_entries: usize, |
| 38 | } |
| 39 | |
| 40 | /// Output buffer size. Large sequential writes: the build box's root is btrfs |
| 41 | /// with `compress-force=zstd`, which pays per extent, and a default 8 KiB |
| 42 | /// `BufWriter` turns a multi-GB geojson into a million small writes. |
| 43 | const WRITE_BUF: usize = 8 << 20; |
| 44 | |
| 45 | /// POIs formatted per parallel geojson batch. Bounds the formatted text held at |
| 46 | /// once (~0.3 KB a line) while giving every thread plenty of chunks. |
| 47 | const GEOJSON_BATCH: usize = 1 << 18; |
| 48 | const GEOJSON_CHUNK: usize = 2048; |
| 49 | |
| 50 | #[allow(clippy::too_many_arguments)] |
| 51 | fn write_outputs( |
| 52 | pois: &[Poi], |
| 53 | geojson: &Path, |
| 54 | names: &Path, |
| 55 | index: &Path, |
| 56 | attrs: &Path, |
| 57 | spatial: &Path, |
| 58 | name_index: &Path, |
| 59 | region: &Path, |
| 60 | timer: &mut crate::timing::PhaseTimer, |
| 61 | ) -> Result<Written> { |
| 62 | // All seven files are pure functions of the Morton-sorted `pois`, and each is |
| 63 | // written by exactly one task, so running the tasks side by side cannot change a |
| 64 | // byte of any of them. They still join by record ordinal because every one of |
| 65 | // them walks the same slice in the same order — the property the single serial |
| 66 | // loop used to guarantee. |
| 67 | timer.switch("write"); |
| 68 | let (r_names, r_geojson, r_attrs, r_spatial, r_name_index, r_region) = { |
| 69 | let mut r_names = None; |
| 70 | let mut r_geojson = None; |
| 71 | let mut r_attrs = None; |
| 72 | let mut r_spatial = None; |
| 73 | let mut r_name_index = None; |
| 74 | let mut r_region = None; |
| 75 | crate::par::install(|| { |
| 76 | rayon::scope(|sc| { |
| 77 | sc.spawn(|_| r_names = Some(write_names_and_index(pois, names, index))); |
| 78 | sc.spawn(|_| r_geojson = Some(write_geojson(pois, geojson))); |
| 79 | sc.spawn(|_| r_attrs = Some(write_attrs(pois, attrs))); |
| 80 | sc.spawn(|_| { |
| 81 | r_spatial = Some(write_with(spatial, |out| { |
| 82 | let coords: Vec<(i32, i32)> = |
| 83 | pois.iter().map(|p| (p.lat_e7, p.lon_e7)).collect(); |
| 84 | poi_side::write_spatial(out, &coords) |
| 85 | })) |
| 86 | }); |
| 87 | sc.spawn(|_| { |
| 88 | r_name_index = Some(write_with(name_index, |out| { |
| 89 | let name_slices: Vec<&[u8]> = pois.iter().map(|p| p.name.as_slice()).collect(); |
| 90 | poi_side::write_name_index(out, &name_slices) |
| 91 | })) |
| 92 | }); |
| 93 | sc.spawn(|_| { |
| 94 | r_region = Some(write_with(region, |out| { |
| 95 | let region_ids: Vec<u64> = pois.iter().map(|p| p.region).collect(); |
| 96 | poi_side::write_region(out, ®ion_ids) |
| 97 | })) |
| 98 | }); |
| 99 | }) |
| 100 | }); |
| 101 | let done = "every write task ran"; |
| 102 | ( |
| 103 | r_names.expect(done), |
| 104 | r_geojson.expect(done), |
| 105 | r_attrs.expect(done), |
| 106 | r_spatial.expect(done), |
| 107 | r_name_index.expect(done), |
| 108 | r_region.expect(done), |
| 109 | ) |
| 110 | }; |
| 111 | // Errors surface in the order the serial writer would have hit them. |
| 112 | let (unique, bytes) = r_names?; |
| 113 | r_geojson?; |
| 114 | let attr_pool = r_attrs?; |
| 115 | let spatial_cells = r_spatial?; |
| 116 | let name_entries = r_name_index?; |
| 117 | r_region?; |
| 118 | |
| 119 | println!( |
| 120 | "Wrote {} record(s), {unique} unique name(s), {bytes} name byte(s)", |
| 121 | pois.len() |
| 122 | ); |
| 123 | println!( |
| 124 | "Wrote {} POI(s) with attributes, {} unique record(s), {} sidecar byte(s)", |
| 125 | attr_pool.with_attrs(), |
| 126 | attr_pool.unique_count(), |
| 127 | attr_pool.total_len() |
| 128 | ); |
| 129 | println!( |
| 130 | "Wrote {spatial_cells} populated grid cell(s), {name_entries} name index entr(ies)" |
| 131 | ); |
| 132 | Ok(Written { |
| 133 | records: pois.len(), |
| 134 | unique_names: unique, |
| 135 | name_bytes: bytes, |
| 136 | with_attrs: attr_pool.with_attrs(), |
| 137 | unique_attrs: attr_pool.unique_count(), |
| 138 | attr_bytes: attr_pool.total_len(), |
| 139 | spatial_cells, |
| 140 | name_entries, |
| 141 | }) |
| 142 | } |
| 143 | |
| 144 | /// Create `path`, hand `f` a large buffered writer over it, flush. |
| 145 | fn write_with<T>(path: &Path, f: impl FnOnce(&mut BufWriter<File>) -> std::io::Result<T>) -> Result<T> { |
| 146 | let mut out = BufWriter::with_capacity(WRITE_BUF, create(path)?); |
| 147 | let v = f(&mut out).map_err(io_err)?; |
| 148 | out.flush().map_err(io_err)?; |
| 149 | Ok(v) |
| 150 | } |
| 151 | |
| 152 | /// `poi_names.bin` + `poi_index.bin`. Serial on purpose: a name's offset is the |
| 153 | /// pool size when it is first seen in record order (see `names.rs`). |
| 154 | fn write_names_and_index(pois: &[Poi], names: &Path, index: &Path) -> Result<(usize, u32)> { |
| 155 | let mut pool = NamePool::new(BufWriter::with_capacity(WRITE_BUF, create(names)?)); |
| 156 | let mut index_out = BufWriter::with_capacity(WRITE_BUF, create(index)?); |
| 157 | for p in pois { |
| 158 | let off = pool.intern(&p.name).map_err(io_err)?; |
| 159 | let mut rec = [0u8; 14]; |
| 160 | rec[0..4].copy_from_slice(&p.lat_e7.to_le_bytes()); |
| 161 | rec[4..8].copy_from_slice(&p.lon_e7.to_le_bytes()); |
| 162 | rec[8..12].copy_from_slice(&off.to_le_bytes()); |
| 163 | rec[12..14].copy_from_slice(&p.type_.to_le_bytes()); |
| 164 | index_out.write_all(&rec).map_err(io_err)?; |
| 165 | } |
| 166 | index_out.flush().map_err(io_err)?; |
| 167 | let unique = pool.unique_count(); |
| 168 | let bytes = pool.byte_len(); |
| 169 | pool.finish().map_err(io_err)?; |
| 170 | Ok((unique, bytes)) |
| 171 | } |
| 172 | |
| 173 | /// The geojsonseq, formatted in parallel batches and written in record order. |
| 174 | /// Each line is a function of its own POI only, so the bytes are the serial |
| 175 | /// loop's. |
| 176 | fn write_geojson(pois: &[Poi], geojson: &Path) -> Result<()> { |
| 177 | use rayon::prelude::*; |
| 178 | let mut out = BufWriter::with_capacity(WRITE_BUF, create(geojson)?); |
| 179 | for batch in pois.chunks(GEOJSON_BATCH) { |
| 180 | let texts: Vec<Vec<u8>> = batch |
| 181 | .par_chunks(GEOJSON_CHUNK) |
| 182 | .map(|chunk| { |
| 183 | let mut buf: Vec<u8> = Vec::with_capacity(chunk.len() * 192); |
| 184 | for p in chunk { |
| 185 | geojson_line(p, &mut buf); |
| 186 | } |
| 187 | buf |
| 188 | }) |
| 189 | .collect(); |
| 190 | for t in &texts { |
| 191 | out.write_all(t).map_err(io_err)?; |
| 192 | } |
| 193 | } |
| 194 | out.flush().map_err(io_err) |
| 195 | } |
| 196 | |
| 197 | /// One geojsonseq feature line, appended to `line`. |
| 198 | fn geojson_line(p: &Poi, line: &mut Vec<u8>) { |
| 199 | // Writes into a Vec cannot fail. |
| 200 | let _ = write!( |
| 201 | line, |
| 202 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"", |
| 203 | p.lon, p.lat |
| 204 | ); |
| 205 | json_escape(&p.name, line); |
| 206 | let _ = writeln!(line, "\",\"type\":{},\"osm_id\":{}}}}}", p.type_, p.osm_id); |
| 207 | } |
| 208 | |
| 209 | /// `poi_attrs.bin`, deduplicated in record order (offsets are first-seen). |
| 210 | fn write_attrs(pois: &[Poi], attrs: &Path) -> Result<AttrPool> { |
| 211 | let mut attr_pool = AttrPool::new(); |
| 212 | for p in pois { |
| 213 | attr_pool.push(&p.attrs).map_err(io_err)?; |
| 214 | } |
| 215 | write_with(attrs, |out| attr_pool.write(out))?; |
| 216 | Ok(attr_pool) |
| 217 | } |
| 218 | |
| 219 | fn create(path: &Path) -> Result<File> { |
| 220 | File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) |
| 221 | } |
| 222 | |
| 223 | fn io_err(e: std::io::Error) -> Error { |
| 224 | Error(e.to_string()) |
| 225 | } |
| 226 | |
| 227 | pub struct Args { |
| 228 | pub input: PathBuf, |
| 229 | pub geojson: PathBuf, |
| 230 | pub names: PathBuf, |
| 231 | pub index: PathBuf, |
| 232 | pub attrs: PathBuf, |
| 233 | pub spatial: PathBuf, |
| 234 | pub name_index: PathBuf, |
| 235 | /// Tagged boundary ids per POI ordinal. Defaults beside `--index`. |
| 236 | pub region: PathBuf, |
| 237 | /// Region bbox filter. `None` (world) keeps everything. |
| 238 | pub bbox: Option<crate::bbox::BBox>, |
| 239 | /// `None` leaves the pool at whatever `par::threads()` decides. |
| 240 | pub threads: Option<usize>, |
| 241 | /// Review table merged into the attribute sidecar (`--reviews FILE`). |
| 242 | pub reviews: Option<PathBuf>, |
| 243 | } |
| 244 | |
| 245 | /// `poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE [--attrs FILE]` |
| 246 | /// `[--spatial FILE] [--name-index FILE] [--reviews FILE] [--region california|na|world] [--threads N]` |
| 247 | /// |
| 248 | /// The optional outputs default to their conventional names beside `--index`, so a |
| 249 | /// caller that predates any of them keeps working and still emits them. Making them |
| 250 | /// required would break build_pois_layer.sh and build_all.* on the same commit. |
| 251 | pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { |
| 252 | let mut input: Option<PathBuf> = None; |
| 253 | let mut geojson: Option<PathBuf> = None; |
| 254 | let mut names: Option<PathBuf> = None; |
| 255 | let mut index: Option<PathBuf> = None; |
| 256 | let mut attrs: Option<PathBuf> = None; |
| 257 | let mut spatial: Option<PathBuf> = None; |
| 258 | let mut name_index: Option<PathBuf> = None; |
| 259 | let mut region: Option<crate::region::Region> = None; |
| 260 | let mut threads: Option<usize> = None; |
| 261 | let mut reviews: Option<PathBuf> = None; |
| 262 | let mut i = 0; |
| 263 | while i < args.len() { |
| 264 | match args[i].as_str() { |
| 265 | "--threads" => { |
| 266 | i += 1; |
| 267 | let value = args |
| 268 | .get(i) |
| 269 | .ok_or_else(|| "--threads needs a value".to_string())?; |
| 270 | threads = Some(crate::par::parse_threads(value)?); |
| 271 | } |
| 272 | "--region" => { |
| 273 | i += 1; |
| 274 | let value = args |
| 275 | .get(i) |
| 276 | .ok_or_else(|| "--region needs `california`, `na` or `world`".to_string())?; |
| 277 | region = Some(crate::region::Region::parse(value).map_err(|e| e.0)?); |
| 278 | } |
| 279 | flag @ ("--geojson" | "--names" | "--index" | "--attrs" | "--spatial" |
| 280 | | "--name-index" | "--reviews") => { |
| 281 | let flag = flag.to_string(); |
| 282 | i += 1; |
| 283 | let value = args |
| 284 | .get(i) |
| 285 | .map(PathBuf::from) |
| 286 | .ok_or_else(|| format!("{flag} needs a value"))?; |
| 287 | match flag.as_str() { |
| 288 | "--geojson" => geojson = Some(value), |
| 289 | "--names" => names = Some(value), |
| 290 | "--attrs" => attrs = Some(value), |
| 291 | "--spatial" => spatial = Some(value), |
| 292 | "--name-index" => name_index = Some(value), |
| 293 | "--reviews" => reviews = Some(value), |
| 294 | _ => index = Some(value), |
| 295 | } |
| 296 | } |
| 297 | a if a.starts_with('-') => return Err(format!("unknown option: {a}")), |
| 298 | a => { |
| 299 | if input.is_some() { |
| 300 | return Err(format!("unexpected extra argument: {a}")); |
| 301 | } |
| 302 | input = Some(PathBuf::from(a)); |
| 303 | } |
| 304 | } |
| 305 | i += 1; |
| 306 | } |
| 307 | // Resolved in the order the usage line lists them, so a bare `in.pbf` still |
| 308 | // complains about the first thing it is missing. |
| 309 | let input = input.ok_or_else(|| "missing IN.osm.pbf".to_string())?; |
| 310 | let geojson = geojson.ok_or_else(|| "--geojson is required".to_string())?; |
| 311 | let names = names.ok_or_else(|| "--names is required".to_string())?; |
| 312 | let index = index.ok_or_else(|| "--index is required".to_string())?; |
| 313 | let attrs = attrs.unwrap_or_else(|| index.with_file_name("poi_attrs.bin")); |
| 314 | let spatial = spatial.unwrap_or_else(|| index.with_file_name("poi_spatial.bin")); |
| 315 | let name_index = name_index.unwrap_or_else(|| index.with_file_name("poi_name_index.bin")); |
| 316 | let region_ids = index.with_file_name("poi_region.bin"); |
| 317 | Ok(Args { |
| 318 | input, |
| 319 | geojson, |
| 320 | names, |
| 321 | index, |
| 322 | attrs, |
| 323 | spatial, |
| 324 | name_index, |
| 325 | region: region_ids, |
| 326 | bbox: region.and_then(|r| r.bbox()), |
| 327 | threads, |
| 328 | reviews, |
| 329 | }) |
| 330 | } |