Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part1.rs

graph_build_part1.rs500 lines · 20.3 KiBRaw
1/// The ways-only pass: one [`Seg`] per consecutive resolvable ref pair.
2///
3/// Re-reading the way blobs replaces a cache of every routable way and every one
4/// of its refs — 32 GB at planet scale — with the cost of inflating the way
5/// blobs a second time. Ways are a small minority of a planet file's blobs and
6/// `blob_kinds` lets the pass skip the rest outright, so the trade is heavily in
7/// favour of re-reading.
8#[derive(Default)]
9struct WayPass {
10 segs: Vec<Seg>,
11 lanes: Vec<u16>,
12 names: LocalNames,
13}
14
15#[derive(Default)]
16struct Pass2 {
17 /// `(dense id, lat_e7, lon_e7)`, scattered index-aligned in the sink.
18 locs: Vec<(u32, i32, i32)>,
19 /// `(dense id, stop code)`, as owned bytes. Interning is deferred until every
20 /// way name is in the pool, because a name's offset is its position in the
21 /// pool: interning a stop code early would shift every way name after it and
22 /// rewrite the whole of `road_names.bin`.
23 stops: Vec<(u32, Vec<u8>)>,
24}
25
26#[derive(Clone, Copy)]
27struct TmpEdge {
28 source: u32,
29 target: u32,
30 dist_mm: u32,
31 name_offset: u32,
32 type_: u8,
33 speed_limit: u8,
34 lane_off: u32,
35 lane_count: u16,
36 /// Chain this edge traverses, or [`NO_CHAIN`]. Only used to make the write
37 /// order total; the geometry comes from the point range below.
38 chain: u32,
39 /// True when it runs from the chain's last point to its first, so the stored
40 /// polyline has to be read backwards.
41 chain_rev: bool,
42 /// The chain's polyline in `chains.pts`. Carried here rather than looked up per
43 /// edge: the header file is 24 GB at planet scale, so seeking back into it once
44 /// per edge would be a billion cold random reads.
45 pts_start: u64,
46 pts_len: u32,
47}
48
49/// Build-time choices that change the shape of the build rather than its output
50/// contract.
51#[derive(Clone, Default)]
52pub struct Options {
53 /// Restrict chains to a single OSM way, which trades some collapsing for the
54 /// segment array and its incidence index. See [`crate::chains`].
55 pub within_way_chains: bool,
56 /// How many source-partitioned rounds to write the pack in. One round is the
57 /// whole graph at once; more rounds trade extra sequential passes over the
58 /// chain spill for a proportionally smaller edge buffer. Zero means one.
59 pub rounds: u32,
60 /// Where to put the chain spill. Defaults to the output directory.
61 ///
62 /// Worth separating because `chains.pts` is the only file the build reads
63 /// randomly — once per edge that stores a polyline — so it wants a disk whose
64 /// seeks are cheap, while the output only ever needs sequential writes and can
65 /// go wherever there is room. Putting the spill on a slow mount cost more wall
66 /// clock on California than every other stage put together.
67 pub spill_dir: Option<PathBuf>,
68 /// Where to put `chains.pts` specifically, if it should not sit beside
69 /// `chains.hdr`.
70 ///
71 /// The header is the larger file — about 24 GB against 18 GB at planet scale —
72 /// but it is only ever streamed from the front, so it can live somewhere roomy
73 /// and slow while the randomly-read points go somewhere fast and small.
74 pub spill_pts_dir: Option<PathBuf>,
75 /// Print the [`Census`] report after the build. Changes no output file.
76 pub stats: bool,
77 /// Cap on the parallel pool. `None` leaves it to [`crate::par::threads`].
78 pub threads: Option<usize>,
79 /// A `.mdem` heightmap dataset (`dem_ingest`) to bake a per-node elevation from.
80 ///
81 /// `None` omits `elevation.bin` entirely — the graph is still valid and the device reads every
82 /// node's elevation as 0 (WS-G's route profile simply comes out flat). When set, every graph
83 /// node is sampled from the DEM and its metres written to `elevation.bin`; a node off the DEM's
84 /// coverage bakes as 0.
85 pub dem: Option<PathBuf>,
86 /// Region bbox filter: keep only ways with at least one node inside.
87 ///
88 /// `None` (world) keeps everything. `Some` (california) drops every routable
89 /// way whose nodes all fall outside — the graph then covers only the region,
90 /// which is what makes a california build fast and small. Stop nodes are
91 /// filtered the same way: a stop outside the region never enters the graph.
92 pub bbox: Option<crate::bbox::BBox>,
93}
94
95impl Options {
96 fn round_count(&self) -> u32 {
97 self.rounds.max(1)
98 }
99}
100
101pub fn build(input: &Path, out_dir: &Path) -> Result<Stats> {
102 build_with(input, out_dir, Options::default())
103}
104
105pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> {
106 if let Some(n) = opts.threads {
107 crate::par::set_threads(n);
108 }
109 // The region filter is validated up front: a later stage reads `graph/`
110 // assuming it covers the same region the tiles do, and a graph built for
111 // the wrong region is a silent layer mismatch, not a loud failure.
112 if let Some(b) = &opts.bbox {
113 println!(
114 "region filter: keeping ways touching {:.3},{:.3} .. {:.3},{:.3}",
115 b.min_lon, b.min_lat, b.max_lon, b.max_lat,
116 );
117 }
118 std::fs::create_dir_all(out_dir)
119 .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?;
120
121 let mut timer = crate::timing::PhaseTimer::start("graph");
122 let blobs = pbf::scan_blobs(input)?;
123 println!("[graph] Scanned {} data blob(s) in {}", blobs.len(), input.display());
124 pbf::probe_compression(input, &blobs)?;
125
126 let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));
127
128 let mut mask = Bitset::new(BITSET_SIZE);
129 let mut marked: u64 = 0;
130 let mut max_id: u64 = 0;
131
132 timer.switch("refs-stops");
133 // --- Pass 1: which nodes the graph needs ---------------------------------
134 // Folded through a sink rather than collected, so a chunk's ref list is
135 // consumed and freed while later chunks are still decoding. Nothing about a
136 // way survives this pass: the ways pass below re-reads the way blobs, which
137 // is far cheaper than caching every routable way and every ref it holds.
138 //
139 // The region filter needs way NODE LOCATIONS, but ways arrive before their
140 // nodes in a PBF — so pass 1 cannot filter ways. It marks every routable
141 // way's refs unconditionally; the way passes below (which run after the
142 // coordinates are resolved) apply the filter when they re-read the ways.
143 // Stop nodes ARE filtered here: a node's own coordinates arrive with it.
144 let filter = opts.bbox;
145 let blob_kinds = pbf::run_pass_sink(
146 input,
147 &blobs,
148 None,
149 KIND_NODES | KIND_WAYS,
150 "Pass 1: refs + stops",
151 Pass1::default,
152 |state, block| pass1_blob(state, block, filter),
153 |chunk| {
154 for id in chunk.refs.iter().chain(chunk.stop_nodes.iter()) {
155 if *id >= 0 && (*id as u64) < BITSET_SIZE {
156 if mask.set(*id as u64) {
157 marked += 1;
158 }
159 // The rank index is sized from the largest id actually
160 // marked, not from BITSET_SIZE: indexing all 20 G nominal ids
161 // would cost 313 MB to describe blocks no node reaches.
162 max_id = max_id.max(*id as u64);
163 }
164 }
165 Ok(())
166 },
167 )?;
168 println!("{marked} graph node(s) expected");
169 // Cache the complete blob-kinds mask beside the graph so a `mamaps_build` run over the same
170 // `.pbf` can skip its own full pass-1 scan. This pass inflated every blob with `None`, so the
171 // mask is complete. Best-effort: a write failure must not fail the graph build, which never
172 // reads the sidecar itself.
173 if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blob_kinds) {
174 eprintln!("WARN: could not write blob-kinds sidecar: {e}");
175 }
176 let slots = cap_u32("marked graph node", marked)?;
177
178 // --- The rank index ------------------------------------------------------
179 // From here on a node's address is the number of marked ids below its own, so
180 // the node array is implicitly ordered by OSM id and needs to store neither
181 // the id nor a sorted side table to look it up by.
182 timer.switch("rank-index");
183 let counted = mask.build_rank(max_id);
184 if counted != marked {
185 // The mask and the running count are maintained in the same loop, so a
186 // disagreement means one of the two is wrong about which ids were set,
187 // and every address derived from the rank would be off by however many.
188 return Err(Error(format!(
189 "rank index counted {counted} marked node(s) but pass 1 set {marked}"
190 )));
191 }
192
193 // --- Pass 2: coordinates and stop codes for the marked nodes -------------
194 // Zero-initialised, so the slots belonging to dangling refs are never touched
195 // and never fault in: an untouched page of `coords` costs no real memory.
196 let mut coords: Vec<geom::Pt> = vec![(0, 0); slots as usize];
197 let mut present = Bitset::new(u64::from(slots));
198 let mut stop = Bitset::new(u64::from(slots));
199 let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new();
200 let mut node_count: u64 = 0;
201 timer.switch("node-scan");
202 let _ = pbf::run_pass_sink(
203 input,
204 &blobs,
205 Some(&blob_kinds),
206 KIND_NODES,
207 "Pass 2: node scan",
208 Pass2::default,
209 |state, block| pass2_blob(state, block, &mask),
210 |chunk| {
211 for (dense, lat_e7, lon_e7) in chunk.locs {
212 coords[dense as usize] = (lat_e7, lon_e7);
213 if present.set(u64::from(dense)) {
214 node_count += 1;
215 }
216 }
217 for (dense, code) in chunk.stops {
218 stop.set(u64::from(dense));
219 stop_codes.push((dense, code));
220 }
221 Ok(())
222 },
223 )?;
224 println!(
225 "Located {node_count} node(s); {} marked id(s) had no coordinates in the file",
226 marked - node_count
227 );
228
229 // Stop codes go into the pool only after every way name is in it, in the
230 // order pass 2 met them, so `road_names.bin` is unaffected by dense
231 // addressing and by where the way names are interned.
232 let index = NodeIndex { mask, present };
233
234 // --- Collapse ------------------------------------------------------------
235 let spill_dir = opts.spill_dir.clone().unwrap_or_else(|| out_dir.to_path_buf());
236 let spill_pts_dir = opts.spill_pts_dir.clone().unwrap_or_else(|| spill_dir.clone());
237 timer.switch("collapse");
238 let mut collapsed = if opts.within_way_chains {
239 collapse_within_ways(
240 input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,
241 slots, filter, &mut pool, &mut timer,
242 )?
243 } else {
244 collapse_segments(
245 input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,
246 slots, filter, &mut pool, &mut timer,
247 )?
248 };
249
250 let mut prog = crate::progress::Progress::new("Interning stop codes", stop_codes.len() as u64);
251 for (_, code) in &stop_codes {
252 pool.intern(code).map_err(io_err)?;
253 prog.inc();
254 }
255 prog.finish();
256 drop(stop_codes);
257 timer.switch("rank-survivors");
258
259 // `saturating_sub` because a file with no routable ways and no stop nodes
260 // marks nothing, and there is then no largest id to index up to.
261 let kept_count = cap_u32(
262 "surviving node",
263 collapsed.kept.build_rank(u64::from(slots).saturating_sub(1)),
264 )?;
265 let kept = collapsed.kept;
266 println!(
267 "Collapsed {node_count} node(s) -> {kept_count} ({} chain(s), {} split(s) for the \
268 256-point limit)",
269 collapsed.chain_count, collapsed.splits
270 );
271 cap_u32("chain", collapsed.chain_count)?;
272 let raw_edge_count = collapsed.raw_edge_count;
273
274 // --- Morton order -------------------------------------------------------
275 // Deferred to here, and applied only to the survivors, because that is the
276 // only set the device ever binary-searches. Sorting before the collapse would
277 // have meant carrying a 64-bit spatial key through every node that was about
278 // to be collapsed away.
279 timer.switch("morton-sort");
280 println!("Sorting {kept_count} surviving node(s) by spatial key...");
281 let mut keys: Vec<(u64, u32)> = Vec::with_capacity(kept_count as usize);
282 let mut prog = crate::progress::Progress::new("Morton keys", u64::from(slots));
283 for i in 0..slots {
284 if kept.get(u64::from(i)) {
285 let (lat_e7, lon_e7) = coords[i as usize];
286 keys.push((spatial_from_e7(lat_e7, lon_e7), i));
287 }
288 prog.inc();
289 }
290 prog.finish();
291 debug_assert_eq!(keys.len(), kept_count as usize);
292 // The key is `(spatial, dense)`, and the loop above pushed `dense` ascending, so
293 // this is exactly the order the previous STABLE `sort_by_key(spatial)` produced:
294 // ties there fell back to insertion order, which was ascending `dense`. Spelling
295 // the tie-break into the key makes the order total, and a total order is what lets
296 // an UNSTABLE parallel sort be substituted without changing a single final id --
297 // and final ids are what `nodes.bin`, `edges.bin` and every offset in the pack are
298 // numbered by, so this is the one comparison in the build that must not move.
299 eprintln!("Sorting {kept_count} spatial key(s)...");
300 par::install(|| keys.par_sort_unstable());
301
302 let mut final_of_kept = vec![0u32; kept_count as usize];
303 let mut node_coords: Vec<geom::Pt> = Vec::with_capacity(kept_count as usize);
304 let mut stops_final = Bitset::new(u64::from(kept_count));
305 let mut prog = crate::progress::Progress::new("Final id assignment", keys.len() as u64);
306 for (final_id, (_, dense)) in keys.iter().enumerate() {
307 final_of_kept[kept.dense(u64::from(*dense)) as usize] = final_id as u32;
308 node_coords.push(coords[*dense as usize]);
309 if stop.get(u64::from(*dense)) {
310 stops_final.set(final_id as u64);
311 }
312 prog.inc();
313 }
314 prog.finish();
315 drop(keys);
316 drop(stop);
317 // The chain spill holds coordinates, so nothing downstream needs the array
318 // indexed by *marked* node — the largest in the build — any longer.
319 drop(coords);
320 drop(index);
321 let ids = FinalIds {
322 kept: &kept,
323 of_kept: &final_of_kept,
324 };
325
326 // --- The edge index -----------------------------------------------------
327 timer.switch("edge-index");
328 let csr = build_csr(&collapsed.spill, kept_count, &ids, &mut timer)?;
329
330 // --- Reconnect isolated transit stops -----------------------------------
331 timer.switch("components");
332 let rec = reconnect_isolated_stops(&node_coords, &stops_final, &csr);
333 let synth = rec.synth;
334 drop(stops_final);
335
336 // --- Write --------------------------------------------------------------
337 // Load the optional DEM up front so a bad `--dem` path fails before the write starts. `None`
338 // leaves `elevation.bin` unwritten and every node's baked elevation at 0.
339 let dem = match &opts.dem {
340 Some(path) => Some(crate::dem::Dem::load(path)?),
341 None => None,
342 };
343 timer.switch("write");
344 let written = write_graph(
345 out_dir,
346 &node_coords,
347 &collapsed.spill,
348 &collapsed.lane_pool,
349 &csr,
350 &synth,
351 &ids,
352 opts.round_count(),
353 dem.as_ref(),
354 &mut timer,
355 )?;
356 collapsed.spill.remove();
357 let unique_names = pool.unique_count();
358 let name_bytes = pool.byte_len();
359 pool.finish().map_err(io_err)?;
360
361 timer.finish();
362 println!(
363 "Done. Nodes: {} Edges: {} intermediate.bin: {} byte(s)",
364 kept_count, written.edge_count, written.intermediate_bytes
365 );
366 Ok(Stats {
367 node_count: u64::from(kept_count),
368 edge_count: written.edge_count,
369 unique_names,
370 name_bytes,
371 lcc_size: rec.lcc_size,
372 stops_already_connected: rec.already_connected,
373 reconnected_stops: synth.len() / 2,
374 stops_unreachable: rec.unreachable,
375 raw_node_count: node_count,
376 raw_edge_count,
377 chain_splits: collapsed.splits,
378 geometry_edges: written.geometry_edges,
379 reversed_edges: written.reversed_edges,
380 intermediate_bytes: written.intermediate_bytes,
381 edges_bytes: written.edges_bytes,
382 escape_count: written.escape_count,
383 named_edges: written.named_edges,
384 census: written.census,
385 })
386}
387
388/// What either collapse strategy hands the writer.
389///
390/// Both produce the same thing — a chain spill plus the set of nodes that survive
391/// — and differ only in how much memory it costs to get there and whether a chain
392/// may cross from one OSM way into the next.
393///
394/// The chains are always on disk, even for the reference path that had them in
395/// memory anyway, so that there is one writer. That also means `coords` — the
396/// largest array in the build, and the only one indexed by *marked* rather than
397/// surviving node — can be freed before the writer runs.
398struct Collapsed {
399 spill: chains::Spill,
400 /// Dense ids that survive as graph nodes.
401 kept: Bitset,
402 lane_pool: Vec<u16>,
403 chain_count: u64,
404 splits: usize,
405 raw_edge_count: u64,
406}
407
408/// The reference path: build every segment, then collapse chains across way
409/// boundaries with [`compact`].
410///
411/// Kept as the baseline the within-way path is measured against. Its cost is the
412/// segment array and the incidence CSR over it, which together are the reason a
413/// planet build does not fit.
414#[allow(clippy::too_many_arguments)]
415fn collapse_segments<W: std::io::Write + Send>(
416 input: &Path,
417 spill_dir: &Path,
418 spill_pts_dir: &Path,
419 blobs: &[pbf::BlobLoc],
420 blob_kinds: &[u8],
421 index: &NodeIndex,
422 coords: &[geom::Pt],
423 stop: &Bitset,
424 slots: u32,
425 filter: RegionFilter,
426 pool: &mut NamePool<W>,
427 timer: &mut crate::timing::PhaseTimer,
428) -> Result<Collapsed> {
429 timer.switch("collapse-segments");
430 // One record per consecutive way-node pair, still carrying both directions'
431 // lane data. Splitting into directed edges is deferred until after
432 // compaction, because pairing a `u -> v` edge with its `v -> u` twin is only
433 // unambiguous while they are still one object.
434 let mut segs: Vec<Seg> = Vec::new();
435 let mut lane_pool: Vec<u16> = Vec::new();
436 let way_kinds = pbf::run_pass_sink(
437 input,
438 blobs,
439 Some(blob_kinds),
440 KIND_WAYS,
441 "Pass 3: segments",
442 WayPass::default,
443 |state, block| way_blob(state, block, index, coords, filter),
444 |chunk| {
445 let name_map = chunk.names.flush(pool).map_err(io_err)?;
446 let lane_base = lane_pool.len() as u32;
447 lane_pool.extend_from_slice(&chunk.lanes);
448 cap_lane_pool(lane_pool.len())?;
449 segs.reserve(chunk.segs.len());
450 for mut s in chunk.segs {
451 s.name_offset = if s.name_offset == u32::MAX {
452 NO_NAME
453 } else {
454 name_map[s.name_offset as usize]
455 };
456 if s.fwd_lane_count > 0 {
457 s.fwd_lane_off += lane_base;
458 }
459 if s.bwd_lane_count > 0 {
460 s.bwd_lane_off += lane_base;
461 }
462 segs.push(s);
463 }
464 Ok(())
465 },
466 )?;
467 report_way_blobs(blobs.len(), &way_kinds);
468
469 let raw_edge_count: u64 = segs.iter().map(|s| if s.oneway { 1u64 } else { 2 }).sum();
470 println!(
471 "Built {} segment(s) ({raw_edge_count} directed edge(s) before compaction)",
472 segs.len()
473 );
474
475 timer.switch("collapse-compact");
476 let comp = compact::compact(slots, &segs, &lane_pool, |n| coords[n as usize], |n| {
477 stop.get(u64::from(n))
478 });
479 drop(segs);
480
481 // A slot with no coordinates has no segments either, so compaction has no
482 // reason to collapse it and would hand it a real node id. Filter it out here
483 // instead: this is the second half of the dangling-reference guard.
484 let mut kept = Bitset::new(u64::from(slots));
485 for i in 0..slots {
486 if comp.new_id[i as usize] != REMOVED && index.present.get(u64::from(i)) {
487 kept.set(u64::from(i));
488 }
489 }
490 let spill = chains::Spill::split(spill_dir, spill_pts_dir);
491 spill.write(&comp.chains, &comp.pts, coords)?;
492 Ok(Collapsed {
493 spill,
494 kept,
495 lane_pool,
496 chain_count: comp.chains.len() as u64,
497 splits: comp.splits,
498 raw_edge_count,
499 })
500}