Legacy Python Pipeline¶
The original muDM tiling pipeline is a pure-Python quadtree slicer built around
TileWriter, TileReader, and the mudm2vt intermediate format. It converts a
muDM / MicroJSON FeatureCollection into a pyramid of vector tiles (JSON, PBF, or
GeoParquet) and reads them back into a FeatureCollection.
This is the legacy path
For production workloads, use the Rust-accelerated pipeline instead. It is dramatically faster (parallel tile encoding, native code) and is the recommended approach for all new projects. See 2D Tiling (Rust).
The Python pipeline described on this page remains available for backwards compatibility, small datasets, debugging, and learning the tiling data model.
When to use the legacy pipeline¶
- You want a dependency-light, pure-Python reference implementation you can step through in a debugger.
- You are working with small
FeatureCollections where raw throughput does not matter. - You need the JSON intermediate tiles for inspection, or want to read tiles back into
a muDM
FeatureCollectionwithTileReader.
If none of these apply, prefer the Rust 2D pipeline.
How it fits together¶
FeatureCollection (.json)
│
▼
TileWriter.microjson2tiles() # mudm_tools.tilewriter
│
▼
mudm2vt() → MuDMVt quadtree slicer # mudm_tools.mudm2vt.mudm2vt
│
▼
per-tile encode (JSON | PBF | Parquet) # chosen by TileWriter flags
│
▼
tiles/{z}/{x}/{y}.{json|pbf|parquet}
│
▼
TileReader.tiles2microjson() # mudm_tools.tilereader → FeatureCollection
The tile pyramid is described by a TileModel instance from
the core mudm package. Both the writer and the reader take that instance directly.
Core API¶
TileWriter and TileReader¶
TileWriter and TileReader are both subclasses of TileHandler and inherit its
constructor. There is no tilejson_path argument — you pass a fully built
mudm.tilemodel.TileModel instance, plus two independent output-format flags.
class TileHandler:
def __init__(self, tileobj: TileModel, pbf: bool = False, parquet: bool = False)
class TileWriter(TileHandler): ...
class TileReader(TileHandler): ...
| Parameter | Type | Default | Description |
|---|---|---|---|
tileobj |
mudm.tilemodel.TileModel |
— | Tile pyramid configuration (an instance, not a path). |
pbf |
bool |
False |
Encode tiles as Mapbox Vector Tile PBF (vt2pbf). |
parquet |
bool |
False |
Encode tiles as GeoParquet (GeoDataFrame.to_parquet). |
Two format flags, not one
Older docs listed only a pbf flag. The constructor takes both pbf and
parquet. The output format is chosen in microjson2tiles by precedence:
if pbf is set → PBF; else if parquet is set → Parquet; otherwise plain JSON.
After construction, a handler exposes tile_json (the TileModel), pbf, parquet,
and internal id_counter / id_set used for integer id assignment during slicing.
One vector layer only
TileWriter currently uses self.tile_json.vector_layers[0] (per an in-source
TODO); only the first vector layer is tiled. Per-layer minzoom/maxzoom are
clamped against the global TileModel zoom range.
TileWriter.microjson2tiles¶
def microjson2tiles(
self,
microjson_data_path: Union[str, Path],
validate: bool = False,
tolerance_key: str = "default",
) -> List[str]
Loads a muDM JSON file, optionally validates it, slices it into vector tiles via
mudm2vt, encodes each tile per the handler flags, writes them to the path template in
tile_json.tiles[0], and returns the list of written tile paths.
| Parameter | Type | Default | Description |
|---|---|---|---|
microjson_data_path |
str \| pathlib.Path |
— | Path to the muDM / MicroJSON FeatureCollection file. |
validate |
bool |
False |
If True, validates with MuDM.model_validate and returns [] on a ValidationError. |
tolerance_key |
str |
"default" |
Simplification tolerance-function key passed to mudm2vt as options['tolerance_function']; must be one of the AVAILABLE_TOLERANCE_FUNCTIONS keys. |
Returns: List[str] — paths to the generated tile files (empty list if validation fails).
Tolerance functions
tolerance_key selects how aggressively geometry is simplified per zoom level. The
valid keys are: default, linear, constant, slow_exponential, logarithmic,
and step. An unknown string raises ValueError. See
mudm2vt options below.
TileReader.tiles2microjson¶
Reads every tile at the given zoom level, reprojects each feature's local tile
coordinates (extent 4096) back into the global coordinate space defined by
tile_json.bounds, and aggregates them into one FeatureCollection dict.
| Parameter | Type | Default | Description |
|---|---|---|---|
zlvl |
int |
0 |
Zoom level to read. Returns {} if zlvl is outside [minzoom, maxzoom] or if bounds is None. |
Returns: dict of the form {"type": "FeatureCollection", "features": [...]} (empty
{} on out-of-range zoom or missing bounds).
Layer name and decoding
TileReader decodes PBF via mapbox_vector_tile.decode when pbf=True, otherwise
json.loads. It expects the layer name geojsonLayer inside each decoded tile, and
reads from the same {z}/{x}/{y} template as the writer.
Helper functions¶
These live in mudm_tools.tilewriter and mudm_tools.polygen.
from mudm_tools.tilewriter import getbounds, extract_fields_ranges_enums
from mudm_tools.polygen import generate_polygons
getbounds¶
Scans Polygon and MultiPolygon feature coordinates and returns the bounding box
[minx, miny, maxx, maxy]. With square=True, expands maxx/maxy so the box is
square (side = max of width/height, anchored at minx/miny). Point and LineString
geometries do not contribute to the bounds.
extract_fields_ranges_enums¶
Inspects feature properties to derive a TileJSON-style schema. Returns a 3-tuple:
field_names: dict[str, str]— field name → type string. Emitted types:String(includesNone),Boolean,Number(int/float),Object(dict),Array(list).field_ranges: dict[str, [min, max]]— numeric field ranges.field_enums: dict[str, set[str]]— string field enum sets.
field_enums returns Python sets
The field_enums values are Python set objects and are not JSON-serializable
as-is. Convert them to lists (e.g. sorted(values)) before dumping to JSON, or rely
on the TileLayer pydantic model to handle serialization for you.
The mudm2vt intermediate format¶
The quadtree slicer is mudm2vt. Mind the import layout — it is the most common
mistake when using this module:
- The top-level
mudm_tools.mudm2vtresolves to the factory function (re-exported inmudm_tools/__init__.py). - The
MuDMVtclass must be imported from the inner modulemudm_tools.mudm2vt.mudm2vt. The subpackagemudm_tools.mudm2vt.__init__contains only a license/attribution comment and exports nothing.
# Factory function (top-level convenience re-export)
from mudm_tools import mudm2vt
# The class and helpers (inner module)
from mudm_tools.mudm2vt.mudm2vt import (
MuDMVt,
mudm2vt as mudm2vt_factory,
get_default_options,
AVAILABLE_TOLERANCE_FUNCTIONS,
)
def mudm2vt(data, options, log_level=logging.INFO) # -> MuDMVt
class MuDMVt:
def __init__(self, data, options, log_level=logging.INFO)
def get_tile(self, z, x, y) # -> dict | None
def split_tile(self, features, z, x, y, cz=None, cx=None, cy=None) # -> None
MuDMVt projects the data, builds per-zoom simplified geometries, and recursively
slices a quadtree of vector tiles. Useful public attributes: .tiles (dict id → tile),
.tile_coords (list of {z, x, y}), .stats, and .total. get_tile(z, x, y) returns
the extent-scaled tile, drilling down from the nearest cached parent when the exact tile
was not pre-sliced (returns None for z < 0 or z > 24).
Default options¶
get_default_options() returns the option dict that user options are merged over:
| Key | Default | Notes |
|---|---|---|
maxZoom |
8 |
Must be 0–24 (else raises Exception). |
indexMaxZoom |
5 |
Highest zoom that is pre-sliced. |
indexMaxPoints |
100000 |
Point budget before splitting further. |
tolerance |
50 |
Base simplification tolerance. |
extent |
4096 |
Tile coordinate extent. |
buffer |
64 |
Tile buffer (in extent units). |
lineMetrics |
False |
|
promoteId |
None |
Mutually exclusive with generateId. |
generateId |
False |
Setting both promoteId and generateId raises Exception. |
projector |
None |
|
bounds |
None |
|
tolerance_function |
default_tolerance_func |
Callable, or a key in AVAILABLE_TOLERANCE_FUNCTIONS. |
AVAILABLE_TOLERANCE_FUNCTIONS maps the string keys default, linear, constant,
slow_exponential, logarithmic, step to callables of signature func(z, options) -> float.
Error semantics
maxZoomoutside0–24raisesException.- Setting both
promoteIdandgenerateIdraisesException. - An invalid
tolerance_functionstring raisesValueError. - A non-callable, non-string
tolerance_functionraisesTypeError.
Walkthrough: generate, tile, and read back¶
This end-to-end example mirrors src/mudm_tools/examples/tiling.py and
src/mudm_tools/examples/readtiles.py. Run the snippets in order from a project checkout.
Step 1 — Generate sample polygon data
generate_polygons writes a random grid of convex polygons to disk and returns the
MuDMFeatureCollection.
Correct import path
Import from mudm_tools.polygen, not microjson.polygen. The demo notebook
ships a stale from microjson.polygen import generate_polygons; that path is
wrong and will fail.
from mudm_tools.polygen import generate_polygons
GRID_SIZE = 10000 # overall grid dimension
CELL_SIZE = 100 # per-cell size (num_cells = GRID_SIZE // CELL_SIZE)
MIN_VERTICES = 10 # min vertices per polygon
MAX_VERTICES = 100 # max vertices per polygon
meta_types = {"num_vertices": "int"}
meta_values_options = {"polytype": ["Type1", "Type2", "Type3", "Type4"]}
mudm_data_path = "example_generated.json"
generate_polygons(
GRID_SIZE,
CELL_SIZE,
MIN_VERTICES,
MAX_VERTICES,
meta_types,
meta_values_options,
mudm_data_path,
)
print(f"Generated polygon data saved to {mudm_data_path}")
generate_polygons takes its arguments positionally, validates the resulting
MuDMFeatureCollection, and writes it via model_dump_json(indent=2).
Step 2 — Extract fields, ranges, and enums
from mudm_tools.tilewriter import extract_fields_ranges_enums
field_names, field_ranges, field_enums = extract_fields_ranges_enums(mudm_data_path)
print(field_names) # {'num_vertices': 'Number', 'polytype': 'String'}
print(field_ranges) # {'num_vertices': [10, 24]}
print(field_enums) # {'polytype': {'Type1', 'Type2', 'Type3', 'Type4'}}
Step 3 — Define the vector layer
Build a TileLayer from the extracted schema. (The
pydantic model serializes the enum set to a JSON array for you.)
Step 4 — Compute bounds and build the TileModel
import os
from pathlib import Path
from mudm.tilemodel import TileJSON, TileModel
from mudm_tools.tilewriter import getbounds
os.makedirs("tiles", exist_ok=True)
# square=True makes the bounding box square (good for a tile pyramid)
maxbounds = getbounds(mudm_data_path, square=True)
center = [0, (maxbounds[0] + maxbounds[2]) / 2, (maxbounds[1] + maxbounds[3]) / 2]
tile_model = TileModel(
tilejson="3.0.0",
tiles=[Path("tiles/{z}/{x}/{y}.pbf")], # path template; {z}/{x}/{y} are filled in
name="Example Tile Layer",
description="A TileJSON example incorporating muDM data",
version="1.0.0",
attribution="Polus AI",
minzoom=0,
maxzoom=7,
bounds=maxbounds,
center=center,
vector_layers=vector_layers,
)
# Optional: persist the TileJSON metadata for viewers / the reader
tileobj = TileJSON(root=tile_model)
with open("tiles/metadata.json", "w") as f:
f.write(tileobj.model_dump_json(indent=2))
The tiles[0] template is what TileWriter formats with each tile's {z}, {x},
and {y}. The .pbf suffix here matches the pbf=True writer flag below — see the
output layout.
Step 5 — Write the tiles
from mudm_tools.tilewriter import TileWriter
writer = TileWriter(tile_model, pbf=True) # PBF output
written = writer.microjson2tiles(mudm_data_path, validate=False)
print(f"Wrote {len(written)} tiles")
Swap the flags to change the format:
Step 6 — Read the tiles back into a FeatureCollection
This mirrors src/mudm_tools/examples/readtiles.py: load the saved metadata,
rebuild a TileModel, and reproject one zoom level back to global coordinates.
import json
from mudm.tilemodel import TileModel
from mudm_tools.tilereader import TileReader
with open("tiles/metadata.json", "r") as f:
tilejson_data = json.load(f)
tile_model = TileModel.model_validate(tilejson_data)
# Match the writer's format flag (pbf=True here because we wrote PBF tiles)
reader = TileReader(tile_model, pbf=True)
fc = reader.tiles2microjson(zlvl=0)
print(fc["type"], len(fc.get("features", [])))
Match the format flag
Construct TileReader with the same pbf / parquet flag you used for the
writer, so it decodes the on-disk tiles correctly.
Running the bundled examples¶
The reference scripts live under src/mudm_tools/examples/ and run as modules:
Note
examples/tiling.py clears and recreates a local tiles/ directory, then writes
tiles/metadata.json and the PBF tile tree. examples/readtiles.py loads
tiles/metadata.json, calls tiles2microjson(zlvl=0), and saves the result to
tiles/microjson_data_read.json.
Output layout¶
TileWriter.microjson2tiles writes one file per tile using the path template from
tile_json.tiles[0], with {z}, {x}, {y} filled in. The handler flags pick the
file format:
<tiles dir from tile_json.tiles[0] template>/
{z}/{x}/{y}.json # default — json.dumps of the tile dict
{z}/{x}/{y}.pbf # pbf=True — vt2pbf-encoded Mapbox Vector Tile
{z}/{x}/{y}.parquet # parquet=True — GeoDataFrame.to_parquet (geometry-only)
TileReader reads back from the same {z}/{x}/{y} template.
Migrating to the Rust pipeline¶
When you outgrow the legacy path, the Rust 2D pipeline is a near-drop-in
replacement: it slices the same FeatureCollection data into the same {z}/{x}/{y}.pbf
and tiled-Parquet layouts, but in parallel native code. The
TileJSON reference describes the shared TileModel /
TileLayer / TileJSON configuration models used by both pipelines.
API reference (autodoc)¶
TileWriter
¶
TileWriter(
tileobj: TileModel,
pbf: bool = False,
parquet: bool = False,
)
Bases: TileHandler
Source code in src/mudm_tools/tilehandler.py
microjson2tiles
¶
microjson2tiles(
microjson_data_path: Union[str, Path],
validate: bool = False,
tolerance_key: str = "default",
) -> List[str]
Generate tiles in form of JSON or PBF files from MuDM data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
microjson_data_path
|
Union[str, Path]
|
Path to the |
required |
validate
|
bool
|
Flag to indicate whether to validate |
False
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: List of paths to the generated tiles |
Source code in src/mudm_tools/tilewriter.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
getbounds
¶
Get the max and min bounds for coordinates of the MuDM file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
microjson_file
|
str
|
Path to the MuDM file |
required |
square
|
bool
|
Flag to indicate whether to return square bounds |
False
|
Returns:
| Type | Description |
|---|---|
List[float]
|
List[float]: List of the bounds [minx, miny, maxx, maxy] |
Source code in src/mudm_tools/tilewriter.py
extract_fields_ranges_enums
¶
Extract field names, ranges, and enums from the provided MuDM file. Returns: tuple: (dict with field names and types, dict of field ranges, dict of field enums)
Source code in src/mudm_tools/tilewriter.py
TileReader
¶
TileReader(
tileobj: TileModel,
pbf: bool = False,
parquet: bool = False,
)
Bases: TileHandler
Class to read tiles and generate MuDM data
Source code in src/mudm_tools/tilehandler.py
tiles2microjson
¶
Generate MuDM data from tiles in form of JSON or PBF files. Get the TileJSON configuration and the PBF flag from the class attributes. Check that zlvl is within the maxzoom and minzoom of the tilejson Get the bounds from the tilejson and use to generate the MuDM data, by reading the tiles at the specified zoom level and extracting the geometries from the tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zlvl
|
int
|
The zoom level of the tiles to read |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
The generated MuDM data |
Source code in src/mudm_tools/tilereader.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
TileHandler
¶
TileHandler(
tileobj: TileModel,
pbf: bool = False,
parquet: bool = False,
)
Class to handle the generation of tiles from MuDM data
Initialize the TileHandler with a TileJSON configuration and optional PBF flag
Args: tileobj (TileModel): TileJSON configuration pbf (bool): Flag to indicate whether to encode the tiles in PBF
Source code in src/mudm_tools/tilehandler.py
MuDMVt
¶
MuDMVt class, which is the main class for generating vector tiles from MuDM data
Constructor for MuDMVt class
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
The data to be converted to vector tiles |
required |
options
|
dict
|
The options to be used for generating vector tiles |
required |
log_level
|
int
|
The logging level to be used |
INFO
|
Source code in src/mudm_tools/mudm2vt/mudm2vt.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
split_tile
¶
Splits features from a parent tile to sub-tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
list
|
The features to be split |
required |
z
|
int
|
The zoom level of the parent tile |
required |
x
|
int
|
The x coordinate of the parent tile |
required |
y
|
int
|
The y coordinate of the parent tile |
required |
cz
|
int
|
The zoom level of the target tile |
None
|
cx
|
int
|
The x coordinate of the target tile |
None
|
cy
|
int
|
The y coordinate of the target tile |
None
|
Source code in src/mudm_tools/mudm2vt/mudm2vt.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
mudm2vt
¶
Converts MuDM data to intermediate vector tiles
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
The MuDM data to be converted to vector tiles |
required |
options
|
dict
|
The options to be used for generating vector tiles |
required |
log_level
|
int
|
The logging level to be used |
INFO
|
Source code in src/mudm_tools/mudm2vt/mudm2vt.py
get_default_options
¶
Source code in src/mudm_tools/mudm2vt/mudm2vt.py
generate_polygons
¶
generate_polygons(
grid_size,
cell_size,
min_vertices,
max_vertices,
meta_types,
meta_values_options,
microjson_data_path,
) -> MuDMFeatureCollection
Source code in src/mudm_tools/polygen.py
See also¶
- 2D Tiling (Rust) — the recommended, faster pipeline.
- TileJSON reference —
TileModel,TileLayer,TileJSONmodels.