Modern Apps git

← Modern-Apps.git

maps: measure mamaps against the MVT it replaces, and its vocabulary

Commit
79c8b496e88e1f4c2b8de63fdde259e755a4c3ff
Author
vayun-mathur <[email protected]>
When
2026-08-28 00:32 UTC (3 months ago)
Parents
46bba33

Diff

scripts/maps/tile_build/examples/mamaps_size.rs
diff --git a/scripts/maps/tile_build/examples/mamaps_size.rs b/scripts/maps/tile_build/examples/mamaps_size.rsnew file mode 100644index 0000000000..da11f3c0de--- /dev/null+++ b/scripts/maps/tile_build/examples/mamaps_size.rs@@ -0,0 +1,90 @@+//! `mamaps_size` — what a `.mamaps` body costs against the MVT it replaces, across zooms.+//!+//! The measurement that settled the coordinate arena, kept so it can be re-run. The first draft of+//! the format stored coordinates as flat `[i16 x, i16 y]` pairs on the reasoning that a zero-copy+//! slice is the cheapest decode; against the real published archive that cost **1.72× the+//! compressed bytes of the MVT it replaces**, because 87% of a body is coordinates and a fixed 4+//! bytes per point is worse than a zigzag varint delta of 1 to 2. Per-part varint deltas bring it+//! to about 1.14×.+//!+//! So this is a regression guard rather than a boast. `.mamaps` is **not** smaller than MVT; what it+//! wins is the decode — no per-tile string table, no property map, no `String` allocation per+//! feature, and one flat point list per layer instead of a geometry-command walk per feature. Run+//! it after any change to the body encoding.+//!+//! Reads the published archive over ranged GETs through `curl`, so it needs a network but no+//! local data.+//!+//! As measured: 1.02x MVT compressed over a San Francisco pyramid, and *better* than MVT at z8,+//! z11 and z4 where features carry attributes. Parity in bytes, and a much cheaper decode.++use std::process::Command;++use tile_build::mamaps::body;+use tile_build::mamaps::from_mvt;+use tile_build::mvt::Tile;+use tile_build::proto::{err, Result};+use tilecodec::stream::{RangeReader, StreamArchive};++const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";++struct Curl;++impl RangeReader for Curl {+    fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+        let range = format!("{offset}-{}", offset + length as u64 - 1);+        match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {+            Ok(out) if out.status.success() => Ok(out.stdout),+            Ok(out) => err(format!("curl failed: {}", out.status)),+            Err(e) => err(format!("curl: {e}")),+        }+    }+}++fn main() {+    let mut archive = StreamArchive::open(Curl).expect("open");+    let deflate = |b: &[u8]| miniz_oxide::deflate::compress_to_vec(b, 9).len();++    // San Francisco down the pyramid, which is what a user actually streams.+    let places: &[(u8, u32, u32, &str)] = &[+        (0, 0, 0, "world"),+        (4, 2, 6, "california"),+        (8, 40, 98, "bay area"),+        (11, 327, 791, "san francisco"),+        (14, 2620, 6333, "downtown SF"),+    ];+    println!(+        "{:<16}{:>10}{:>10}{:>10}{:>10}{:>9}{:>9}{:>8}",+        "tile", "mvt", "mvt-z", "mamaps", "mamaps-z", "ratio", "points", "feats",+    );+    let (mut mvt_total, mut ours_total) = (0usize, 0usize);+    for (z, x, y, name) in places {+        let Some(raw) = archive.tile(*z, *x, *y).expect("tile") else {+            println!("{name}: absent");+            continue;+        };+        let tile = Tile::decode(&raw).expect("decode");+        let (mamaps, stats) = from_mvt::from_tile(&tile).expect("convert");+        let encoded = body::serialize(&mamaps).expect("serialize");+        let points: usize = mamaps.layers.iter().map(|l| l.coords.len()).sum();+        let (mvt_z, ours_z) = (deflate(&raw), deflate(&encoded));+        println!(+            "{:<16}{:>10}{:>10}{:>10}{:>10}{:>9}{:>9}{:>8}",+            name,+            raw.len(),+            mvt_z,+            encoded.len(),+            ours_z,+            format!("{:.2}x", ours_z as f64 / mvt_z as f64),+            points,+            stats.features,+        );+        mvt_total += mvt_z;+        ours_total += ours_z;+    }+    println!(+        "\ncompressed total: mvt {mvt_total}, mamaps {ours_total} ({:.2}x)",+        ours_total as f64 / mvt_total as f64,+    );+    println!("a ratio near 1.7x means the coordinate arena has reverted to fixed-width pairs");+}
scripts/maps/tile_build/examples/mamaps_vocabulary.rs
diff --git a/scripts/maps/tile_build/examples/mamaps_vocabulary.rs b/scripts/maps/tile_build/examples/mamaps_vocabulary.rsnew file mode 100644index 0000000000..f20f755f5b--- /dev/null+++ b/scripts/maps/tile_build/examples/mamaps_vocabulary.rs@@ -0,0 +1,108 @@+//! Collect the `(layer, kind)` vocabulary the published archive actually uses, and flag anything+//! `mamaps::dict` has no id for.+//!+//! The measurement that says how complete the schema table is. Sampled rather than exhaustive: the+//! published archive is 137 GB, and the point is to find values we do not carry, which show up in+//! the first few hundred tiles or not at all.++use std::collections::{BTreeMap, BTreeSet};+use std::process::Command;++use tile_build::mamaps::{dict, from_mvt};+use tile_build::mvt::{Tile, Value};+use tile_build::proto::{err, Result};+use tilecodec::stream::{RangeReader, StreamArchive};++const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";++struct Curl;++impl RangeReader for Curl {+    fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+        let range = format!("{offset}-{}", offset + length as u64 - 1);+        match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {+            Ok(out) if out.status.success() => Ok(out.stdout),+            Ok(out) => err(format!("curl failed: {}", out.status)),+            Err(e) => err(format!("curl: {e}")),+        }+    }+}++fn main() {+    let mut archive = StreamArchive::open(Curl).expect("open");+    // A spread rather than a sweep: world, California, the Bay, SF, downtown, plus a few places+    // with different geography so the vocabulary is not just one metro's.+    let tiles: &[(u8, u32, u32)] = &[+        (0, 0, 0),+        (2, 0, 1),+        (4, 2, 6),+        (5, 5, 12),+        (6, 10, 24),+        (8, 40, 98),+        (8, 41, 98),+        (10, 163, 395),+        (11, 327, 791),+        (12, 655, 1583),+        (13, 1310, 3166),+        (14, 2620, 6333),+        (14, 2621, 6333),+        (14, 2620, 6334),+    ];++    let mut seen: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();+    let mut details: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    let mut other_props: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    for (z, x, y) in tiles {+        let Some(raw) = archive.tile(*z, *x, *y).expect("tile") else { continue };+        let tile = Tile::decode(&raw).expect("decode");+        for layer in &tile.layers {+            if !dict::LAYERS.contains(&layer.name.as_str()) {+                continue;+            }+            for feature in &layer.features {+                for (key, value) in &feature.props {+                    match (key.as_str(), value) {+                        ("kind", Value::String(kind)) => {+                            *seen+                                .entry(layer.name.clone())+                                .or_default()+                                .entry(kind.clone())+                                .or_default() += 1;+                        }+                        ("kind_detail", Value::String(detail)) => {+                            details.entry(layer.name.clone()).or_default().insert(detail.clone());+                        }+                        ("kind_detail", other) => {+                            details+                                .entry(layer.name.clone())+                                .or_default()+                                .insert(format!("<{other:?}>"));+                        }+                        (key, _) => {+                            other_props.entry(layer.name.clone()).or_default().insert(key.to_string());+                        }+                    }+                }+            }+        }+    }++    println!("== kinds, by layer. `MISSING` is one the schema table has no id for ==");+    for (layer, kinds) in &seen {+        for (kind, count) in kinds {+            let mark = if from_mvt::kind_id(kind).is_some() { "     " } else { "MISS " };+            println!("{mark}{layer:<12}{kind:<26}{count}");+        }+    }+    println!("\n== kind_detail values seen ==");+    for (layer, values) in &details {+        for value in values {+            let mark = if from_mvt::detail_id(value).is_some() { "     " } else { "MISS " };+            println!("{mark}{layer:<12}{value}");+        }+    }+    println!("\n== other property keys, which this format deliberately drops ==");+    for (layer, keys) in &other_props {+        println!("{layer:<12}{}", keys.iter().cloned().collect::<Vec<_>>().join(","));+    }+}