Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part2.rs
graph_build_part2.rs485 lines · 17.4 KiBRaw
| 1 | /// The planet path: a byte of degree per node and a positional walk over each |
| 2 | /// way's refs. See [`crate::chains`] for what it costs and what it buys. |
| 3 | #[allow(clippy::too_many_arguments)] |
| 4 | fn collapse_within_ways<W: std::io::Write + Send>( |
| 5 | input: &Path, |
| 6 | spill_dir: &Path, |
| 7 | spill_pts_dir: &Path, |
| 8 | blobs: &[pbf::BlobLoc], |
| 9 | blob_kinds: &[u8], |
| 10 | index: &NodeIndex, |
| 11 | coords: &[geom::Pt], |
| 12 | stop: &Bitset, |
| 13 | slots: u32, |
| 14 | filter: RegionFilter, |
| 15 | pool: &mut NamePool<W>, |
| 16 | timer: &mut crate::timing::PhaseTimer, |
| 17 | ) -> Result<Collapsed> { |
| 18 | timer.switch("collapse-degrees"); |
| 19 | let degree = chains::count_degrees(input, blobs, blob_kinds, index, slots, filter)?; |
| 20 | let spill = chains::Spill::split(spill_dir, spill_pts_dir); |
| 21 | timer.switch("collapse-chains"); |
| 22 | let built = chains::build( |
| 23 | input, blobs, blob_kinds, index, coords, °ree, stop, slots, filter, pool, &spill, |
| 24 | )?; |
| 25 | report_way_blobs(blobs.len(), &built.kinds); |
| 26 | |
| 27 | let mut kept = Bitset::new(u64::from(slots)); |
| 28 | let mut prog = crate::progress::Progress::new("Selecting kept nodes", u64::from(slots)); |
| 29 | for i in 0..slots { |
| 30 | if index.present.get(u64::from(i)) && chains::survives(&built.endpoints, °ree, stop, i) { |
| 31 | kept.set(u64::from(i)); |
| 32 | } |
| 33 | prog.inc(); |
| 34 | } |
| 35 | prog.finish(); |
| 36 | drop(degree); |
| 37 | |
| 38 | let count = spill.chain_count()?; |
| 39 | if count != built.chain_count { |
| 40 | return Err(Error(format!( |
| 41 | "the chain pass streamed {} chain(s) but chains.hdr holds {count}", |
| 42 | built.chain_count |
| 43 | ))); |
| 44 | } |
| 45 | |
| 46 | Ok(Collapsed { |
| 47 | spill, |
| 48 | kept, |
| 49 | lane_pool: built.lanes, |
| 50 | chain_count: count, |
| 51 | splits: built.splits, |
| 52 | raw_edge_count: built.raw_edge_count, |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | /// The load-bearing measurement for re-reading the way blobs rather than caching |
| 57 | /// them: if a ways-only pass had to touch most blobs, the cache would have been |
| 58 | /// the cheaper of the two. |
| 59 | fn report_way_blobs(total: usize, kinds: &[u8]) { |
| 60 | let read = kinds.iter().filter(|k| *k & KIND_WAYS != 0).count(); |
| 61 | println!( |
| 62 | "The ways pass read {read} of {total} blob(s) ({:.1}%)", |
| 63 | read as f64 * 100.0 / total.max(1) as f64 |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | /// Refuse a lane pool whose offsets would no longer fit a `u32`. |
| 68 | /// |
| 69 | /// Same failure mode as the counts above and one step worse: a rebased offset that |
| 70 | /// wrapped onto [`NO_LANES`] reads back as "this edge has no lane data", so real |
| 71 | /// turn lanes would disappear from a build that reported success. |
| 72 | pub(crate) fn cap_lane_pool(len: usize) -> Result<()> { |
| 73 | if len as u64 >= u64::from(NO_LANES) { |
| 74 | return Err(Error(format!( |
| 75 | "the lane pool reached {len} mask(s), past the {NO_LANES} an offset can address" |
| 76 | ))); |
| 77 | } |
| 78 | Ok(()) |
| 79 | } |
| 80 | |
| 81 | /// Refuse a count that no longer fits the `u32` ids the build and the on-disk |
| 82 | /// format are built on. |
| 83 | /// |
| 84 | /// Every one of these is a silent truncation rather than a crash: a `u32` node id |
| 85 | /// or chain id that wrapped would address a real but wrong record, so the build |
| 86 | /// would succeed and the graph would be quietly wrong. The ceilings are ~2.5x |
| 87 | /// away at planet scale, which is close enough to be worth naming. |
| 88 | fn cap_u32(what: &str, n: u64) -> Result<u32> { |
| 89 | u32::try_from(n).map_err(|_| { |
| 90 | Error(format!( |
| 91 | "{n} {what}(s) is past the {} this format can address", |
| 92 | u32::MAX |
| 93 | )) |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | /// Dense id -> final (Morton) id, for the nodes that survived. |
| 98 | /// |
| 99 | /// Indexed by rank over the surviving-node bitset rather than by dense id, so it |
| 100 | /// costs four bytes per *survivor* instead of four per marked id — a difference of |
| 101 | /// tens of gigabytes at planet scale, since the marked set includes every node any |
| 102 | /// routable way ever mentions. |
| 103 | struct FinalIds<'a> { |
| 104 | kept: &'a Bitset, |
| 105 | of_kept: &'a [u32], |
| 106 | } |
| 107 | |
| 108 | impl FinalIds<'_> { |
| 109 | #[inline] |
| 110 | fn get(&self, dense: u32) -> u32 { |
| 111 | self.of_kept[self.kept.dense(u64::from(dense)) as usize] |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | /// Out-edges per surviving node, as a CSR in final id space. |
| 116 | /// |
| 117 | /// Built by two sequential scans of the chain spill, and it pays for itself three |
| 118 | /// times over: [`twin_is_unique`] becomes a binary search in one node's group |
| 119 | /// rather than in the whole edge array, the component scan walks it instead of a |
| 120 | /// materialised edge array — which is what makes that scan affordable at all — and |
| 121 | /// each write round takes its expected edge count straight out of `edge_ptr`. |
| 122 | struct Csr { |
| 123 | /// Directed edges before node `v`'s group. Length is `kept_count + 1`. |
| 124 | edge_ptr: Vec<u64>, |
| 125 | /// Each group's targets, ascending. |
| 126 | targets: Vec<u32>, |
| 127 | } |
| 128 | |
| 129 | impl Csr { |
| 130 | #[inline] |
| 131 | fn out(&self, v: u32) -> &[u32] { |
| 132 | let (a, b) = (self.edge_ptr[v as usize], self.edge_ptr[v as usize + 1]); |
| 133 | &self.targets[a as usize..b as usize] |
| 134 | } |
| 135 | |
| 136 | fn edge_count(&self) -> u64 { |
| 137 | *self.edge_ptr.last().expect("edge_ptr has a sentinel") |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// One synthetic connector reattaching an isolated transit stop. |
| 142 | /// |
| 143 | /// Kept apart from the CSR rather than merged into it: there are a handful of |
| 144 | /// these against billions of real edges, and inserting them would mean rebuilding |
| 145 | /// `targets` to make room. |
| 146 | #[derive(Clone, Copy)] |
| 147 | struct Synth { |
| 148 | source: u32, |
| 149 | target: u32, |
| 150 | dist_mm: u32, |
| 151 | } |
| 152 | |
| 153 | fn build_csr( |
| 154 | spill: &chains::Spill, |
| 155 | kept_count: u32, |
| 156 | ids: &FinalIds, |
| 157 | timer: &mut crate::timing::PhaseTimer, |
| 158 | ) -> Result<Csr> { |
| 159 | println!("Building the edge index over {kept_count} node(s)..."); |
| 160 | let chain_total = spill.chain_count()?; |
| 161 | let mut edge_ptr = vec![0u64; kept_count as usize + 2]; |
| 162 | let mut hdr = spill.headers()?; |
| 163 | let mut prog = crate::progress::Progress::new("Edge index: counting", chain_total); |
| 164 | while let Some(c) = hdr.next()? { |
| 165 | edge_ptr[ids.get(c.first) as usize + 1] += 1; |
| 166 | if !c.oneway { |
| 167 | edge_ptr[ids.get(c.last) as usize + 1] += 1; |
| 168 | } |
| 169 | prog.inc(); |
| 170 | } |
| 171 | prog.finish(); |
| 172 | for i in 0..=kept_count as usize { |
| 173 | edge_ptr[i + 1] += edge_ptr[i]; |
| 174 | } |
| 175 | |
| 176 | let total = edge_ptr[kept_count as usize]; |
| 177 | timer.switch("edge-index-scatter"); |
| 178 | let mut targets = vec![0u32; total as usize]; |
| 179 | let mut cursor: Vec<u64> = edge_ptr[..=kept_count as usize].to_vec(); |
| 180 | let mut hdr = spill.headers()?; |
| 181 | let mut prog = crate::progress::Progress::new("Edge index: scatter", chain_total); |
| 182 | while let Some(c) = hdr.next()? { |
| 183 | let (a, b) = (ids.get(c.first), ids.get(c.last)); |
| 184 | let slot = &mut cursor[a as usize]; |
| 185 | targets[*slot as usize] = b; |
| 186 | *slot += 1; |
| 187 | if !c.oneway { |
| 188 | let slot = &mut cursor[b as usize]; |
| 189 | targets[*slot as usize] = a; |
| 190 | *slot += 1; |
| 191 | } |
| 192 | prog.inc(); |
| 193 | } |
| 194 | prog.finish(); |
| 195 | edge_ptr.truncate(kept_count as usize + 1); |
| 196 | |
| 197 | // Per group, so `twin_is_unique` can binary-search it. Sorting the whole array |
| 198 | // would be one comparison sort over a billion elements; this is millions of |
| 199 | // sorts over a handful each. |
| 200 | // |
| 201 | // Parallelised by carving `targets` into one disjoint slice per WORKER, each |
| 202 | // covering a contiguous span of nodes, rather than one slice per group: a |
| 203 | // `&mut [u32]` is 16 bytes, and a planet graph has around a billion groups, so |
| 204 | // collecting them all would cost more memory than the graph. Sorting `u32`s has |
| 205 | // one answer, so nothing here depends on the order the work happens in. |
| 206 | let n = kept_count as usize; |
| 207 | let workers = par::threads().min(n).max(1); |
| 208 | let mut pieces: Vec<(usize, usize, &mut [u32])> = Vec::with_capacity(workers); |
| 209 | let mut rest: &mut [u32] = &mut targets; |
| 210 | let mut consumed = 0usize; |
| 211 | for w in 0..workers { |
| 212 | let lo = n * w / workers; |
| 213 | let hi = n * (w + 1) / workers; |
| 214 | let end = edge_ptr[hi] as usize; |
| 215 | let (mine, tail) = rest.split_at_mut(end - consumed); |
| 216 | pieces.push((lo, hi, mine)); |
| 217 | rest = tail; |
| 218 | consumed = end; |
| 219 | } |
| 220 | let ptr = &edge_ptr; |
| 221 | timer.switch("edge-index-sort"); |
| 222 | eprintln!("Sorting edge groups across {workers} worker(s)..."); |
| 223 | par::install(|| { |
| 224 | pieces.par_iter_mut().for_each(|(lo, hi, buf)| { |
| 225 | let base = ptr[*lo] as usize; |
| 226 | for v in *lo..*hi { |
| 227 | let (a, b) = (ptr[v] as usize - base, ptr[v + 1] as usize - base); |
| 228 | buf[a..b].sort_unstable(); |
| 229 | } |
| 230 | }); |
| 231 | }); |
| 232 | println!("{total} directed edge(s) from chains"); |
| 233 | Ok(Csr { edge_ptr, targets }) |
| 234 | } |
| 235 | |
| 236 | /// True when `target`'s edge range holds exactly one edge pointing back at |
| 237 | /// `source`. |
| 238 | /// |
| 239 | /// `graph.rs` resolves a reversed edge by scanning the target's range for the |
| 240 | /// first edge whose own target is the source, so with two parallel roads between |
| 241 | /// the same pair of nodes it could pick the wrong twin and draw the wrong |
| 242 | /// polyline. |
| 243 | /// |
| 244 | /// The synthetic connectors have to be counted too, even though they are not in |
| 245 | /// the CSR, because the reader does not know they are synthetic. In practice they |
| 246 | /// never collide — a connector runs from a component too small to be routable into |
| 247 | /// one that is, so no chain can join the same pair — but counting them makes that a |
| 248 | /// measured fact rather than an assumption, and it is a binary search in a list of |
| 249 | /// a few thousand. |
| 250 | fn twin_is_unique(csr: &Csr, synth: &[Synth], source: u32, target: u32) -> bool { |
| 251 | let group = csr.out(target); |
| 252 | let lo = group.partition_point(|t| *t < source); |
| 253 | let hi = group.partition_point(|t| *t <= source); |
| 254 | let from_synth = { |
| 255 | let key = (target, source); |
| 256 | let a = synth.partition_point(|s| (s.source, s.target) < key); |
| 257 | let b = synth.partition_point(|s| (s.source, s.target) <= key); |
| 258 | b - a |
| 259 | }; |
| 260 | hi - lo + from_synth == 1 |
| 261 | } |
| 262 | |
| 263 | fn pass1_blob( |
| 264 | state: &mut Pass1, |
| 265 | block: &pbf::PrimitiveBlock, |
| 266 | filter: RegionFilter, |
| 267 | ) -> Result<u8> { |
| 268 | let mut kinds = 0u8; |
| 269 | visit_block( |
| 270 | block, |
| 271 | KIND_NODES | KIND_WAYS, |
| 272 | &mut kinds, |
| 273 | &mut |el: Element| { |
| 274 | match el { |
| 275 | Element::Node(n) => { |
| 276 | if tags::is_stop_node( |
| 277 | n.tags.get_str("highway"), |
| 278 | n.tags.get_str("railway"), |
| 279 | n.tags.get_str("public_transport"), |
| 280 | ) { |
| 281 | // A stop outside the region never enters the graph. The |
| 282 | // node carries its own coordinates, so this is the one |
| 283 | // place the region filter can apply without a location |
| 284 | // table. |
| 285 | if crate::bbox::keep_e7(filter.as_ref(), n.lat_e7, n.lon_e7) { |
| 286 | state.stop_nodes.push(n.id); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | Element::Way(w) => { |
| 291 | if tags::get_hw_id(w.tags.get_str("highway")) != 0 { |
| 292 | state.refs.extend_from_slice(w.refs); |
| 293 | } |
| 294 | } |
| 295 | Element::Relation(_) => {} |
| 296 | } |
| 297 | Ok(()) |
| 298 | }, |
| 299 | )?; |
| 300 | Ok(kinds) |
| 301 | } |
| 302 | |
| 303 | /// Everything the graph takes from one routable way's tags. |
| 304 | pub(crate) struct WayAttrs { |
| 305 | /// Chunk-local name id, or `u32::MAX` for an unnamed way. |
| 306 | pub name: u32, |
| 307 | pub type_: u8, |
| 308 | pub speed_limit: u8, |
| 309 | pub oneway: bool, |
| 310 | pub fwd_lane_off: u32, |
| 311 | pub fwd_lane_count: u16, |
| 312 | pub bwd_lane_off: u32, |
| 313 | pub bwd_lane_count: u16, |
| 314 | } |
| 315 | |
| 316 | fn way_blob( |
| 317 | state: &mut WayPass, |
| 318 | block: &pbf::PrimitiveBlock, |
| 319 | index: &NodeIndex, |
| 320 | coords: &[geom::Pt], |
| 321 | filter: RegionFilter, |
| 322 | ) -> Result<u8> { |
| 323 | let mut kinds = 0u8; |
| 324 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| { |
| 325 | let Element::Way(w) = el else { |
| 326 | return Ok(()); |
| 327 | }; |
| 328 | let type_ = tags::get_hw_id(w.tags.get_str("highway")); |
| 329 | if type_ == 0 { |
| 330 | return Ok(()); |
| 331 | } |
| 332 | // Region filter: keep the way when ANY node touches the box (the |
| 333 | // `complete_ways` rule — truncating at the boundary would invent a |
| 334 | // vertex). Coordinates are resolved by now, so this is a direct test. |
| 335 | if let Some(b) = filter.as_ref() { |
| 336 | let mut touches = false; |
| 337 | for r in w.refs { |
| 338 | if let Some(d) = index.dense(*r) { |
| 339 | let (lat_e7, lon_e7) = coords[d as usize]; |
| 340 | if b.contains_e7(lat_e7, lon_e7) { |
| 341 | touches = true; |
| 342 | break; |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | if !touches { |
| 347 | return Ok(()); |
| 348 | } |
| 349 | } |
| 350 | let attrs = way_attrs(&w, type_, &mut state.lanes, &mut state.names); |
| 351 | for pair in w.refs.windows(2) { |
| 352 | // The same predicate the within-way path uses, so the two collapse |
| 353 | // paths agree on what a segment is. Asking a different question here |
| 354 | // would make the reference path emit a zero-length self-loop for a |
| 355 | // repeated ref, and the byte-identity comparison between the two would |
| 356 | // stop meaning anything. |
| 357 | let Some((u, v)) = chains::segment(index, pair[0], pair[1]) else { |
| 358 | continue; |
| 359 | }; |
| 360 | let (a, b) = (coords[u as usize], coords[v as usize]); |
| 361 | state.segs.push(Seg { |
| 362 | u, |
| 363 | v, |
| 364 | dist_mm: accurate_dist_mm(a.0, a.1, b.0, b.1), |
| 365 | name_offset: attrs.name, |
| 366 | type_: attrs.type_, |
| 367 | speed_limit: attrs.speed_limit, |
| 368 | oneway: attrs.oneway, |
| 369 | fwd_lane_off: attrs.fwd_lane_off, |
| 370 | fwd_lane_count: attrs.fwd_lane_count, |
| 371 | bwd_lane_off: attrs.bwd_lane_off, |
| 372 | bwd_lane_count: attrs.bwd_lane_count, |
| 373 | }); |
| 374 | } |
| 375 | Ok(()) |
| 376 | })?; |
| 377 | Ok(kinds) |
| 378 | } |
| 379 | |
| 380 | /// Lane masks are pushed into `lanes` and the name interned into `names`, both |
| 381 | /// chunk-local: the sink rebases the offsets when it folds the chunk in. |
| 382 | pub(crate) fn way_attrs( |
| 383 | w: &crate::osm::WayView, |
| 384 | type_: u8, |
| 385 | lanes: &mut Vec<u16>, |
| 386 | names: &mut LocalNames, |
| 387 | ) -> WayAttrs { |
| 388 | let name = match w.tags.get("name") { |
| 389 | Some(n) => names.id(n), |
| 390 | None => u32::MAX, |
| 391 | }; |
| 392 | let speed_limit = tags::parse_maxspeed(w.tags.get_str("maxspeed")); |
| 393 | let oneway = w.tags.get_str("oneway") == Some("yes"); |
| 394 | |
| 395 | // Forward lanes come from turn:lanes:forward, or from plain turn:lanes on a |
| 396 | // oneway; backward from turn:lanes:backward. Plain `lanes*` only refine the |
| 397 | // count. No turn:lanes at all means no lane data, and the router infers lanes |
| 398 | // from junction topology instead. |
| 399 | let tl = w.tags.get_str("turn:lanes"); |
| 400 | let tlf = w.tags.get_str("turn:lanes:forward"); |
| 401 | let tlb = w.tags.get_str("turn:lanes:backward"); |
| 402 | let count_all = tags::parse_int_tag(w.tags.get_str("lanes")); |
| 403 | let count_fwd = tags::parse_int_tag(w.tags.get_str("lanes:forward")); |
| 404 | let count_bwd = tags::parse_int_tag(w.tags.get_str("lanes:backward")); |
| 405 | |
| 406 | let fwd_spec = tlf.or(if oneway { tl } else { None }); |
| 407 | let fwd_hint = if count_fwd > 0 { |
| 408 | count_fwd |
| 409 | } else if oneway { |
| 410 | count_all |
| 411 | } else { |
| 412 | 0 |
| 413 | }; |
| 414 | let bwd_spec = if oneway { None } else { tlb }; |
| 415 | let fwd = tags::build_dir_lanes(fwd_spec, fwd_hint); |
| 416 | let bwd = tags::build_dir_lanes(bwd_spec, count_bwd); |
| 417 | |
| 418 | let mut push_lanes = |masks: &[u16]| -> (u32, u16) { |
| 419 | if masks.is_empty() { |
| 420 | return (NO_LANES, 0); |
| 421 | } |
| 422 | let off = lanes.len() as u32; |
| 423 | lanes.extend_from_slice(masks); |
| 424 | (off, masks.len() as u16) |
| 425 | }; |
| 426 | let (fwd_lane_off, fwd_lane_count) = push_lanes(&fwd); |
| 427 | let (bwd_lane_off, bwd_lane_count) = push_lanes(&bwd); |
| 428 | |
| 429 | WayAttrs { |
| 430 | name, |
| 431 | type_, |
| 432 | speed_limit, |
| 433 | oneway, |
| 434 | fwd_lane_off, |
| 435 | fwd_lane_count, |
| 436 | bwd_lane_off, |
| 437 | bwd_lane_count, |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | fn pass2_blob(state: &mut Pass2, block: &pbf::PrimitiveBlock, mask: &Bitset) -> Result<u8> { |
| 442 | let mut kinds = 0u8; |
| 443 | visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| { |
| 444 | if let Element::Node(n) = el { |
| 445 | if n.id < 0 || n.id as u64 >= BITSET_SIZE || !mask.get(n.id as u64) { |
| 446 | return Ok(()); |
| 447 | } |
| 448 | let dense = mask.dense(n.id as u64); |
| 449 | // A `gtfs:stop_code:<feed>` tag means this node is a matched GTFS |
| 450 | // stop; its `name` (or the code itself) becomes the stop label the |
| 451 | // transit planner shows. Otherwise fall back to the plain OSM stop |
| 452 | // tags. |
| 453 | let gtfs_code = n |
| 454 | .tags |
| 455 | .iter() |
| 456 | .find(|(k, _)| k.starts_with(b"gtfs:stop_code:")) |
| 457 | .map(|(_, v)| n.tags.get("name").unwrap_or(v)); |
| 458 | let stop_code = match gtfs_code { |
| 459 | Some(code) => Some(code), |
| 460 | None => tags::is_stop_node( |
| 461 | n.tags.get_str("highway"), |
| 462 | n.tags.get_str("railway"), |
| 463 | n.tags.get_str("public_transport"), |
| 464 | ) |
| 465 | .then(|| n.tags.get("name").unwrap_or(UNNAMED_STOP)), |
| 466 | }; |
| 467 | state.locs.push((dense, n.lat_e7, n.lon_e7)); |
| 468 | if let Some(code) = stop_code { |
| 469 | state.stops.push((dense, code.to_vec())); |
| 470 | } |
| 471 | } |
| 472 | Ok(()) |
| 473 | })?; |
| 474 | Ok(kinds) |
| 475 | } |
| 476 | |
| 477 | /// What one stop-reconnection pass did, for [`Stats`] and for the log line that |
| 478 | /// makes [`MIN_ROUTABLE_COMPONENT`] auditable. |
| 479 | struct Reconnected { |
| 480 | lcc_size: u64, |
| 481 | /// Bidirectional connectors, sorted by `(source, target)`. |
| 482 | synth: Vec<Synth>, |
| 483 | already_connected: usize, |
| 484 | unreachable: usize, |
| 485 | } |