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.rs229 lines · 8.4 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 | ) -> Poi { |
| 8 | let lat_e7 = (lat * 1e7).round() as i32; |
| 9 | let lon_e7 = (lon * 1e7).round() as i32; |
| 10 | Poi { |
| 11 | lat, |
| 12 | lon, |
| 13 | lat_e7, |
| 14 | lon_e7, |
| 15 | // Derived from the *stored* integers, not the pre-rounding f64, so the |
| 16 | // sort order matches the key a reader recomputes from `poi_index.bin`. |
| 17 | morton: spatial_from_e7(lat_e7, lon_e7), |
| 18 | type_, |
| 19 | osm_id, |
| 20 | name: name.to_vec(), |
| 21 | attrs, |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | struct Written { |
| 26 | records: usize, |
| 27 | unique_names: usize, |
| 28 | name_bytes: u32, |
| 29 | with_attrs: usize, |
| 30 | unique_attrs: usize, |
| 31 | attr_bytes: usize, |
| 32 | spatial_cells: usize, |
| 33 | name_entries: usize, |
| 34 | } |
| 35 | |
| 36 | fn write_outputs( |
| 37 | pois: &[Poi], |
| 38 | geojson: &Path, |
| 39 | names: &Path, |
| 40 | index: &Path, |
| 41 | attrs: &Path, |
| 42 | spatial: &Path, |
| 43 | name_index: &Path, |
| 44 | ) -> Result<Written> { |
| 45 | let mut pool = NamePool::new(BufWriter::new(create(names)?)); |
| 46 | let mut index_out = BufWriter::new(create(index)?); |
| 47 | let mut geojson_out = BufWriter::new(create(geojson)?); |
| 48 | // The sidecar is indexed by record ordinal, so it is filled in this same loop |
| 49 | // over the same Morton-sorted vector. Any second pass over `pois` would be an |
| 50 | // opportunity for the two files to disagree. |
| 51 | let mut attr_pool = AttrPool::new(); |
| 52 | let mut line: Vec<u8> = Vec::new(); |
| 53 | |
| 54 | for p in pois { |
| 55 | let off = pool.intern(&p.name).map_err(io_err)?; |
| 56 | index_out.write_all(&p.lat_e7.to_le_bytes()).map_err(io_err)?; |
| 57 | index_out.write_all(&p.lon_e7.to_le_bytes()).map_err(io_err)?; |
| 58 | index_out.write_all(&off.to_le_bytes()).map_err(io_err)?; |
| 59 | index_out.write_all(&p.type_.to_le_bytes()).map_err(io_err)?; |
| 60 | attr_pool.push(&p.attrs).map_err(io_err)?; |
| 61 | |
| 62 | line.clear(); |
| 63 | write!( |
| 64 | line, |
| 65 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"", |
| 66 | p.lon, p.lat |
| 67 | ) |
| 68 | .map_err(io_err)?; |
| 69 | json_escape(&p.name, &mut line); |
| 70 | writeln!(line, "\",\"type\":{},\"osm_id\":{}}}}}", p.type_, p.osm_id).map_err(io_err)?; |
| 71 | geojson_out.write_all(&line).map_err(io_err)?; |
| 72 | } |
| 73 | |
| 74 | let mut attrs_out = BufWriter::new(create(attrs)?); |
| 75 | attr_pool.write(&mut attrs_out).map_err(io_err)?; |
| 76 | attrs_out.flush().map_err(io_err)?; |
| 77 | |
| 78 | // Both side files are derived from the same Morton-sorted vector as the index, in |
| 79 | // the same function, for the same reason the sidecar is: they join by record |
| 80 | // ordinal, and any second pass over `pois` is an opportunity to disagree. |
| 81 | let coords: Vec<(i32, i32)> = pois.iter().map(|p| (p.lat_e7, p.lon_e7)).collect(); |
| 82 | let mut spatial_out = BufWriter::new(create(spatial)?); |
| 83 | let spatial_cells = poi_side::write_spatial(&mut spatial_out, &coords).map_err(io_err)?; |
| 84 | spatial_out.flush().map_err(io_err)?; |
| 85 | |
| 86 | let name_slices: Vec<&[u8]> = pois.iter().map(|p| p.name.as_slice()).collect(); |
| 87 | let mut name_index_out = BufWriter::new(create(name_index)?); |
| 88 | let name_entries = |
| 89 | poi_side::write_name_index(&mut name_index_out, &name_slices).map_err(io_err)?; |
| 90 | name_index_out.flush().map_err(io_err)?; |
| 91 | |
| 92 | index_out.flush().map_err(io_err)?; |
| 93 | geojson_out.flush().map_err(io_err)?; |
| 94 | let unique = pool.unique_count(); |
| 95 | let bytes = pool.byte_len(); |
| 96 | pool.finish().map_err(io_err)?; |
| 97 | println!( |
| 98 | "Wrote {} record(s), {unique} unique name(s), {bytes} name byte(s)", |
| 99 | pois.len() |
| 100 | ); |
| 101 | println!( |
| 102 | "Wrote {} POI(s) with attributes, {} unique record(s), {} sidecar byte(s)", |
| 103 | attr_pool.with_attrs(), |
| 104 | attr_pool.unique_count(), |
| 105 | attr_pool.total_len() |
| 106 | ); |
| 107 | println!( |
| 108 | "Wrote {spatial_cells} populated grid cell(s), {name_entries} name index entr(ies)" |
| 109 | ); |
| 110 | Ok(Written { |
| 111 | records: pois.len(), |
| 112 | unique_names: unique, |
| 113 | name_bytes: bytes, |
| 114 | with_attrs: attr_pool.with_attrs(), |
| 115 | unique_attrs: attr_pool.unique_count(), |
| 116 | attr_bytes: attr_pool.total_len(), |
| 117 | spatial_cells, |
| 118 | name_entries, |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | fn create(path: &Path) -> Result<File> { |
| 123 | File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) |
| 124 | } |
| 125 | |
| 126 | fn io_err(e: std::io::Error) -> Error { |
| 127 | Error(e.to_string()) |
| 128 | } |
| 129 | |
| 130 | pub struct Args { |
| 131 | pub input: PathBuf, |
| 132 | pub geojson: PathBuf, |
| 133 | pub names: PathBuf, |
| 134 | pub index: PathBuf, |
| 135 | pub attrs: PathBuf, |
| 136 | pub spatial: PathBuf, |
| 137 | pub name_index: PathBuf, |
| 138 | /// Region bbox filter. `None` (world) keeps everything. |
| 139 | pub bbox: Option<crate::bbox::BBox>, |
| 140 | /// `None` leaves the pool at whatever `par::threads()` decides. |
| 141 | pub threads: Option<usize>, |
| 142 | /// Review table merged into the attribute sidecar (`--reviews FILE`). |
| 143 | pub reviews: Option<PathBuf>, |
| 144 | } |
| 145 | |
| 146 | /// `poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE [--attrs FILE]` |
| 147 | /// `[--spatial FILE] [--name-index FILE] [--reviews FILE] [--region california|na|world] [--threads N]` |
| 148 | /// |
| 149 | /// The optional outputs default to their conventional names beside `--index`, so a |
| 150 | /// caller that predates any of them keeps working and still emits them. Making them |
| 151 | /// required would break build_pois_layer.sh and build_all.* on the same commit. |
| 152 | pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { |
| 153 | let mut input: Option<PathBuf> = None; |
| 154 | let mut geojson: Option<PathBuf> = None; |
| 155 | let mut names: Option<PathBuf> = None; |
| 156 | let mut index: Option<PathBuf> = None; |
| 157 | let mut attrs: Option<PathBuf> = None; |
| 158 | let mut spatial: Option<PathBuf> = None; |
| 159 | let mut name_index: Option<PathBuf> = None; |
| 160 | let mut region: Option<crate::region::Region> = None; |
| 161 | let mut threads: Option<usize> = None; |
| 162 | let mut reviews: Option<PathBuf> = None; |
| 163 | let mut i = 0; |
| 164 | while i < args.len() { |
| 165 | match args[i].as_str() { |
| 166 | "--threads" => { |
| 167 | i += 1; |
| 168 | let value = args |
| 169 | .get(i) |
| 170 | .ok_or_else(|| "--threads needs a value".to_string())?; |
| 171 | threads = Some(crate::par::parse_threads(value)?); |
| 172 | } |
| 173 | "--region" => { |
| 174 | i += 1; |
| 175 | let value = args |
| 176 | .get(i) |
| 177 | .ok_or_else(|| "--region needs `california`, `na` or `world`".to_string())?; |
| 178 | region = Some(crate::region::Region::parse(value).map_err(|e| e.0)?); |
| 179 | } |
| 180 | flag @ ("--geojson" | "--names" | "--index" | "--attrs" | "--spatial" |
| 181 | | "--name-index" | "--reviews") => { |
| 182 | let flag = flag.to_string(); |
| 183 | i += 1; |
| 184 | let value = args |
| 185 | .get(i) |
| 186 | .map(PathBuf::from) |
| 187 | .ok_or_else(|| format!("{flag} needs a value"))?; |
| 188 | match flag.as_str() { |
| 189 | "--geojson" => geojson = Some(value), |
| 190 | "--names" => names = Some(value), |
| 191 | "--attrs" => attrs = Some(value), |
| 192 | "--spatial" => spatial = Some(value), |
| 193 | "--name-index" => name_index = Some(value), |
| 194 | "--reviews" => reviews = Some(value), |
| 195 | _ => index = Some(value), |
| 196 | } |
| 197 | } |
| 198 | a if a.starts_with('-') => return Err(format!("unknown option: {a}")), |
| 199 | a => { |
| 200 | if input.is_some() { |
| 201 | return Err(format!("unexpected extra argument: {a}")); |
| 202 | } |
| 203 | input = Some(PathBuf::from(a)); |
| 204 | } |
| 205 | } |
| 206 | i += 1; |
| 207 | } |
| 208 | // Resolved in the order the usage line lists them, so a bare `in.pbf` still |
| 209 | // complains about the first thing it is missing. |
| 210 | let input = input.ok_or_else(|| "missing IN.osm.pbf".to_string())?; |
| 211 | let geojson = geojson.ok_or_else(|| "--geojson is required".to_string())?; |
| 212 | let names = names.ok_or_else(|| "--names is required".to_string())?; |
| 213 | let index = index.ok_or_else(|| "--index is required".to_string())?; |
| 214 | let attrs = attrs.unwrap_or_else(|| index.with_file_name("poi_attrs.bin")); |
| 215 | let spatial = spatial.unwrap_or_else(|| index.with_file_name("poi_spatial.bin")); |
| 216 | let name_index = name_index.unwrap_or_else(|| index.with_file_name("poi_name_index.bin")); |
| 217 | Ok(Args { |
| 218 | input, |
| 219 | geojson, |
| 220 | names, |
| 221 | index, |
| 222 | attrs, |
| 223 | spatial, |
| 224 | name_index, |
| 225 | bbox: region.and_then(|r| r.bbox()), |
| 226 | threads, |
| 227 | reviews, |
| 228 | }) |
| 229 | } |