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

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

graph_build_part1_s1.rs392 lines · 16.9 KiBRaw
1pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> {
2 if let Some(n) = opts.threads {
3 crate::par::set_threads(n);
4 }
5 // The region filter is validated up front: a later stage reads `graph/`
6 // assuming it covers the same region the tiles do, and a graph built for
7 // the wrong region is a silent layer mismatch, not a loud failure.
8 if let Some(b) = &opts.bbox {
9 println!(
10 "region filter: keeping ways touching {:.3},{:.3} .. {:.3},{:.3}",
11 b.min_lon, b.min_lat, b.max_lon, b.max_lat,
12 );
13 }
14 std::fs::create_dir_all(out_dir)
15 .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?;
16
17 let mut timer = crate::timing::PhaseTimer::start("graph");
18 let blobs = pbf::scan_blobs(input)?;
19 println!("[graph] Scanned {} data blob(s) in {}", blobs.len(), input.display());
20 pbf::probe_compression(input, &blobs)?;
21
22 let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));
23
24 let mut mask = Bitset::new(BITSET_SIZE);
25 let mut marked: u64 = 0;
26 let mut max_id: u64 = 0;
27
28 timer.switch("refs-stops");
29 // --- Pass 1: which nodes the graph needs ---------------------------------
30 // Folded through a sink rather than collected, so a chunk's ref list is
31 // consumed and freed while later chunks are still decoding. Nothing about a
32 // way survives this pass: the ways pass below re-reads the way blobs, which
33 // is far cheaper than caching every routable way and every ref it holds.
34 //
35 // The region filter needs way NODE LOCATIONS, but ways arrive before their
36 // nodes in a PBF — so pass 1 cannot filter ways. It marks every routable
37 // way's refs unconditionally; the way passes below (which run after the
38 // coordinates are resolved) apply the filter when they re-read the ways.
39 // Stop nodes ARE filtered here: a node's own coordinates arrive with it.
40 let filter = opts.bbox;
41 let blob_kinds = {
42 let bits = mask.atomic();
43 pbf::run_pass_sink(
44 input,
45 &blobs,
46 pbf::PassSpec { blob_kinds: None, want: KIND_NODES | KIND_WAYS, label: "Pass 1: refs + stops" },
47 Pass1::default,
48 |state, block| pass1_blob(state, block, filter, &bits),
49 |chunk| {
50 marked += chunk.marked;
51 max_id = max_id.max(chunk.max_id);
52 Ok(())
53 },
54 )?
55 };
56 println!("{marked} graph node(s) expected");
57 // Cache the complete blob-kinds mask beside the graph so a `mamaps_build` run over the same
58 // `.pbf` can skip its own full pass-1 scan. This pass inflated every blob with `None`, so the
59 // mask is complete. Best-effort: a write failure must not fail the graph build, which never
60 // reads the sidecar itself.
61 if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blobs, &blob_kinds) {
62 eprintln!("WARN: could not write blob-kinds sidecar: {e}");
63 }
64 let slots = cap_u32("marked graph node", marked)?;
65
66 // --- The rank index ------------------------------------------------------
67 // From here on a node's address is the number of marked ids below its own, so
68 // the node array is implicitly ordered by OSM id and needs to store neither
69 // the id nor a sorted side table to look it up by.
70 timer.switch("rank-index");
71 let counted = mask.build_rank(max_id);
72 if counted != marked {
73 // The mask and the running count are maintained in the same loop, so a
74 // disagreement means one of the two is wrong about which ids were set,
75 // and every address derived from the rank would be off by however many.
76 return Err(Error(format!(
77 "rank index counted {counted} marked node(s) but pass 1 set {marked}"
78 )));
79 }
80
81 // --- Pass 2: coordinates and stop codes for the marked nodes -------------
82 // Zero-initialised, so the slots belonging to dangling refs are never touched
83 // and never fault in: an untouched page of `coords` costs no real memory.
84 let mut coords: Vec<geom::Pt> = vec![(0, 0); slots as usize];
85 let mut present = Bitset::new(u64::from(slots));
86 let mut stop = Bitset::new(u64::from(slots));
87 let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new();
88 let mut node_count: u64 = 0;
89 timer.switch("node-scan");
90 // Coordinates scatter from the decode workers. Each node id claims its
91 // `present` bit atomically and only the claimant writes its slot, so every
92 // slot has exactly one writer. That equals the serial fold — which let the
93 // LAST occurrence of an id win — whenever ids are unique, as they are in
94 // any well-formed (sorted) PBF. If some id occurs twice, the race for its
95 // slot could pick a different occurrence, so the pass is redone with the
96 // original single-threaded fold, keeping the output exact either way.
97 // Stop codes stay in the ordered sink: their order is interning order.
98 let duplicate = std::sync::atomic::AtomicBool::new(false);
99 {
100 let pres = present.atomic();
101 let slots_out = par::SyncPtr(coords.as_mut_ptr());
102 let _ = pbf::run_pass_sink(
103 input,
104 &blobs,
105 pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan" },
106 Pass2::default,
107 |state, block| {
108 let kinds = pass2_blob(state, block, &mask)?;
109 for (dense, lat_e7, lon_e7) in state.locs.drain(..) {
110 if pres.set(u64::from(dense)) {
111 // SAFETY: `dense < slots` (a rank over the mask), and
112 // the `present` claim above makes this the only writer.
113 unsafe { slots_out.write(dense as usize, (lat_e7, lon_e7)) };
114 state.claimed += 1;
115 } else {
116 duplicate.store(true, Ordering::Relaxed);
117 }
118 }
119 Ok(kinds)
120 },
121 |chunk| {
122 node_count += chunk.claimed;
123 for (dense, code) in chunk.stops {
124 stop.set(u64::from(dense));
125 stop_codes.push((dense, code));
126 }
127 Ok(())
128 },
129 )?;
130 }
131 if duplicate.load(Ordering::Relaxed) {
132 eprintln!("WARN: a node id occurs more than once; redoing the node scan serially");
133 coords.iter_mut().for_each(|c| *c = (0, 0));
134 present = Bitset::new(u64::from(slots));
135 stop = Bitset::new(u64::from(slots));
136 stop_codes.clear();
137 node_count = 0;
138 let _ = pbf::run_pass_sink(
139 input,
140 &blobs,
141 pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan (serial)" },
142 Pass2::default,
143 |state, block| pass2_blob(state, block, &mask),
144 |chunk| {
145 for (dense, lat_e7, lon_e7) in chunk.locs {
146 coords[dense as usize] = (lat_e7, lon_e7);
147 if present.set(u64::from(dense)) {
148 node_count += 1;
149 }
150 }
151 for (dense, code) in chunk.stops {
152 stop.set(u64::from(dense));
153 stop_codes.push((dense, code));
154 }
155 Ok(())
156 },
157 )?;
158 }
159 println!(
160 "Located {node_count} node(s); {} marked id(s) had no coordinates in the file",
161 marked - node_count
162 );
163
164 // Stop codes go into the pool only after every way name is in it, in the
165 // order pass 2 met them, so `road_names.bin` is unaffected by dense
166 // addressing and by where the way names are interned.
167 let index = NodeIndex { mask, present };
168
169 // --- Collapse ------------------------------------------------------------
170 let spill_dir = opts.spill_dir.clone().unwrap_or_else(|| out_dir.to_path_buf());
171 let spill_pts_dir = opts.spill_pts_dir.clone().unwrap_or_else(|| spill_dir.clone());
172 timer.switch("collapse");
173 let mut collapsed = if opts.within_way_chains {
174 collapse_within_ways(
175 input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,
176 slots, filter, &mut pool, &mut timer,
177 )?
178 } else {
179 collapse_segments(
180 input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,
181 slots, filter, &mut pool, &mut timer,
182 )?
183 };
184
185 let mut prog = crate::progress::Progress::new("Interning stop codes", stop_codes.len() as u64);
186 for (_, code) in &stop_codes {
187 pool.intern(code).map_err(io_err)?;
188 prog.inc();
189 }
190 prog.finish();
191 drop(stop_codes);
192 timer.switch("rank-survivors");
193
194 // `saturating_sub` because a file with no routable ways and no stop nodes
195 // marks nothing, and there is then no largest id to index up to.
196 let kept_count = cap_u32(
197 "surviving node",
198 collapsed.kept.build_rank(u64::from(slots).saturating_sub(1)),
199 )?;
200 let kept = collapsed.kept;
201 println!(
202 "Collapsed {node_count} node(s) -> {kept_count} ({} chain(s), {} split(s) for the \
203 256-point limit)",
204 collapsed.chain_count, collapsed.splits
205 );
206 cap_u32("chain", collapsed.chain_count)?;
207 let raw_edge_count = collapsed.raw_edge_count;
208
209 // --- Morton order -------------------------------------------------------
210 // Deferred to here, and applied only to the survivors, because that is the
211 // only set the device ever binary-searches. Sorting before the collapse would
212 // have meant carrying a 64-bit spatial key through every node that was about
213 // to be collapsed away.
214 timer.switch("morton-sort");
215 println!("Sorting {kept_count} surviving node(s) by spatial key...");
216 // Keys on the pool, written in place: the kept bitset's rank says where
217 // each slot range's keys start, so every range fills its own disjoint
218 // slice and `keys` comes out exactly as the serial loop pushed it
219 // (ascending `dense`) with no second copy.
220 let mut keys: Vec<(u64, u32)> = vec![(0, 0); kept_count as usize];
221 {
222 const RANGE: usize = 1 << 20;
223 let ranges: Vec<(usize, usize)> = (0..(slots as usize).div_ceil(RANGE))
224 .map(|r| (r * RANGE, ((r + 1) * RANGE).min(slots as usize)))
225 .collect();
226 let mut pieces: Vec<KeyPiece<'_>> = Vec::with_capacity(ranges.len());
227 let mut rest: &mut [(u64, u32)] = &mut keys;
228 for &(lo, hi) in &ranges {
229 // Kept ids below `hi` minus those below `lo`.
230 let rank = |i: usize| -> usize {
231 if i >= slots as usize {
232 kept_count as usize
233 } else {
234 kept.dense(i as u64) as usize
235 }
236 };
237 let (mine, tail) = rest.split_at_mut(rank(hi) - rank(lo));
238 pieces.push(((lo, hi), mine));
239 rest = tail;
240 }
241 debug_assert!(rest.is_empty());
242 let coords = &coords;
243 let kept = &kept;
244 par::install(|| {
245 pieces.par_iter_mut().for_each(|((lo, hi), out)| {
246 let mut k = 0usize;
247 for i in *lo as u32..*hi as u32 {
248 if kept.get(u64::from(i)) {
249 let (lat_e7, lon_e7) = coords[i as usize];
250 out[k] = (spatial_from_e7(lat_e7, lon_e7), i);
251 k += 1;
252 }
253 }
254 debug_assert_eq!(k, out.len());
255 });
256 });
257 }
258 // The key is `(spatial, dense)`, and the keys are laid out with `dense`
259 // ascending, so this is exactly the order the previous STABLE
260 // `sort_by_key(spatial)` produced: ties there fell back to insertion order,
261 // which was ascending `dense`. Spelling the tie-break into the key makes the
262 // order total, and a total order is what lets an UNSTABLE parallel sort be
263 // substituted without changing a single final id -- and final ids are what
264 // `nodes.bin`, `edges.bin` and every offset in the pack are numbered by, so
265 // this is the one comparison in the build that must not move.
266 eprintln!("Sorting {kept_count} spatial key(s)...");
267 par::install(|| keys.par_sort_unstable());
268
269 // Final ids on the pool. `final_of_kept` is a permutation write (every
270 // `dense` appears once in `keys`), `node_coords` an ordered map, and each
271 // byte of `stops_final` a pure function of its own eight final ids.
272 let mut final_of_kept = vec![0u32; kept_count as usize];
273 let mut stops_final = Bitset::new(u64::from(kept_count));
274 let node_coords: Vec<geom::Pt> = {
275 let out = par::SyncPtr(final_of_kept.as_mut_ptr());
276 let (keys, kept, coords, stop) = (&keys, &kept, &coords, &stop);
277 par::install(|| {
278 keys.par_iter().enumerate().for_each(|(final_id, (_, dense))| {
279 // SAFETY: `keys` holds each kept dense id exactly once, so each
280 // rank is written by exactly one iteration.
281 unsafe { out.write(kept.dense(u64::from(*dense)) as usize, final_id as u32) };
282 });
283 stops_final.bits.par_chunks_mut(1 << 16).enumerate().for_each(|(ci, chunk)| {
284 for (j, byte) in chunk.iter_mut().enumerate() {
285 let base = ((ci << 16) + j) * 8;
286 let mut v = 0u8;
287 for k in 0..8 {
288 if let Some((_, dense)) = keys.get(base + k) {
289 if stop.get(u64::from(*dense)) {
290 v |= 1 << k;
291 }
292 }
293 }
294 *byte = v;
295 }
296 });
297 keys.par_iter().map(|(_, dense)| coords[*dense as usize]).collect()
298 })
299 };
300 drop(keys);
301 drop(stop);
302 // The chain spill holds coordinates, so nothing downstream needs the array
303 // indexed by *marked* node — the largest in the build — any longer.
304 drop(coords);
305 drop(index);
306 let ids = FinalIds {
307 kept: &kept,
308 of_kept: &final_of_kept,
309 };
310
311 // --- The edge index -----------------------------------------------------
312 timer.switch("edge-index");
313 let csr = build_csr(&collapsed.spill, kept_count, &ids, &mut timer)?;
314
315 // --- Reconnect isolated transit stops -----------------------------------
316 timer.switch("components");
317 let rec = reconnect_isolated_stops(&node_coords, &stops_final, &csr);
318 let synth = rec.synth;
319 drop(stops_final);
320
321 // --- Write --------------------------------------------------------------
322 // Load the optional DEM up front so a bad `--dem` path fails before the write starts. `None`
323 // leaves `elevation.bin` unwritten and every node's baked elevation at 0.
324 let dem = match &opts.dem {
325 Some(path) => Some(crate::dem::Dem::load(path)?),
326 None => None,
327 };
328 timer.switch("write");
329 let written = write_graph(
330 out_dir,
331 &node_coords,
332 &collapsed.spill,
333 &collapsed.lane_pool,
334 &csr,
335 &synth,
336 &ids,
337 opts.round_count(),
338 dem.as_ref(),
339 &mut timer,
340 )?;
341 collapsed.spill.remove();
342 let unique_names = pool.unique_count();
343 let name_bytes = pool.byte_len();
344 pool.finish().map_err(io_err)?;
345
346 timer.finish();
347 println!(
348 "Done. Nodes: {} Edges: {} intermediate.bin: {} byte(s)",
349 kept_count, written.edge_count, written.intermediate_bytes
350 );
351 Ok(Stats {
352 node_count: u64::from(kept_count),
353 edge_count: written.edge_count,
354 unique_names,
355 name_bytes,
356 lcc_size: rec.lcc_size,
357 stops_already_connected: rec.already_connected,
358 reconnected_stops: synth.len() / 2,
359 stops_unreachable: rec.unreachable,
360 raw_node_count: node_count,
361 raw_edge_count,
362 chain_splits: collapsed.splits,
363 geometry_edges: written.geometry_edges,
364 reversed_edges: written.reversed_edges,
365 intermediate_bytes: written.intermediate_bytes,
366 edges_bytes: written.edges_bytes,
367 escape_count: written.escape_count,
368 named_edges: written.named_edges,
369 census: written.census,
370 })
371}
372
373/// What either collapse strategy hands the writer.
374///
375/// Both produce the same thing — a chain spill plus the set of nodes that survive
376/// — and differ only in how much memory it costs to get there and whether a chain
377/// may cross from one OSM way into the next.
378///
379/// The chains are always on disk, even for the reference path that had them in
380/// memory anyway, so that there is one writer. That also means `coords` — the
381/// largest array in the build, and the only one indexed by *marked* rather than
382/// surviving node — can be freed before the writer runs.
383struct Collapsed {
384 spill: chains::Spill,
385 /// Dense ids that survive as graph nodes.
386 kept: Bitset,
387 lane_pool: Vec<u16>,
388 chain_count: u64,
389 splits: usize,
390 raw_edge_count: u64,
391}
392