Skip to content

Tile multi-layer tilesets one layer at a time - #33

Open
gpt-cmdr wants to merge 3 commits into
walkerke:mainfrom
gpt-cmdr:upstream/layered-tiler
Open

gpt-cmdr wants to merge 3 commits into
walkerke:mainfrom
gpt-cmdr:upstream/layered-tiler

Conversation

@gpt-cmdr

Copy link
Copy Markdown

Stacked on #31 and #32: please review those first. Once they merge, this PR's diff is the last commit only.

Multi-layer freestile() calls hold every layer in memory for the whole run: all decoded features, and at each zoom every layer's tile assignment. This is the memory problem reported in #17. This PR tiles one layer at a time, so peak memory follows the largest layer instead of the sum of all layers. The output is unchanged byte for byte.

In both MVT and MLT, a tile is a sequence of independently encoded layers. Every per-layer step (clipping, snapping, drop masks, clustering, coalescing, Morton feature order) depends only on that layer. So a tile can be built by encoding each layer on its own and concatenating the encodings in layer order. The new LayeredTiler does this:

  • add_layer() runs the existing tile loop on one layer. The loop is unchanged; it is factored into generate_tiles_into(), which generate_tiles() now calls. Each tile's raw layer encoding goes to a temporary spool file, with a small tile_id -> [(offset, len)] index, and then the layer is dropped.
  • finish() reads each tile's encodings back in layer order, concatenates and gzips them, and writes the archive through the existing TileSpool / write_pmtiles_from_spool(). Assembly holds at most 64 MiB of raw tile data at a time (one oversized tile still goes alone), so this step doesn't grow with the number of layers.
  • R and Python freestile() use it for every multi-layer, non-categorical call. Single-layer calls and categorical clustering are unchanged. Generated feature IDs still continue across layers.
  • In Python, the new freestile_layers(layers, output, ...) also loads layers lazily. It takes (name, source) pairs or a generator, where a source is a GeoDataFrame, a FreestileLayer, a GeoParquet path or a zero-argument callable. This is the path-based multi-layer input asked for in Multi-layered pmtiles file without loading all layers into memory? #17. In R, the layers are already in memory as sf objects, so the saving there is the Rust copy of the features and the per-layer tile maps. I did not add an R equivalent of freestile_layers(). Happy to add one if you'd like the APIs to match.
  • gzip_level (from the stacked PR) applies to the layered path as well.
  • The R and Python parsers changed only enough to hand over one layer at a time: the loop body passes each layer to a callback instead of pushing it onto a Vec. git diff -w shows the small change.

Memory and time. Synthetic data: an n x n grid of adjacent square cells (a dense polygon coverage) in WGS84, with cell_id and one float column per layer, tiled at z10-15. Each run is a fresh process; peak working set is from psutil on Windows, 8 cores. The script is below. "Before" calls _freestile() with all layers parsed at once, which is what freestile() did with a dict of layers.

Python, 90,000 cells per layer, freestile_layers() with GeoParquet paths:

Layers Before peak After peak Archive
1 237 MiB 236 MiB identical (12.4 MB)
5 645 MiB 249 MiB identical (60.7 MB)
10 1,141 MiB 269 MiB identical (121.0 MB)

R, 40,000 cells per layer, sf objects built in the session (they stay resident), freestile() on a named list:

Layers Before peak After peak Archive
1 224 MiB 227 MiB identical
5 371 MiB 285 MiB identical

Wall time was the same within run-to-run noise (about 10% on this machine). The rest of the peak growth from 1 to 10 layers is the tile index and the Python allocator.

Validation:

  • New Rust integration test tests/layered.rs, added as a CI step. It uses five layers with different zoom ranges: two cell grids, a small grid at z12-13, lines and points. It checks byte identity with generate_pmtiles() for MVT and MLT under default snapping, no snapping, point clustering, coalescing, and drop_rate + base_zoom + gzip_level = 6, with assembly budgets of 1 byte and 1 MiB. It also checks that a tileset with no tiles fails like the in-memory path and leaves no file, that an invalid gzip_level is refused before any output, and that the spool appends correctly after reads. Byte identity with coalescing depends on the reproducible-coalesce fix this PR is stacked on.
  • R: built from source (R 4.6.1, Rtools45, CRAN feature set). I ran a 3-layer nc tileset (polygons, boundary lines, centroids) with 10 configurations: MVT and MLT x default, simplification = FALSE, drop_rate + base_zoom, clustering, and generate_ids = FALSE. The archives are byte-identical between main and this branch. Full testthat suite: 0 failures (the skips are DuckDB/GeoParquet tests the CRAN build doesn't include).
  • Python: tests/test_layered.py checks byte identity against the all-layers _freestile() call (MVT and MLT) and through freestile(), lazy sources (paths, callables, generators), and duplicate/empty refusals. test_gzip_level.py gains layered cases. Full suite: all pass. Wheel built with --no-default-features --features geoparquet, so the DuckDB tests skip.
  • tests/layered.rs was run through a small harness crate that path-depends on freestiler-core. On my Windows machine, the dev-dependency mlt-core -> fastpfor can't download CPM.cmake (TLS error), so cargo test in the crate doesn't build there. The CI step runs the test directly.
  • No new dependencies and no lockfile or vendor changes. rustfmt --check is clean on the new code (I didn't touch existing unformatted code).

Notes and limits:

  • Disk: the spool holds every layer's raw (uncompressed) tile encodings until finish(). On the 10-layer run above that was several hundred MB in the system temp directory, next to the existing tile spool.
  • Within one layer, memory is unchanged: that layer's features plus one zoom's tile map. Streaming a single large polygon layer (Possibility of streaming support for complex geometry #16) is separate work. This PR only removes the cost of stacking layers.
  • Progress output now prints a line per layer before that layer's zoom lines.

Reproduce the Python measurement:

# prep: python measure.py prep DIR 300 10
# run:  python measure.py memory|layered DIR LAYERS OUT.pmtiles   (fresh process each)
import sys, time
from pathlib import Path
import numpy as np

if sys.argv[1] == "prep":
    import geopandas as gpd, shapely
    d, n, k = Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])
    d.mkdir(parents=True, exist_ok=True)
    step = 0.0005
    i, j = np.meshgrid(np.arange(n), np.arange(n))
    x0, y0 = -77.9 + i.ravel() * step, 40.8 + j.ravel() * step
    cells = shapely.box(x0, y0, x0 + step, y0 + step)
    rng = np.random.default_rng(0)
    for layer in range(k):
        gpd.GeoDataFrame({"cell_id": np.arange(n * n),
                          "value": rng.normal(600, 5, n * n).round(3)},
                         geometry=cells, crs="EPSG:4326").to_parquet(d / f"layer{layer:02d}.parquet")
    sys.exit()

import psutil, geopandas as gpd, freestiler
mode, d, k, out = sys.argv[1], Path(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
paths = [d / f"layer{i:02d}.parquet" for i in range(k)]
t = time.perf_counter()
if mode == "memory":
    from freestiler import _preprocess_layer
    from freestiler._freestiler import _freestile
    layers = [_preprocess_layer(gpd.read_parquet(p), p.stem, 10, 15, True) for p in paths]
    _freestile(layers, out, "mvt", 10, 15, -1, True, True, True, -1.0, -1.0, -1, False)
else:
    freestiler.freestile_layers([(p.stem, str(p)) for p in paths], out,
                                min_zoom=10, max_zoom=15, quiet=True)
print(mode, k, f"{psutil.Process().memory_info().peak_wset / 2**20:.0f} MiB",
      f"{time.perf_counter() - t:.1f} s", Path(out).stat().st_size)

(peak_wset is Windows-only; on Linux/macOS use resource.getrusage(resource.RUSAGE_SELF).ru_maxrss.)

Closes #17.

I prepared this change with AI assistance (Claude Code) and reviewed it before submitting.

gpt-cmdr and others added 3 commits October 27, 2026 20:31
coalesce_features() grouped features by property hash in a HashMap and
emitted the groups in iteration order. std's HashMap is seeded per map, so
the order of coalesced features in a tile, and therefore the archive bytes,
changed from run to run. Groups now keep the order in which their first
feature appears, which is the Morton order the tile was sorted in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tiles are always gzipped at the fast level 1. A new gzip_level option (0-9)
in R and Python freestile(), and TileConfig::gzip_level in the core, sets the
level for the in-memory pipeline. None keeps level 1, so existing output is
unchanged; other levels change only the compression, never the decompressed
tiles. Out-of-range levels are refused before any output is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
freestile() with several layers held every layer's features, and every
layer's per-zoom tile assignment, in memory at once. LayeredTiler tiles each
layer on its own, spools its raw per-tile encodings to a temporary file with
a small (tile, layer) index, and at the end concatenates each tile's layer
encodings in layer order and gzips them. MVT and MLT tiles are sequences of
independently encoded layers, and every per-layer step (clipping, snapping,
dropping, clustering, coalescing, feature order) depends only on that layer,
so the archive is byte-identical to generate_pmtiles().

R and Python freestile() use it for every multi-layer call. Python's new
freestile_layers() also loads layers lazily from (name, source) pairs, where
a source is a GeoDataFrame, a FreestileLayer, a GeoParquet path or a
callable (walkerke#17).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multi-layered pmtiles file without loading all layers into memory?

1 participant