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

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

overlay_s1.rs397 lines · 16.9 KiBRaw
1fn build_from_chunked(
2 meta: &[u8],
3 nodes: &[u8],
4 edges: &[u8],
5 out: &Path,
6 chunk_nodes: u32,
7) -> io::Result<OverlayStats> {
8 let walk = GraphWalk::open(meta, nodes, edges)?;
9 let n = walk.node_count as u64;
10 let full_edges = u64_at(meta, 16);
11 let chunk_nodes = chunk_nodes.max(1);
12 let units: Vec<u32> = (0..n.div_ceil(u64::from(chunk_nodes))).map(|c| c as u32).collect();
13 let range = |c: u32| -> (u32, u32) {
14 let a = u64::from(c) * u64::from(chunk_nodes);
15 (a as u32, (a + u64::from(chunk_nodes)).min(n) as u32)
16 };
17
18 // Pass 1: every endpoint of an arterial edge is on the overlay. A target may sit in any
19 // range, so the bitmap is shared; `fetch_or` makes the result independent of which
20 // thread sets a bit first.
21 let shared: Vec<AtomicU8> = (0..n.div_ceil(8)).map(|_| AtomicU8::new(0)).collect();
22 let set = |id: u32| {
23 shared[(id / 8) as usize].fetch_or(1 << (id % 8), Ordering::Relaxed);
24 };
25 let pass1 = par::map_chunks(&units, 1, |_, unit| -> io::Result<Arterials> {
26 let (a, b) = range(unit[0]);
27 let mut art = Arterials::default();
28 walk.for_range(a, b, |u, lat, lon, es| {
29 let before = art.edges.len();
30 for (i, e) in es.iter().filter(|(_, e)| on_overlay(e.type_)) {
31 if u64::from(e.target) >= n {
32 return Err(bad(format!(
33 "edge from {u} targets {} past the node count",
34 e.target
35 )));
36 }
37 set(u);
38 set(e.target);
39 art.edges.push((u, *i, *e));
40 }
41 if art.edges.len() > before {
42 art.sources.push((u, lat, lon));
43 }
44 Ok(())
45 })?;
46 Ok(art)
47 });
48 // The first failing range in range order is the first failure a sequential walk meets.
49 let pass1: Vec<Arterials> = pass1.into_iter().collect::<io::Result<_>>()?;
50 let present: Vec<u8> = shared.into_iter().map(AtomicU8::into_inner).collect();
51
52 // Rank index: set bits before each 64-byte block, then the total.
53 let blocks = n.div_ceil(RANK_BLOCK_BYTES * 8);
54 let mut rank = Vec::with_capacity(blocks as usize + 1);
55 let mut running = 0u64;
56 for b in 0..=blocks {
57 rank.push(running);
58 let lo = (b * RANK_BLOCK_BYTES) as usize;
59 let hi = (lo + RANK_BLOCK_BYTES as usize).min(present.len());
60 if lo < hi {
61 running += present[lo..hi].iter().map(|x| u64::from(x.count_ones())).sum::<u64>();
62 }
63 }
64 let m = running;
65 let of = |id: u32| -> u32 {
66 let byte = u64::from(id) / 8;
67 let block = byte / RANK_BLOCK_BYTES;
68 let mut r = rank[block as usize];
69 for x in &present[(block * RANK_BLOCK_BYTES) as usize..byte as usize] {
70 r += u64::from(x.count_ones());
71 }
72 (r + u64::from((present[byte as usize] & ((1u8 << (id % 8)) - 1)).count_ones())) as u32
73 };
74 let is_set = |id: u32| present[(id / 8) as usize] & (1 << (id % 8)) != 0;
75
76 // Pass 2: emit nodes in full-id order with their arterial out-edges, per range.
77 let pass2 = par::map_chunks(&units, 1, |_, unit| -> io::Result<Emitted> {
78 let (a, b) = range(unit[0]);
79 let art = &pass1[unit[0] as usize];
80 let mut em = Emitted { nodes: Vec::new(), edges: Vec::new(), edge_count: 0 };
81 let mut cache = BlockCache::new(1);
82 let (mut si, mut ei) = (0usize, 0usize);
83 for u in a..b {
84 if !is_set(u) {
85 continue;
86 }
87 // Every source is on the overlay, so the cursor meets them in order.
88 let (lat, lon) = match art.sources.get(si) {
89 Some(&(s, lat, lon)) if s == u => {
90 si += 1;
91 (lat, lon)
92 }
93 _ => {
94 let (lat, lon, _) = walk.node_at(u64::from(u), &mut cache)?;
95 (lat, lon)
96 }
97 };
98 let mut rec = [0u8; NODE_LEN];
99 rec[0..4].copy_from_slice(&lat.to_le_bytes());
100 rec[4..8].copy_from_slice(&lon.to_le_bytes());
101 // Relative; rebased in the merge below.
102 rec[8..12].copy_from_slice(&(em.edge_count as u32).to_le_bytes());
103 rec[12..16].copy_from_slice(&u.to_le_bytes());
104 em.nodes.extend_from_slice(&rec);
105 while let Some(&(src, i, e)) = art.edges.get(ei) {
106 if src != u {
107 break;
108 }
109 let mut rec = [0u8; EDGE_LEN];
110 rec[0..4].copy_from_slice(&of(e.target).to_le_bytes());
111 rec[4..8].copy_from_slice(&e.dist_mm.to_le_bytes());
112 rec[8..16].copy_from_slice(&i.to_le_bytes());
113 rec[16] = e.type_;
114 rec[17] = e.speed_limit;
115 em.edges.extend_from_slice(&rec);
116 em.edge_count += 1;
117 ei += 1;
118 }
119 }
120 Ok(em)
121 });
122 drop(pass1);
123
124 // Ordered merge: rebase each range's edge pointers on the edges before it.
125 let mut node_recs: Vec<u8> = Vec::with_capacity((m as usize + 1) * NODE_LEN);
126 let mut edge_recs: Vec<u8> = Vec::new();
127 let mut k = 0u64;
128 for em in pass2 {
129 let em = em?;
130 for rec in em.nodes.chunks_exact(NODE_LEN) {
131 let ptr = u32::try_from(k + u64::from(u32_at(rec, 8)))
132 .map_err(|_| bad("overlay edge count past u32"))?;
133 node_recs.extend_from_slice(&rec[0..8]);
134 node_recs.extend_from_slice(&ptr.to_le_bytes());
135 node_recs.extend_from_slice(&rec[12..16]);
136 }
137 edge_recs.extend_from_slice(&em.edges);
138 k += em.edge_count;
139 }
140 let mut sentinel = [0u8; NODE_LEN];
141 sentinel[8..12].copy_from_slice(
142 &u32::try_from(k).map_err(|_| bad("overlay edge count past u32"))?.to_le_bytes(),
143 );
144 sentinel[12..16].copy_from_slice(&u32::MAX.to_le_bytes());
145 node_recs.extend_from_slice(&sentinel);
146 let nodes_sec = blocked_section(&node_recs, NODE_LEN);
147 drop(node_recs);
148 let edges_sec = blocked_section(&edge_recs, EDGE_LEN);
149 drop(edge_recs);
150
151 // One large buffer: the file is written in a few big sequential extents.
152 let mut f = io::BufWriter::with_capacity(8 << 20, std::fs::File::create(out)?);
153 f.write_all(&OVERLAY_MAGIC.to_le_bytes())?;
154 f.write_all(&OVERLAY_VERSION.to_le_bytes())?;
155 for v in [n, full_edges, m, k, nodes_sec.len() as u64, edges_sec.len() as u64] {
156 f.write_all(&v.to_le_bytes())?;
157 }
158 let nodes_end = 56 + nodes_sec.len() as u64;
159 let edges_end = align8(nodes_end) + edges_sec.len() as u64;
160 f.write_all(&nodes_sec)?;
161 f.write_all(&vec![0u8; (align8(nodes_end) - nodes_end) as usize])?;
162 f.write_all(&edges_sec)?;
163 f.write_all(&vec![0u8; (align8(edges_end) - edges_end) as usize])?;
164 for r in &rank {
165 f.write_all(&r.to_le_bytes())?;
166 }
167 f.write_all(&present)?;
168 f.flush()?;
169 let bytes = align8(edges_end) + rank.len() as u64 * 8 + present.len() as u64;
170 Ok(OverlayStats { full_nodes: n, full_edges, nodes: m, edges: k, bytes })
171}
172
173/// `records` as a ZBLK section, byte-identical to what
174/// [`tilecodec::blocked::BlockedStreamWriter`] writes for the same records, with the
175/// blocks compressed in parallel.
176///
177/// The stream writer compresses each 4096-record block on its own with a fresh encoder, so
178/// a block's frame depends on that block's bytes alone. Each frame here is taken from
179/// [`write_blocked_with`] over that one block — tilecodec's own encoder and settings, so
180/// the two cannot drift — and the header and offset table are laid out as the module docs
181/// of `tilecodec::blocked` specify. `blocked_section_matches_the_stream_writer` pins the
182/// equality.
183fn blocked_section(records: &[u8], record_len: usize) -> Vec<u8> {
184 assert_eq!(records.len() % record_len, 0, "whole records only");
185 let per_block = BLOCK_RECORDS as usize * record_len;
186 let blocks: Vec<&[u8]> = records.chunks(per_block).collect();
187 let frames: Vec<Vec<u8>> = par::map_chunks(&blocks, 1, |_, block| {
188 let one = write_blocked_with(block[0], record_len, BLOCK_RECORDS);
189 let parsed = Blocked::parse(&one).expect("a section tilecodec just wrote");
190 let lo = parsed.block_offset(0).expect("one block") as usize;
191 let hi = parsed.block_offset(1).expect("one block") as usize;
192 one[lo..hi].to_vec()
193 });
194 let mut out = Vec::with_capacity(
195 28 + (frames.len() + 1) * 8 + frames.iter().map(Vec::len).sum::<usize>(),
196 );
197 out.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());
198 out.extend_from_slice(&0u32.to_le_bytes());
199 out.extend_from_slice(&(record_len as u32).to_le_bytes());
200 out.extend_from_slice(&BLOCK_RECORDS.to_le_bytes());
201 out.extend_from_slice(&(records.len() as u64).to_le_bytes());
202 out.extend_from_slice(&(frames.len() as u32).to_le_bytes());
203 let mut off = (28 + (frames.len() + 1) * 8) as u64;
204 for f in &frames {
205 out.extend_from_slice(&off.to_le_bytes());
206 off += f.len() as u64;
207 }
208 out.extend_from_slice(&off.to_le_bytes());
209 for f in &frames {
210 out.extend_from_slice(f);
211 }
212 out
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 /// A motorway A-B-C, a motorway_link C-D, residential D-E and B-F.
220 fn sample(tag: &str) -> std::path::PathBuf {
221 let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000);
222 let nodes: Vec<(i64, i32, i32)> = (1..=6).map(|id| (id as i64, p(id).0, p(id).1)).collect();
223 let nodes =
224 [nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], (6, p(2).0 + 5_000, p(2).1 - 5_000)];
225 let ways: [(i64, &str, &[i64]); 4] = [
226 (10, "motorway", &[1, 2, 3]),
227 (11, "motorway_link", &[3, 4]),
228 (12, "residential", &[4, 5]),
229 (13, "residential", &[2, 6]),
230 ];
231 let (pbf, dir) = crate::testpbf::write_highway_sample(tag, &nodes, &ways);
232 crate::graph_build::build(&pbf, &dir).unwrap();
233 dir
234 }
235
236 struct Decoded {
237 header: [u64; 6],
238 nodes: Vec<(i32, i32, u32, u32)>,
239 edges: Vec<(u32, u32, u64, u8)>,
240 }
241
242 fn decode(bytes: &[u8]) -> Decoded {
243 assert_eq!(u32_at(bytes, 0), OVERLAY_MAGIC);
244 assert_eq!(u32_at(bytes, 4), OVERLAY_VERSION);
245 let header: [u64; 6] = std::array::from_fn(|i| u64_at(bytes, 8 + i * 8));
246 let (nodes_len, edges_len) = (header[4] as usize, header[5] as usize);
247 let inflate = |b: &[u8]| {
248 let v = Blocked::parse(b).unwrap();
249 let mut c = BlockCache::new(0);
250 (0..v.block_count()).flat_map(|i| c.get(&v, i).unwrap().clone()).collect::<Vec<u8>>()
251 };
252 let nb = inflate(&bytes[56..56 + nodes_len]);
253 let edges_at = align8(56 + nodes_len as u64) as usize;
254 let eb = inflate(&bytes[edges_at..edges_at + edges_len]);
255 let nodes = nb
256 .chunks(NODE_LEN)
257 .map(|r| {
258 (
259 i32::from_le_bytes(r[0..4].try_into().unwrap()),
260 i32::from_le_bytes(r[4..8].try_into().unwrap()),
261 u32_at(r, 8),
262 u32_at(r, 12),
263 )
264 })
265 .collect();
266 let edges = eb
267 .chunks(EDGE_LEN)
268 .map(|r| (u32_at(r, 0), u32_at(r, 4), u64_at(r, 8), r[16]))
269 .collect();
270 Decoded { header, nodes, edges }
271 }
272
273 #[test]
274 fn the_overlay_holds_the_arterials_and_their_ramps_only() {
275 let dir = sample("overlay_arterials");
276 let out = dir.join("overlay.bin");
277 let stats = build(&dir, &out).unwrap();
278 let d = decode(&std::fs::read(&out).unwrap());
279 assert_eq!(d.header[0], stats.full_nodes);
280 assert_eq!((d.header[2], d.header[3]), (stats.nodes, stats.edges));
281 assert_eq!(d.nodes.len() as u64, stats.nodes + 1, "plus the sentinel");
282 assert_eq!(d.nodes.last().unwrap().2 as u64, stats.edges, "sentinel edge_ptr is K");
283 // Coordinates identify the full nodes regardless of compaction.
284 let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000);
285 let coords: Vec<(i32, i32)> =
286 d.nodes[..stats.nodes as usize].iter().map(|n| (n.0, n.1)).collect();
287 for id in [1, 4] {
288 assert!(coords.contains(&p(id)), "motorway end / ramp end {id} is on the overlay");
289 }
290 assert!(!coords.contains(&p(5)), "the residential-only end is not");
291 // Each overlay edge is the full edge it names: same source, same target.
292 let meta = std::fs::read(dir.join("metadata.bin")).unwrap();
293 let (nodes, edges) =
294 (map(&dir.join("nodes.bin")).unwrap(), map(&dir.join("edges.bin")).unwrap());
295 let walk = GraphWalk::open(&meta, &nodes, &edges).unwrap();
296 let mut full: Vec<(u32, u64, u32, u8)> = Vec::new();
297 walk.for_each(|u, _, _, es| {
298 full.extend(es.iter().map(|(i, e)| (u, *i, e.target, e.type_)));
299 Ok(())
300 })
301 .unwrap();
302 let mut k = 0usize;
303 for (o, n) in d.nodes[..stats.nodes as usize].iter().enumerate() {
304 let end = d.nodes[o + 1].2 as usize;
305 for &(t, _, full_edge, ty) in &d.edges[n.2 as usize..end] {
306 let &(src, _, tgt, fty) = full.iter().find(|f| f.1 == full_edge).unwrap();
307 assert_eq!(src, n.3, "overlay node {o} owns full edge {full_edge}");
308 assert_eq!(tgt, d.nodes[t as usize].3, "target maps back");
309 assert_eq!(ty, fty);
310 assert!(on_overlay(ty));
311 k += 1;
312 }
313 }
314 assert_eq!(k as u64, stats.edges);
315 assert_eq!(
316 k,
317 full.iter().filter(|f| on_overlay(f.3)).count(),
318 "every arterial edge, nothing else"
319 );
320 // Full ids ascend, so the rank map is exact.
321 assert!(d.nodes[..stats.nodes as usize].windows(2).all(|w| w[0].3 < w[1].3));
322 }
323
324 #[test]
325 fn the_overlay_is_byte_identical_across_runs() {
326 let dir = sample("overlay_determinism");
327 build(&dir, &dir.join("a.bin")).unwrap();
328 build(&dir, &dir.join("b.bin")).unwrap();
329 assert_eq!(
330 std::fs::read(dir.join("a.bin")).unwrap(),
331 std::fs::read(dir.join("b.bin")).unwrap()
332 );
333 }
334
335 #[test]
336 fn the_overlay_is_byte_identical_across_work_splits_and_thread_counts() {
337 let dir = sample("overlay_splits");
338 build(&dir, &dir.join("ref.bin")).unwrap();
339 let want = std::fs::read(dir.join("ref.bin")).unwrap();
340 let meta = std::fs::read(dir.join("metadata.bin")).unwrap();
341 let (nodes, edges) =
342 (map(&dir.join("nodes.bin")).unwrap(), map(&dir.join("edges.bin")).unwrap());
343 // One node per range puts every range boundary between a source and its targets,
344 // so a target bit, a target-only node's coordinates and an edge pointer all cross
345 // a range on every edge.
346 for chunk in [1, 2, 3, 5, CHUNK_NODES] {
347 for threads in [1, 3, 8] {
348 crate::par::set_threads(threads);
349 let out = dir.join(format!("c{chunk}_t{threads}.bin"));
350 build_from_chunked(&meta, &nodes, &edges, &out, chunk).unwrap();
351 assert_eq!(
352 std::fs::read(&out).unwrap(),
353 want,
354 "chunk {chunk}, {threads} thread(s)"
355 );
356 }
357 }
358 crate::par::clear_threads();
359 }
360
361 #[test]
362 fn blocked_section_matches_the_stream_writer() {
363 // Several full blocks plus a tail, a single partial block, exactly one block, and
364 // nothing at all, at both overlay strides.
365 let mut x = 0x9E37_79B9_7F4A_7C15u64;
366 for record_len in [NODE_LEN, EDGE_LEN] {
367 for count in [0usize, 1, 4095, 4096, 4097, 3 * 4096 + 17] {
368 let records: Vec<u8> = (0..count * record_len)
369 .map(|i| {
370 x ^= x << 13;
371 x ^= x >> 7;
372 x ^= x << 17;
373 // Compressible but not trivially: a slow counter plus noise.
374 if i % 4 == 0 {
375 (x & 0x0F) as u8
376 } else {
377 (i / 97) as u8
378 }
379 })
380 .collect();
381 let scratch = std::env::temp_dir()
382 .join(format!("overlay_bs_{}_{record_len}_{count}.tmp", std::process::id()));
383 let mut w =
384 tilecodec::blocked::BlockedStreamWriter::create(record_len, &scratch).unwrap();
385 // Pushed in odd-sized runs, as the old builder pushed one record at a time.
386 for run in records.chunks(record_len * 7) {
387 w.push(run).unwrap();
388 }
389 assert_eq!(
390 blocked_section(&records, record_len),
391 w.finish().unwrap(),
392 "{record_len} B x {count}"
393 );
394 }
395 }
396 }
397}