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

Modern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_sizes.rs

mamaps_sizes.rs607 lines · 27.2 KiBRaw
1//! `mamaps_sizes` — byte breakdown of a `.mamaps` archive without inflating bodies.
2//!
3//! Usage: mamaps_sizes IN.mamaps [--sample-every N]
4//!
5//! Sections:
6//! A. File envelope: header/dict/root/leaves/data/sidecars/footer + alignment.
7//! B. Sidecar directory: per-section kind/offset/len.
8//! C. Tile overhead: index bytes per tile + empty-body cost (the zero-feature
9//! baseline: 16B body header + per-layer index entries with zero-length payloads).
10//! D. Per-layer stored bytes, attributed by raw-share: each body's stored
11//! (compressed) length is split across its layers by raw payload share.
12//! Bodies are compressed as a unit, so this is an estimate — exact for the
13//! total, approximate per layer (layers with similar entropy split evenly).
14//! E. Wire anatomy: feature records (24B), part entries (12B), point counts,
15//! trailing-table presence from body flags.
16//!
17//! Reads only structural metadata: header, dict, root, leaves, and each body's
18//! 16B frame prefix + layer index. Never inflates, never reads coordinates.
19//! Bodies are walked through a single sequential pass over the leaf table with
20//! the body-prefix reads batched per leaf, so a 66GB file scans in minutes.
21use std::collections::BTreeMap;
22use std::process::ExitCode;
23
24use tile_build::mamaps::body::{
25 BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP,
26 BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_ROAD_LANES,
27 BODY_HEADER_LEN, FEATURE_RECORD_LEN, LAYER_INDEX_LEN,
28};
29use tile_build::mamaps::dict::Dictionary;
30use tile_build::mamaps::header::Header;
31use tile_build::mamaps::index::{decompress_leaf, parse_leaf, parse_root, LEAF_ENTRY_LEN, ROOT_ENTRY_LEN};
32
33const KIND_NAMES: [(u8, &str); 13] = [
34 (1, "graph_meta"), (2, "graph_nodes"), (3, "graph_edges"), (4, "graph_intermediate"),
35 (5, "graph_names"), (6, "graph_lanes"), (7, "graph_elevation"), (8, "poi_index"),
36 (9, "poi_names"), (10, "poi_attrs"), (11, "poi_spatial"), (12, "poi_words"),
37 (13, "transit"),
38];
39
40fn gb(n: u64) -> f64 {
41 n as f64 / 1e9
42}
43
44fn th(n: u64) -> String {
45 let s = n.to_string();
46 let mut out = String::with_capacity(s.len() + s.len() / 3);
47 for (i, c) in s.chars().rev().enumerate() {
48 if i > 0 && i % 3 == 0 {
49 out.push(',');
50 }
51 out.push(c);
52 }
53 out.chars().rev().collect()
54}
55
56fn kind_name(kind: u8) -> String {
57 KIND_NAMES.iter().find(|(k, _)| *k == kind).map(|(_, n)| n.to_string()).unwrap_or_else(|| format!("kind{kind}"))
58}
59
60/// One leaf's worth of the D/E scan, computed on a worker thread with its own
61/// file handle. Aggregated by the caller; never shared mid-scan.
62#[derive(Default)]
63struct Partial {
64 bodies_seen: u64,
65 total_stored: u64,
66 total_raw: u64,
67 empty_bodies: u64,
68 empty_stored: u64,
69 extended_count: u64,
70 layer_stored: BTreeMap<u8, u64>,
71 layer_raw: BTreeMap<u8, u64>,
72 layer_bodies: BTreeMap<u8, u64>,
73 layer_features: BTreeMap<u8, u64>,
74 flags_hist: BTreeMap<u8, u64>,
75 // Stored bytes by (zoom, layer): exact per-zoom totals need no sampling —
76 // the zoom comes from the tile id, the layer split from the sample below.
77 // Keyed (zoom, layer) -> sampled stored bytes; scaled like layer_stored.
78 zoom_layer_stored: BTreeMap<(u8, u8), u64>,
79 // Trailing-table bytes by section, measured on the RAW (decompressed) body:
80 // names, ids, turn-lanes, buildings, heightmap, carriageways. Compressed
81 // share is attributed by raw-share like the layers.
82 table_raw: BTreeMap<&'static str, u64>,
83 table_stored: BTreeMap<&'static str, u64>,
84}
85
86fn scan_leaf(
87 path: &str,
88 header: &Header,
89 re: &tile_build::mamaps::index::RootEntry,
90 sample_every: u64,
91 body_counter: &std::sync::atomic::AtomicU64,
92) -> Result<Partial, String> {
93 use std::fs::File;
94 use std::io::{Read, Seek, SeekFrom};
95 let mut f = File::open(path).map_err(|e| format!("cannot open: {e}"))?;
96 let mut p = Partial::default();
97 f.seek(SeekFrom::Start(header.leaf_offset + re.leaf_offset))
98 .map_err(|e| format!("cannot seek to leaf: {e}"))?;
99 // v9 leaf framing: `stored_len == 0` is a raw legacy leaf, anything else is
100 // one raw-DEFLATE frame of that length (see `index::decompress_leaf`).
101 let raw_len = re.leaf_entry_count as usize * LEAF_ENTRY_LEN;
102 let stored_len = if re.stored_len == 0 { raw_len } else { re.stored_len as usize };
103 let mut stored_buf = vec![0u8; stored_len];
104 f.read_exact(&mut stored_buf).map_err(|e| format!("cannot read leaf: {e}"))?;
105 let leaf_buf = if re.stored_len == 0 {
106 stored_buf
107 } else {
108 decompress_leaf(&stored_buf, raw_len).map_err(|e| format!("bad leaf frame: {e:?}"))?
109 };
110 let leaf = parse_leaf(&leaf_buf).map_err(|e| format!("bad leaf: {e:?}"))?;
111 // Dedup: a run of consecutive tiles shares one body — count each stored body
112 // once (keyed by data offset), while crediting addressed tiles separately.
113 // The zoom for the (zoom, layer) table comes from each body's own tile id.
114 let mut seen_offsets = std::collections::HashSet::new();
115 for le in &leaf {
116 let start = header.data_offset + re.base_data_offset + le.offset_delta as u64;
117 if !seen_offsets.insert(start) {
118 continue;
119 }
120 let tile_id = re.base_tile_id + le.tile_id_lo as u64;
121 let zoom = tile_build::pmtiles::tile_zxy(tile_id).0;
122 // Exact totals need every body; layer attribution needs only a sample.
123 // Inflate every `sample_every`-th body (global counter): the index parse
124 // below runs on DECOMPRESSED bytes, which the old code got wrong by
125 // reading the compressed frame.
126 let n = body_counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
127 let sampled = sample_every == 0 || n % sample_every == 0;
128 // Stored length + raw length come from the leaf + frame prefix (cheap,
129 // exact, every body).
130 f.seek(SeekFrom::Start(start)).map_err(|e| format!("cannot seek to body: {e}"))?;
131 let mut prefix = [0u8; BODY_HEADER_LEN];
132 f.read_exact(&mut prefix).map_err(|e| format!("cannot read body prefix: {e}"))?;
133 if &prefix[0..3] != b"MBD" {
134 continue;
135 }
136 let raw_len = u32::from_le_bytes(prefix[4..8].try_into().unwrap()) as u64;
137 let bflags = prefix[11];
138 *p.flags_hist.entry(bflags).or_default() += 1;
139 p.total_stored += le.length as u64;
140 p.total_raw += raw_len;
141 p.bodies_seen += 1;
142 if !sampled {
143 continue;
144 }
145 // Sampled: read the whole stored frame, inflate, parse the layer index.
146 let mut stored = vec![0u8; le.length as usize];
147 f.seek(SeekFrom::Start(start)).map_err(|e| format!("cannot seek to body: {e}"))?;
148 f.read_exact(&mut stored).map_err(|e| format!("cannot read body: {e}"))?;
149 let raw = tile_build::mamaps::read::helpers::decompress(header.compression, &stored)
150 .map_err(|e| format!("cannot inflate body: {e:?}"))?;
151 let nlayers = raw[10] as usize;
152 let bflags = raw[11];
153 if bflags & BODY_FLAG_EXTENDED_COUNTS != 0 {
154 p.extended_count += 1;
155 }
156 let mut payloads: Vec<(u8, u64, u64)> = Vec::with_capacity(nlayers);
157 let mut raw_sum = 0u64;
158 for i in 0..nlayers {
159 let at = BODY_HEADER_LEN + i * LAYER_INDEX_LEN;
160 let lid = raw[at];
161 let fcount = u16::from_le_bytes([raw[at + 2], raw[at + 3]]) as u64;
162 let plen = u32::from_le_bytes(raw[at + 8..at + 12].try_into().unwrap()) as u64;
163 payloads.push((lid, fcount, plen));
164 raw_sum += plen;
165 }
166 if payloads.iter().all(|(_, fc, _)| *fc == 0) {
167 p.empty_bodies += 1;
168 p.empty_stored += le.length as u64;
169 }
170 let denom = raw_sum.max(1);
171 for (lid, fcount, plen) in payloads {
172 let share_num = plen as f64 / denom as f64;
173 let attrib = (le.length as f64 * share_num) as u64;
174 *p.layer_stored.entry(lid).or_default() += attrib;
175 *p.zoom_layer_stored.entry((zoom, lid)).or_default() += attrib;
176 *p.layer_raw.entry(lid).or_default() += plen;
177 if fcount > 0 {
178 *p.layer_bodies.entry(lid).or_default() += 1;
179 *p.layer_features.entry(lid).or_default() += fcount;
180 }
181 }
182 // Trailing tables: parse the inflated body for real and re-measure
183 // each section with the same serializers the writer uses. Exact raw
184 // bytes; stored share by raw-share like the layers.
185 {
186 use tile_build::mamaps::body::Body;
187 use tile_build::mamaps::body::{tables, tables_extra};
188 if let Ok(body) = Body::parse(&raw) {
189 let mut sections: Vec<(&'static str, usize)> = Vec::new();
190 // header + layer index (incl. extended counts), 4-aligned
191 let mut idx = BODY_HEADER_LEN + nlayers * LAYER_INDEX_LEN;
192 if bflags & BODY_FLAG_EXTENDED_COUNTS != 0 {
193 idx += nlayers * 4;
194 }
195 sections.push(("header+index", (idx + 3) & !3));
196 let mut scratch = Vec::new();
197 if !body.names.is_empty() {
198 scratch = tables::serialize_names(&body.names);
199 sections.push(("names", scratch.len()));
200 }
201 if !body.ids.is_empty() {
202 scratch.clear();
203 tables::serialize_ids(&body.ids, &mut scratch);
204 sections.push(("ids", scratch.len()));
205 }
206 if !body.turn_lanes.is_empty() {
207 scratch.clear();
208 tables::serialize_lanes(&body.turn_lanes, &mut scratch);
209 sections.push(("turn_lanes", scratch.len()));
210 }
211 if !body.buildings.is_empty() {
212 scratch.clear();
213 tables_extra::serialize_buildings(&body.buildings, &mut scratch);
214 sections.push(("buildings_table", scratch.len()));
215 }
216 if let Some(grid) = &body.heightmap {
217 scratch.clear();
218 tables::serialize_heightmap(grid, &mut scratch);
219 sections.push(("heightmap", scratch.len()));
220 }
221 if !body.carriageways.is_empty() {
222 scratch.clear();
223 tables::serialize_carriageways(
224 &body.carriageways,
225 body.convention.unwrap_or_default(),
226 &mut scratch,
227 );
228 sections.push(("carriageways", scratch.len()));
229 }
230 for (name, len) in sections {
231 let len = len as u64;
232 *p.table_raw.entry(name).or_default() += len;
233 *p.table_stored.entry(name).or_default() +=
234 ((le.length as f64) * (len as f64) / (raw_len.max(1) as f64)) as u64;
235 }
236 }
237 }
238 }
239 Ok(p)
240}
241
242fn main() -> ExitCode {
243 let args: Vec<String> = std::env::args().collect();
244 let mut input = None;
245 let mut sample_every: u64 = 0;
246 let mut i = 1;
247 while i < args.len() {
248 match args[i].as_str() {
249 "--sample-every" => {
250 sample_every = args.get(i + 1).and_then(|s| s.parse().ok()).unwrap_or(0);
251 i += 2;
252 }
253 other => {
254 if input.is_some() {
255 eprintln!("mamaps_sizes: more than one input");
256 return ExitCode::from(2);
257 }
258 input = Some(other.to_string());
259 i += 1;
260 }
261 }
262 }
263 let Some(input) = input else {
264 eprintln!("usage: mamaps_sizes IN.mamaps [--sample-every N]");
265 return ExitCode::from(2);
266 };
267 match run(&input, sample_every) {
268 Ok(()) => ExitCode::SUCCESS,
269 Err(e) => {
270 eprintln!("mamaps_sizes: {input}: {e}");
271 ExitCode::from(1)
272 }
273 }
274}
275
276fn run(path: &str, sample_every_arg: u64) -> Result<(), String> {
277 use std::fs::File;
278 use std::io::{Read, Seek, SeekFrom};
279 let mut f = File::open(path).map_err(|e| format!("cannot open: {e}"))?;
280 let size = f.metadata().map_err(|e| format!("cannot stat: {e}"))?.len();
281
282 let mut hbuf = [0u8; 128];
283 f.read_exact(&mut hbuf).map_err(|e| format!("cannot read header: {e}"))?;
284 let header = Header::parse(&hbuf).map_err(|e| format!("bad header: {e:?}"))?;
285
286 // Layer names come from the file's own dict, not a hardcoded schema table:
287 // v8 merged the four v7 wash layers (earth/water/landcover/landuse) into
288 // landtype, so any fixed table rots on the next schema change.
289 f.seek(SeekFrom::Start(header.dict_offset)).map_err(|e| format!("cannot seek to dict: {e}"))?;
290 let mut dbuf = vec![0u8; header.dict_len as usize];
291 f.read_exact(&mut dbuf).map_err(|e| format!("cannot read dict: {e}"))?;
292 let dictionary = Dictionary::parse(&dbuf).map_err(|e| format!("bad dict: {e:?}"))?;
293 let layer_names: BTreeMap<u8, String> = dictionary
294 .layers
295 .iter()
296 .enumerate()
297 .map(|(id, nm)| (id as u8, nm.clone()))
298 .collect();
299
300 println!("== {path} ({:.2} GB on disk, header declares {:.2} GB)", gb(size), gb(header.file_len));
301 println!(
302 " compression={} layers={} zoom={}..{} leaf_cap={}",
303 header.compression, header.layer_count, header.min_zoom, header.max_zoom, header.leaf_entry_capacity
304 );
305 println!(
306 " tiles_addressed={} bodies_written={} dedup={:.3}",
307 header.tiles_addressed,
308 header.bodies_written,
309 header.bodies_written as f64 / header.tiles_addressed.max(1) as f64
310 );
311 println!();
312 println!("== A. envelope");
313 println!(" {:20} {:>14} ({:.4} GB)", "header", th(128), gb(128));
314 println!(" {:20} {:>14} ({:.4} GB)", "dict", th(header.dict_len as u64), gb(header.dict_len as u64));
315 println!(
316 " {:20} {:>14} ({} entries x 32B)",
317 "root",
318 th(header.root_len as u64),
319 header.root_len / ROOT_ENTRY_LEN as u32
320 );
321 println!(
322 " {:20} {:>14} ({} entries x 16B)",
323 "leaves",
324 th(header.leaf_len),
325 header.leaf_len / LEAF_ENTRY_LEN as u64
326 );
327 println!(
328 " leaf-bytes per stored body: {:.1} B",
329 header.leaf_len as f64 / header.bodies_written.max(1) as f64
330 );
331 println!(
332 " leaf-bytes per addressed tile: {:.1} B",
333 header.leaf_len as f64 / header.tiles_addressed.max(1) as f64
334 );
335 println!(
336 " {:20} {:>14} ({:.2} GB)",
337 "tile data section",
338 th(header.data_len),
339 gb(header.data_len)
340 );
341
342 // B. sidecars via footer
343 f.seek(SeekFrom::End(-32)).map_err(|e| format!("cannot seek to footer: {e}"))?;
344 let mut footer = [0u8; 32];
345 f.read_exact(&mut footer).map_err(|e| format!("cannot read footer: {e}"))?;
346 println!();
347 if &footer[0..8] == b"MAMA8\0\0\0" {
348 let dir_offset = u64::from_le_bytes(footer[8..16].try_into().unwrap());
349 let dir_len = u64::from_le_bytes(footer[16..24].try_into().unwrap());
350 let footer_build = u64::from_le_bytes(footer[24..32].try_into().unwrap());
351 println!("== B. sidecars (dir@{dir_offset}+{dir_len} build={footer_build:#018x})");
352 f.seek(SeekFrom::Start(dir_offset)).map_err(|e| format!("cannot seek to dir: {e}"))?;
353 let mut cbuf = [0u8; 4];
354 f.read_exact(&mut cbuf).map_err(|e| format!("cannot read dir count: {e}"))?;
355 let count = u32::from_le_bytes(cbuf) as usize;
356 let mut sidecar_total = 0u64;
357 let mut prev_end = header.data_offset + header.data_len;
358 for _ in 0..count {
359 let mut ebuf = [0u8; 32];
360 f.read_exact(&mut ebuf).map_err(|e| format!("cannot read dir entry: {e}"))?;
361 let kind = ebuf[0];
362 let offset = u64::from_le_bytes(ebuf[8..16].try_into().unwrap());
363 let length = u64::from_le_bytes(ebuf[16..24].try_into().unwrap());
364 let extra = u64::from_le_bytes(ebuf[24..32].try_into().unwrap());
365 let pad_before = offset.saturating_sub(prev_end);
366 sidecar_total += length;
367 println!(
368 " {:22} {:>14} ({:.2} GB) pad_before={} extra={}",
369 kind_name(kind),
370 th(length),
371 gb(length),
372 th(pad_before),
373 extra
374 );
375 prev_end = offset + length;
376 }
377 let dir_pad = (dir_offset + dir_len).saturating_sub(prev_end);
378 println!(
379 " {:22} {:>14} pad_before_dir={}",
380 "[dir+footer]",
381 th(dir_len + 32),
382 th(dir_pad)
383 );
384 println!(" sidecar payloads total: {} ({:.2} GB)", th(sidecar_total), gb(sidecar_total));
385 } else {
386 println!("== B. sidecars: (no MAMA8 footer — tiles-only archive)");
387 }
388
389 println!();
390 println!("== C. tile overhead (the zero-feature baseline)");
391 let empty_raw = (BODY_HEADER_LEN + header.layer_count as usize * LAYER_INDEX_LEN + 3) & !3;
392 println!(" empty-body raw: {empty_raw} B (16B header + {}x12B layer index)", header.layer_count);
393 println!(" (stored empty-body cost follows from the D/E scan: bodies with no layers.)");
394 println!(
395 " index overhead: root {} + leaves {} = {} ({:.4} GB)",
396 header.root_len,
397 header.leaf_len,
398 header.root_len as u64 + header.leaf_len,
399 gb(header.root_len as u64 + header.leaf_len)
400 );
401 println!(
402 " per addressed tile: {:.1} B index",
403 (header.root_len as u64 + header.leaf_len) as f64 / header.tiles_addressed.max(1) as f64
404 );
405
406 // D/E. walk leaves -> bodies, read frame prefix + layer index only.
407 println!();
408 println!("== D/E. per-layer stored bytes (raw-share of each compressed body) + wire anatomy");
409 println!(" scanning body headers + layer indexes (no inflate, no coords)...");
410 f.seek(SeekFrom::Start(header.root_offset)).map_err(|e| format!("cannot seek to root: {e}"))?;
411 let mut root_buf = vec![0u8; header.root_len as usize];
412 f.read_exact(&mut root_buf).map_err(|e| format!("cannot read root: {e}"))?;
413 let root = parse_root(&root_buf).map_err(|e| format!("bad root: {e:?}"))?;
414
415 let mut layer_stored: BTreeMap<u8, u64> = BTreeMap::new();
416 let mut layer_raw: BTreeMap<u8, u64> = BTreeMap::new();
417 let mut layer_bodies: BTreeMap<u8, u64> = BTreeMap::new();
418 let mut layer_features: BTreeMap<u8, u64> = BTreeMap::new();
419 let mut flags_hist: BTreeMap<u8, u64> = BTreeMap::new();
420 let mut extended_count = 0u64;
421 let mut total_stored = 0u64;
422 let mut total_raw = 0u64;
423 let mut empty_bodies = 0u64;
424 let mut empty_stored = 0u64;
425 let mut bodies_seen = 0u64;
426
427 // `layer_names` was built from the file's dict above; the dead first-pass
428 // accumulators used to live here but were shadowed by the aggregation block
429 // below, so they are gone and only the dict-derived names survive.
430
431 let t0 = std::time::Instant::now();
432 // Parallel scan: one task per root entry (313 leaves for this archive), each
433 // with its own file handle (pread-style seeks are thread-safe on separate
434 // handles). Totals are exact (every body's leaf length); layer attribution
435 // inflates every `sample_every`-th body (default 64, ~2M samples, <1% error).
436 let sample_every = if sample_every_arg == 0 { 64 } else { sample_every_arg };
437 let body_counter = std::sync::atomic::AtomicU64::new(0);
438 let partials: Vec<Partial> = tile_build::par::install(|| {
439 use rayon::prelude::*;
440 root.par_iter()
441 .map(|re| scan_leaf(path, &header, re, sample_every, &body_counter).unwrap_or_else(|e| {
442 eprintln!("warning: skipping leaf @{}: {e}", re.base_tile_id);
443 Partial::default()
444 }))
445 .collect()
446 });
447 let mut layer_stored: BTreeMap<u8, u64> = BTreeMap::new();
448 let mut layer_raw: BTreeMap<u8, u64> = BTreeMap::new();
449 let mut layer_bodies: BTreeMap<u8, u64> = BTreeMap::new();
450 let mut layer_features: BTreeMap<u8, u64> = BTreeMap::new();
451 let mut flags_hist: BTreeMap<u8, u64> = BTreeMap::new();
452 let mut zoom_layer_stored: BTreeMap<(u8, u8), u64> = BTreeMap::new();
453 let mut table_raw: BTreeMap<&'static str, u64> = BTreeMap::new();
454 let mut table_stored: BTreeMap<&'static str, u64> = BTreeMap::new();
455 let mut extended_count = 0u64;
456 let mut total_stored = 0u64;
457 let mut total_raw = 0u64;
458 let mut empty_bodies = 0u64;
459 let mut empty_stored = 0u64;
460 let mut bodies_seen = 0u64;
461 for p in &partials {
462 bodies_seen += p.bodies_seen;
463 total_stored += p.total_stored;
464 total_raw += p.total_raw;
465 empty_bodies += p.empty_bodies;
466 empty_stored += p.empty_stored;
467 extended_count += p.extended_count;
468 for (k, v) in &p.layer_stored {
469 *layer_stored.entry(*k).or_default() += v;
470 }
471 for (k, v) in &p.zoom_layer_stored {
472 *zoom_layer_stored.entry(*k).or_default() += v;
473 }
474 for (k, v) in &p.table_raw {
475 *table_raw.entry(k).or_default() += v;
476 }
477 for (k, v) in &p.table_stored {
478 *table_stored.entry(k).or_default() += v;
479 }
480 for (k, v) in &p.layer_raw {
481 *layer_raw.entry(*k).or_default() += v;
482 }
483 for (k, v) in &p.layer_bodies {
484 *layer_bodies.entry(*k).or_default() += v;
485 }
486 for (k, v) in &p.layer_features {
487 *layer_features.entry(*k).or_default() += v;
488 }
489 for (k, v) in &p.flags_hist {
490 *flags_hist.entry(*k).or_default() += v;
491 }
492 }
493 println!(" bodies scanned: {bodies_seen} in {:.1}s", t0.elapsed().as_secs_f64());
494 println!(" (layer attribution from every {sample_every}-th body, scaled to exact totals)");
495 let mismatch = (total_stored as i64 - header.data_len as i64).abs();
496 println!(
497 " stored-bytes check {} vs data_len {} ({})",
498 total_stored,
499 header.data_len,
500 if mismatch < (header.data_len as i64 / 100) { "OK" } else { "MISMATCH" }
501 );
502 println!(
503 " raw bytes (declared): {} ({:.2} GB) compression ratio: {:.2}x",
504 total_raw,
505 gb(total_raw),
506 total_raw as f64 / total_stored.max(1) as f64
507 );
508 println!(" bodies with extended counts: {extended_count}");
509 println!(" body-flag histogram: {:?}", flags_hist);
510 println!(
511 " empty bodies (zero features everywhere): {empty_bodies} holding {empty_stored} stored bytes ({:.2} GB)",
512 gb(empty_stored)
513 );
514 println!();
515 println!(
516 " {:14} {:>10} {:>10} {:>10} {:>12} {:>10} {:>8}",
517 "layer", "stored(GB)", "raw(GB)", "bodies", "features", "B/feat(st)", "feat/B"
518 );
519 for (lid, st) in &layer_stored {
520 let rw = layer_raw.get(lid).copied().unwrap_or(0);
521 let nb = layer_bodies.get(lid).copied().unwrap_or(0);
522 let nf = layer_features.get(lid).copied().unwrap_or(0);
523 let nm = layer_names.get(lid).cloned().unwrap_or_else(|| format!("layer{lid}"));
524 // Scale the sampled attribution to the exact stored total: the sample
525 // ratio is uniform, so each layer's share of the sample scales linearly.
526 // Raw scales by the same factor (both accumulated on the sample only).
527 let scale = total_stored as f64 / layer_stored.values().sum::<u64>().max(1) as f64;
528 let st_scaled = (*st as f64 * scale) as u64;
529 let rw_scaled = (rw as f64 * scale) as u64;
530 // Bodies/features counts are sample-only: scale to the full body count.
531 let count_scale = bodies_seen as f64 / layer_bodies.values().sum::<u64>().max(1) as f64;
532 let nb_scaled = (nb as f64 * count_scale) as u64;
533 let nf_scaled = (nf as f64 * count_scale) as u64;
534 println!(
535 " {:14} {:>10.2} {:>10.2} {:>10} {:>12} {:>10.1} {:>8.1}",
536 nm,
537 gb(st_scaled),
538 gb(rw_scaled),
539 nb_scaled,
540 nf_scaled,
541 st_scaled as f64 / nf_scaled.max(1) as f64,
542 nf_scaled as f64 / nb_scaled.max(1) as f64
543 );
544 }
545 println!();
546 println!(" wire anatomy per feature (fixed widths): 24B feature record + 12B/part +");
547 println!(" varint arena (zigzag deltas, ~2-4B/point typical) + trailing tables.");
548 println!(" trailing-table flags: names=0x04 ids=0x02 lanes=0x08 buildings=0x10");
549 println!(" heightmap=0x20 roadlanes=0x40 (see histogram above).");
550 println!(" feature-record fields: kind u16, detail u16, geom u8, flags u8, name u16,");
551 println!(" parts_off u32, part_count u32, transit_color u32, ordinal/lanes/taper/lanecount u8x4.");
552 println!();
553 println!("== F. stored GB by (zoom, layer) — sampled attribution scaled to exact totals");
554 println!(" rows: zoom 0..14 (+ `all`); columns: layers in schema order. `..` = <0.005GB.");
555 let zscale = total_stored as f64 / zoom_layer_stored.values().sum::<u64>().max(1) as f64;
556 let nlayers = header.layer_count;
557 print!(" {:>4}", "z");
558 for lid in 0..nlayers {
559 let nm = layer_names.get(&lid).cloned().unwrap_or_else(|| format!("layer{lid}"));
560 print!(" {:>10}", nm.chars().take(10).collect::<String>());
561 }
562 println!(" {:>10}", "z-total");
563 let mut col_totals = vec![0u64; nlayers as usize];
564 for z in 0..=14u8 {
565 let mut row_total = 0u64;
566 print!(" {:>4}", z);
567 for lid in 0..nlayers {
568 let v = ((zoom_layer_stored.get(&(z, lid)).copied().unwrap_or(0) as f64) * zscale) as u64;
569 row_total += v;
570 col_totals[lid as usize] += v;
571 if v < 5_000_000 {
572 print!(" {:>10}", "..");
573 } else {
574 print!(" {:>10.2}", gb(v));
575 }
576 }
577 println!(" {:>10.2}", gb(row_total));
578 }
579 print!(" {:>4}", "all");
580 let mut grand = 0u64;
581 for lid in 0..nlayers {
582 let v = col_totals[lid as usize];
583 grand += v;
584 print!(" {:>10.2}", gb(v));
585 }
586 println!(" {:>10.2}", gb(grand));
587 println!();
588 println!("== G. trailing-table + framing bytes (sampled, scaled to exact totals)");
589 println!(" raw = re-serialized section bytes; stored = raw-share of compressed bodies.");
590 // Per-body attribution already splits each sampled body's stored bytes
591 // across its sections by raw-share. Sampling is uniform (every 64th body),
592 // so scale to full by the measured ratio of exact total stored bytes to
593 // sampled attributed stored bytes (the layer table's own scale factor).
594 let sampled_stored: u64 = layer_stored.values().sum();
595 let to_full = total_stored as f64 / sampled_stored.max(1) as f64;
596 let mut t_total_st = 0u64;
597 for name in ["header+index", "names", "ids", "turn_lanes", "buildings_table", "heightmap", "carriageways"] {
598 let st = ((table_stored.get(name).copied().unwrap_or(0) as f64) * to_full) as u64;
599 let rw = table_raw.get(name).copied().unwrap_or(0);
600 t_total_st += st;
601 println!(" {:16} stored={:>10.2} GB raw(sample)={:>12} B", name, gb(st), th(rw));
602 }
603 println!(" {:16} stored={:>10.2} GB", "tables-total", gb(t_total_st));
604 println!(" (payload arenas = the rest: total stored {:.2} GB - tables {:.2} GB = {:.2} GB geometry)",
605 gb(total_stored), gb(t_total_st), gb(total_stored.saturating_sub(t_total_st)));
606 Ok(())
607}