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.rs379 lines · 14.2 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, coords, 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 | // One byte of `kept` (eight nodes) per item, on the pool: each byte is a |
| 28 | // pure function of its own nodes, so the split cannot show. |
| 29 | let mut kept = Bitset::new(u64::from(slots)); |
| 30 | { |
| 31 | let n = u64::from(slots); |
| 32 | let present = &index.present; |
| 33 | let ends = &built.endpoints; |
| 34 | let degree = °ree; |
| 35 | par::install(|| { |
| 36 | kept.bits.par_chunks_mut(1 << 16).enumerate().for_each(|(ci, chunk)| { |
| 37 | for (j, byte) in chunk.iter_mut().enumerate() { |
| 38 | let base = (((ci << 16) + j) as u64) * 8; |
| 39 | let mut v = 0u8; |
| 40 | for k in 0..8u64 { |
| 41 | let i = base + k; |
| 42 | if i < n && present.get(i) && chains::survives(ends, degree, stop, i as u32) |
| 43 | { |
| 44 | v |= 1 << k; |
| 45 | } |
| 46 | } |
| 47 | *byte = v; |
| 48 | } |
| 49 | }); |
| 50 | }); |
| 51 | } |
| 52 | drop(degree); |
| 53 | |
| 54 | let count = spill.chain_count()?; |
| 55 | if count != built.chain_count { |
| 56 | return Err(Error(format!( |
| 57 | "the chain pass streamed {} chain(s) but chains.hdr holds {count}", |
| 58 | built.chain_count |
| 59 | ))); |
| 60 | } |
| 61 | |
| 62 | Ok(Collapsed { |
| 63 | spill, |
| 64 | kept, |
| 65 | lane_pool: built.lanes, |
| 66 | chain_count: count, |
| 67 | splits: built.splits, |
| 68 | raw_edge_count: built.raw_edge_count, |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | /// The load-bearing measurement for re-reading the way blobs rather than caching |
| 73 | /// them: if a ways-only pass had to touch most blobs, the cache would have been |
| 74 | /// the cheaper of the two. |
| 75 | fn report_way_blobs(total: usize, kinds: &[u8]) { |
| 76 | let read = kinds.iter().filter(|k| *k & KIND_WAYS != 0).count(); |
| 77 | println!( |
| 78 | "The ways pass read {read} of {total} blob(s) ({:.1}%)", |
| 79 | read as f64 * 100.0 / total.max(1) as f64 |
| 80 | ); |
| 81 | } |
| 82 | |
| 83 | /// Refuse a lane pool whose offsets would no longer fit a `u32`. |
| 84 | /// |
| 85 | /// Same failure mode as the counts above and one step worse: a rebased offset that |
| 86 | /// wrapped onto [`NO_LANES`] reads back as "this edge has no lane data", so real |
| 87 | /// turn lanes would disappear from a build that reported success. |
| 88 | pub(crate) fn cap_lane_pool(len: usize) -> Result<()> { |
| 89 | if len as u64 >= u64::from(NO_LANES) { |
| 90 | return Err(Error(format!( |
| 91 | "the lane pool reached {len} mask(s), past the {NO_LANES} an offset can address" |
| 92 | ))); |
| 93 | } |
| 94 | Ok(()) |
| 95 | } |
| 96 | |
| 97 | /// Refuse a count that no longer fits the `u32` ids the build and the on-disk |
| 98 | /// format are built on. |
| 99 | /// |
| 100 | /// Every one of these is a silent truncation rather than a crash: a `u32` node id |
| 101 | /// or chain id that wrapped would address a real but wrong record, so the build |
| 102 | /// would succeed and the graph would be quietly wrong. The ceilings are ~2.5x |
| 103 | /// away at planet scale, which is close enough to be worth naming. |
| 104 | fn cap_u32(what: &str, n: u64) -> Result<u32> { |
| 105 | u32::try_from(n).map_err(|_| { |
| 106 | Error(format!( |
| 107 | "{n} {what}(s) is past the {} this format can address", |
| 108 | u32::MAX |
| 109 | )) |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | /// Dense id -> final (Morton) id, for the nodes that survived. |
| 114 | /// |
| 115 | /// Indexed by rank over the surviving-node bitset rather than by dense id, so it |
| 116 | /// costs four bytes per *survivor* instead of four per marked id — a difference of |
| 117 | /// tens of gigabytes at planet scale, since the marked set includes every node any |
| 118 | /// routable way ever mentions. |
| 119 | struct FinalIds<'a> { |
| 120 | kept: &'a Bitset, |
| 121 | of_kept: &'a [u32], |
| 122 | } |
| 123 | |
| 124 | impl FinalIds<'_> { |
| 125 | #[inline] |
| 126 | fn get(&self, dense: u32) -> u32 { |
| 127 | self.of_kept[self.kept.dense(u64::from(dense)) as usize] |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// Out-edges per surviving node, as a CSR in final id space. |
| 132 | /// |
| 133 | /// Built by two sequential scans of the chain spill, and it pays for itself three |
| 134 | /// times over: [`twin_is_unique`] becomes a binary search in one node's group |
| 135 | /// rather than in the whole edge array, the component scan walks it instead of a |
| 136 | /// materialised edge array — which is what makes that scan affordable at all — and |
| 137 | /// each write round takes its expected edge count straight out of `edge_ptr`. |
| 138 | struct Csr { |
| 139 | /// Directed edges before node `v`'s group. Length is `kept_count + 1`. |
| 140 | edge_ptr: Vec<u64>, |
| 141 | /// Each group's targets, ascending. |
| 142 | targets: Vec<u32>, |
| 143 | } |
| 144 | |
| 145 | impl Csr { |
| 146 | #[inline] |
| 147 | fn out(&self, v: u32) -> &[u32] { |
| 148 | let (a, b) = (self.edge_ptr[v as usize], self.edge_ptr[v as usize + 1]); |
| 149 | &self.targets[a as usize..b as usize] |
| 150 | } |
| 151 | |
| 152 | fn edge_count(&self) -> u64 { |
| 153 | *self.edge_ptr.last().expect("edge_ptr has a sentinel") |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// One synthetic connector reattaching an isolated transit stop. |
| 158 | /// |
| 159 | /// Kept apart from the CSR rather than merged into it: there are a handful of |
| 160 | /// these against billions of real edges, and inserting them would mean rebuilding |
| 161 | /// `targets` to make room. |
| 162 | #[derive(Clone, Copy)] |
| 163 | struct Synth { |
| 164 | source: u32, |
| 165 | target: u32, |
| 166 | dist_mm: u32, |
| 167 | } |
| 168 | |
| 169 | fn build_csr( |
| 170 | spill: &chains::Spill, |
| 171 | kept_count: u32, |
| 172 | ids: &FinalIds, |
| 173 | timer: &mut crate::timing::PhaseTimer, |
| 174 | ) -> Result<Csr> { |
| 175 | println!("Building the edge index over {kept_count} node(s)..."); |
| 176 | let chain_total = spill.chain_count()?; |
| 177 | // Both scans run on the pool over the mapped header file. |
| 178 | // |
| 179 | // Counting is integer addition into per-node counters, so atomic |
| 180 | // increments give the same counts in any order. The scatter claims each |
| 181 | // slot with an atomic cursor, so WHERE in its group a target lands depends |
| 182 | // on scheduling — but every group is sorted right after (below), and a |
| 183 | // sorted group of `u32`s has one arrangement, so `targets` comes out |
| 184 | // identical to the serial scan's. |
| 185 | let headers = spill.headers_mapped()?; |
| 186 | if headers.len()? != chain_total { |
| 187 | return Err(Error("chains.hdr changed size under the edge index".into())); |
| 188 | } |
| 189 | let mut edge_ptr = vec![0u64; kept_count as usize + 2]; |
| 190 | { |
| 191 | let counts = atomic_u64s(&mut edge_ptr); |
| 192 | let errs: Vec<Result<()>> = par::map_ranges(chain_total as usize, 1 << 16, |r| { |
| 193 | for ci in r { |
| 194 | let c = headers.get(ci as u64)?; |
| 195 | counts[ids.get(c.first) as usize + 1].fetch_add(1, Ordering::Relaxed); |
| 196 | if !c.oneway { |
| 197 | counts[ids.get(c.last) as usize + 1].fetch_add(1, Ordering::Relaxed); |
| 198 | } |
| 199 | } |
| 200 | Ok(()) |
| 201 | }); |
| 202 | errs.into_iter().collect::<Result<Vec<()>>>()?; |
| 203 | } |
| 204 | for i in 0..=kept_count as usize { |
| 205 | edge_ptr[i + 1] += edge_ptr[i]; |
| 206 | } |
| 207 | |
| 208 | let total = edge_ptr[kept_count as usize]; |
| 209 | timer.switch("edge-index-scatter"); |
| 210 | let mut targets = vec![0u32; total as usize]; |
| 211 | { |
| 212 | let mut cursor: Vec<u64> = edge_ptr[..=kept_count as usize].to_vec(); |
| 213 | let cursor = atomic_u64s(&mut cursor); |
| 214 | let out = par::SyncPtr(targets.as_mut_ptr()); |
| 215 | let errs: Vec<Result<()>> = par::map_ranges(chain_total as usize, 1 << 16, |r| { |
| 216 | for ci in r { |
| 217 | let c = headers.get(ci as u64)?; |
| 218 | let (a, b) = (ids.get(c.first), ids.get(c.last)); |
| 219 | let slot = cursor[a as usize].fetch_add(1, Ordering::Relaxed); |
| 220 | // SAFETY: `fetch_add` hands every slot out exactly once, and the |
| 221 | // counts above bound each group's slots to its own range. |
| 222 | unsafe { out.write(slot as usize, b) }; |
| 223 | if !c.oneway { |
| 224 | let slot = cursor[b as usize].fetch_add(1, Ordering::Relaxed); |
| 225 | // SAFETY: as above. |
| 226 | unsafe { out.write(slot as usize, a) }; |
| 227 | } |
| 228 | } |
| 229 | Ok(()) |
| 230 | }); |
| 231 | errs.into_iter().collect::<Result<Vec<()>>>()?; |
| 232 | } |
| 233 | edge_ptr.truncate(kept_count as usize + 1); |
| 234 | |
| 235 | // Per group, so `twin_is_unique` can binary-search it. Sorting the whole array |
| 236 | // would be one comparison sort over a billion elements; this is millions of |
| 237 | // sorts over a handful each. |
| 238 | // |
| 239 | // Parallelised by carving `targets` into one disjoint slice per WORKER, each |
| 240 | // covering a contiguous span of nodes, rather than one slice per group: a |
| 241 | // `&mut [u32]` is 16 bytes, and a planet graph has around a billion groups, so |
| 242 | // collecting them all would cost more memory than the graph. Sorting `u32`s has |
| 243 | // one answer, so nothing here depends on the order the work happens in. |
| 244 | let n = kept_count as usize; |
| 245 | let workers = par::threads().min(n).max(1); |
| 246 | let mut pieces: Vec<(usize, usize, &mut [u32])> = Vec::with_capacity(workers); |
| 247 | let mut rest: &mut [u32] = &mut targets; |
| 248 | let mut consumed = 0usize; |
| 249 | for w in 0..workers { |
| 250 | let lo = n * w / workers; |
| 251 | let hi = n * (w + 1) / workers; |
| 252 | let end = edge_ptr[hi] as usize; |
| 253 | let (mine, tail) = rest.split_at_mut(end - consumed); |
| 254 | pieces.push((lo, hi, mine)); |
| 255 | rest = tail; |
| 256 | consumed = end; |
| 257 | } |
| 258 | let ptr = &edge_ptr; |
| 259 | timer.switch("edge-index-sort"); |
| 260 | eprintln!("Sorting edge groups across {workers} worker(s)..."); |
| 261 | par::install(|| { |
| 262 | pieces.par_iter_mut().for_each(|(lo, hi, buf)| { |
| 263 | let base = ptr[*lo] as usize; |
| 264 | for v in *lo..*hi { |
| 265 | let (a, b) = (ptr[v] as usize - base, ptr[v + 1] as usize - base); |
| 266 | buf[a..b].sort_unstable(); |
| 267 | } |
| 268 | }); |
| 269 | }); |
| 270 | println!("{total} directed edge(s) from chains"); |
| 271 | Ok(Csr { edge_ptr, targets }) |
| 272 | } |
| 273 | |
| 274 | /// A `Vec<u64>` as shared atomic counters for the length of the borrow. |
| 275 | fn atomic_u64s(v: &mut [u64]) -> &[std::sync::atomic::AtomicU64] { |
| 276 | // SAFETY: `AtomicU64` has the size and bit validity of `u64` and, on every |
| 277 | // target this tool builds for, its alignment too (asserted below); the |
| 278 | // exclusive borrow is held for the view's lifetime. |
| 279 | const _: () = assert!( |
| 280 | std::mem::align_of::<std::sync::atomic::AtomicU64>() == std::mem::align_of::<u64>() |
| 281 | ); |
| 282 | unsafe { &*(v as *mut [u64] as *const [std::sync::atomic::AtomicU64]) } |
| 283 | } |
| 284 | |
| 285 | /// True when `target`'s edge range holds exactly one edge pointing back at |
| 286 | /// `source`. |
| 287 | /// |
| 288 | /// `graph.rs` resolves a reversed edge by scanning the target's range for the |
| 289 | /// first edge whose own target is the source, so with two parallel roads between |
| 290 | /// the same pair of nodes it could pick the wrong twin and draw the wrong |
| 291 | /// polyline. |
| 292 | /// |
| 293 | /// The synthetic connectors have to be counted too, even though they are not in |
| 294 | /// the CSR, because the reader does not know they are synthetic. In practice they |
| 295 | /// never collide — a connector runs from a component too small to be routable into |
| 296 | /// one that is, so no chain can join the same pair — but counting them makes that a |
| 297 | /// measured fact rather than an assumption, and it is a binary search in a list of |
| 298 | /// a few thousand. |
| 299 | fn twin_is_unique(csr: &Csr, synth: &[Synth], source: u32, target: u32) -> bool { |
| 300 | let group = csr.out(target); |
| 301 | let lo = group.partition_point(|t| *t < source); |
| 302 | let hi = group.partition_point(|t| *t <= source); |
| 303 | let from_synth = { |
| 304 | let key = (target, source); |
| 305 | let a = synth.partition_point(|s| (s.source, s.target) < key); |
| 306 | let b = synth.partition_point(|s| (s.source, s.target) <= key); |
| 307 | b - a |
| 308 | }; |
| 309 | hi - lo + from_synth == 1 |
| 310 | } |
| 311 | |
| 312 | fn pass1_blob( |
| 313 | state: &mut Pass1, |
| 314 | block: &pbf::PrimitiveBlock, |
| 315 | filter: RegionFilter, |
| 316 | mask: &AtomicBits, |
| 317 | ) -> Result<u8> { |
| 318 | let mut kinds = 0u8; |
| 319 | let mut mark = |id: i64| { |
| 320 | if id >= 0 && (id as u64) < BITSET_SIZE { |
| 321 | if mask.set(id as u64) { |
| 322 | state.marked += 1; |
| 323 | } |
| 324 | // The rank index is sized from the largest id actually marked, |
| 325 | // not from BITSET_SIZE: indexing all 20 G nominal ids would cost |
| 326 | // 313 MB to describe blocks no node reaches. |
| 327 | state.max_id = state.max_id.max(id as u64); |
| 328 | } |
| 329 | }; |
| 330 | visit_block( |
| 331 | block, |
| 332 | KIND_NODES | KIND_WAYS, |
| 333 | &mut kinds, |
| 334 | &mut |el: Element| { |
| 335 | match el { |
| 336 | Element::Node(n) => { |
| 337 | if tags::is_stop_node( |
| 338 | n.tags.get_str("highway"), |
| 339 | n.tags.get_str("railway"), |
| 340 | n.tags.get_str("public_transport"), |
| 341 | ) { |
| 342 | // A stop outside the region never enters the graph. The |
| 343 | // node carries its own coordinates, so this is the one |
| 344 | // place the region filter can apply without a location |
| 345 | // table. |
| 346 | if crate::bbox::keep_e7(filter.as_ref(), n.lat_e7, n.lon_e7) { |
| 347 | mark(n.id); |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | Element::Way(w) => { |
| 352 | if tags::get_hw_id(w.tags.get_str("highway")) != 0 { |
| 353 | for r in w.refs { |
| 354 | mark(*r); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | Element::Relation(_) => {} |
| 359 | } |
| 360 | Ok(()) |
| 361 | }, |
| 362 | )?; |
| 363 | Ok(kinds) |
| 364 | } |
| 365 | |
| 366 | /// Everything the graph takes from one routable way's tags. |
| 367 | pub(crate) struct WayAttrs { |
| 368 | /// Chunk-local name id, or `u32::MAX` for an unnamed way. |
| 369 | pub name: u32, |
| 370 | pub type_: u8, |
| 371 | pub speed_limit: u8, |
| 372 | pub oneway: bool, |
| 373 | pub fwd_lane_off: u32, |
| 374 | pub fwd_lane_count: u16, |
| 375 | pub bwd_lane_off: u32, |
| 376 | pub bwd_lane_count: u16, |
| 377 | } |
| 378 | |
| 379 | include!("graph_build_part2_s1.rs"); |