Skip to content

Map site

A self-contained, archivable map site built from one run's outputs.

build_site(run_dir) writes <run_dir>/site/ — an HTML page, a vendored MapLibre front end, PMTiles tilesets and a copy of the run manifest. It opens with a Python interpreter and nothing else, reaches no network, and needs no API key.

See lczkit.viz.site for what it contains and why, and lczkit.viz.serve for why a local server is required rather than a bare file:// open.

A static web map written to output/lczkit/<run_id>/site/. It is drawn by MapLibre GL, a browser mapping library, reading PMTiles — a single-file tile archive served over ordinary HTTP range requests, so no tile server is needed. The tiles are built by tippecanoe, a command-line tool installed by the lczkit[viz] extra and invoked as a subprocess. The front end is vendored, so the site depends on nothing remote.

The site opens with no network and no software the user must install. It is served by its own bundled serve.py, standard library only, over loopback.

file:// does not work, and that is not fixable

PMTiles reads byte ranges through fetch, and the Fetch standard leaves file: URLs unhandled — Chrome and Firefox both return a network error. Every built site ships a README.md giving the working command, because opening index.html is the first thing a recipient tries and it is the thing that fails.

The basemap is the run's own cleaned Overture water and streets: already cached for the bbox, ODbL-attributable, and the same linework the classification was computed from. Online raster grounds are available opt-in via VizConfig.online_basemaps, one or several, offered to the reader as a dropdown; with it empty the emitted site names no remote host anywhere, and that default is enforced by a test rather than promised in prose. Two of the providers need an API key, which is written into style.json and therefore travels with the built site — see VizConfig.maptiler_key for what that does and does not bound.

lczkit.viz.site

build_site(run_dir) — a self-contained, archivable map of one run.

The deliverable is a directory that a reader can copy, open with a Python interpreter and nothing else, and still read in ten years: no CDN, no basemap API key, no live kernel, no build step. It is a paper supplement, not a dev tool.

It is a pure transform of run outputs. Every number it draws — labels, parameters, the 17-way distance vector, the classification breaks the choropleths bin on — was decided by the run and read back from units.parquet, units_viz.parquet and manifest.json. Nothing here computes a parameter or a quantile, and nothing here reads input/. That is why write_run gained a layers= argument: the basemap and the extrusions are drawn from geometry the run persisted, so an archived run directory rebuilds its own site with no access to the source data.

The one thing that is measured rather than assumed is the attribute split. MVT repeats a feature's whole attribute table in every tile at every zoom, so at metropolitan scale a 38-column unit table costs more to tile than 892 000 building footprints — 115 MB against 61 MB. The render attributes therefore ride at every zoom and the rest ride once, at the maximum zoom, where the only thing that reads them is a click. Both tilesets and the choice between them are recorded in site.json.

ASSETS_DIR module-attribute

ASSETS_DIR = Path(__file__).resolve().parent / 'assets'

The vendored front end, shipped inside the wheel.

This is the one place in the package that resolves a path from __file__. The rule against that is about locating data relative to the source tree, because data lives under DATA_DIR. These are package resources — JavaScript and HTML that ship in the wheel — and there is no other way to find a file inside an installed package.

BASEMAP_LAYERS module-attribute

BASEMAP_LAYERS = ('land_use', 'water', 'streets')

Context layers drawn under the units, in draw order.

Tiled as geometry alone. They are painted flat, carry no labels, and answer no click, so every attribute on them is dead weight — and it is not small dead weight: Overture's id is a 32-character GERS string, repeated once per feature per zoom level. Stripping the columns took a 9 km² basemap from 6.43 MB to 4.00 MB, for pixels that look identical.

SiteReport dataclass

SiteReport(site_dir: Path, tilesets: list[TilesetReport] = list(), n_units: int = 0, render_columns: list[str] = list(), detail_columns: list[str] = list(), skipped: dict[str, str] = dict())

What build_site wrote, and how.

skipped class-attribute instance-attribute

skipped: dict[str, str] = field(default_factory=dict)

Anything the site could not draw, and why — an absent layer, a detail tileset declined for size. Recorded rather than silently omitted, so a missing basemap is distinguishable from a basemap that failed.

as_dict

as_dict() -> dict[str, Any]

The report as JSON-ready primitives, for the run manifest's site block.

Source code in src/lczkit/viz/site.py
def as_dict(self) -> dict[str, Any]:
    """The report as JSON-ready primitives, for the run manifest's `site` block."""
    return {
        "site_dir": str(self.site_dir),
        "n_units": self.n_units,
        "render_columns": self.render_columns,
        "detail_columns": self.detail_columns,
        "skipped": self.skipped,
        "tilesets": [tileset.as_detail() for tileset in self.tilesets],
        "total_bytes": sum(tileset.size_bytes for tileset in self.tilesets),
    }

build_site

build_site(run_dir: Path | str, *, config: VizConfig | None = None) -> SiteReport

Write <run_dir>/site/ from the run's own outputs, returning what was built.

config defaults to the viz section recorded in the run's manifest, so rebuilding a site from an archived run reproduces the same tilesets without the caller having to restate the settings.

Source code in src/lczkit/viz/site.py
def build_site(run_dir: Path | str, *, config: VizConfig | None = None) -> SiteReport:
    """Write `<run_dir>/site/` from the run's own outputs, returning what was built.

    `config` defaults to the `viz` section recorded in the run's manifest, so rebuilding a site from
    an archived run reproduces the same tilesets without the caller having to restate the settings.
    """
    run_dir = Path(run_dir)
    manifest = json.loads((run_dir / MANIFEST_FILE).read_text(encoding="utf-8"))
    if config is None:
        config = VizConfig.model_validate(manifest.get("config", {}).get("viz", {}))

    units = gpd.read_parquet(run_dir / UNITS_FILE, columns=["geometry"])
    attributes = pd.read_parquet(run_dir / VIZ_FILE)
    table = gpd.GeoDataFrame(
        attributes.join(units[["geometry"]], how="inner"), geometry="geometry", crs=units.crs
    )
    table = table.reset_index().rename(columns={table.index.name or "index": "unit_id"})

    site_dir = run_dir / SITE_DIR
    tiles_dir = site_dir / "tiles"
    site_dir.mkdir(parents=True, exist_ok=True)
    tiles_dir.mkdir(parents=True, exist_ok=True)

    skipped: dict[str, str] = {}
    tilesets: list[TilesetReport] = []

    render_columns = _render_columns(list(table.columns), config)
    missing = sorted(set(config.render_columns) - set(render_columns))
    if missing:
        skipped["render_columns"] = f"not produced by this run: {', '.join(missing)}"

    tilesets.append(
        build_tileset(
            {"units": table[["unit_id", *render_columns, "geometry"]]},
            tiles_dir / "units.pmtiles",
            name="units",
            min_zoom=config.unit_min_zoom,
            max_zoom=config.unit_max_zoom,
        )
    )

    detail_columns = [
        column for column in table.columns if column not in {*render_columns, "unit_id", "geometry"}
    ]
    has_detail = bool(detail_columns) and len(table) <= config.detail_max_features
    if detail_columns and not has_detail:
        skipped["units_detail"] = (
            f"{len(table)} units exceeds detail_max_features={config.detail_max_features}; "
            "the sidebar falls back to the render attributes"
        )
    if has_detail:
        tilesets.append(
            build_tileset(
                {"units_detail": table[["unit_id", *detail_columns, "geometry"]]},
                tiles_dir / "units_detail.pmtiles",
                name="units_detail",
                min_zoom=config.unit_max_zoom,
                max_zoom=config.unit_max_zoom,
                # A dropped feature here is a unit whose sidebar silently comes up empty, which is
                # worse than a large tile — this tileset is only ever read one feature at a time.
                drop_densest=False,
            )
        )

    wanted = tuple(name for name in BASEMAP_LAYERS if name in config.basemap_layers)
    basemap = {name: frame[["geometry"]] for name, frame in _read_layers(run_dir, wanted).items()}
    if basemap:
        tilesets.append(
            build_tileset(
                basemap,
                tiles_dir / "basemap.pmtiles",
                name="basemap",
                min_zoom=config.basemap_min_zoom,
                max_zoom=config.basemap_max_zoom,
                simplification=config.basemap_simplification,
            )
        )
    else:
        skipped["basemap"] = (
            f"none of {', '.join(wanted) or 'the configured layers'} was persisted by this run; "
            "pass layers= to write_run to draw a basemap"
        )

    has_buildings = False
    if config.include_buildings:
        buildings = _read_layers(run_dir, ("buildings",))
        if buildings:
            tilesets.append(
                build_tileset(
                    {"buildings": _building_columns(buildings["buildings"])},
                    tiles_dir / "buildings.pmtiles",
                    name="buildings",
                    min_zoom=config.building_min_zoom,
                    max_zoom=config.building_max_zoom,
                )
            )
            has_buildings = True
        else:
            skipped["buildings"] = (
                "include_buildings is set but the run persisted no building layer"
            )

    bounds = table.to_crs(4326).total_bounds
    style = style_module.build_style(
        manifest,
        columns=["unit_id", *render_columns],
        bounds=(float(bounds[0]), float(bounds[1]), float(bounds[2]), float(bounds[3])),
        centre=(float((bounds[0] + bounds[2]) / 2), float((bounds[1] + bounds[3]) / 2)),
        has_detail=has_detail,
        basemap_layers=tuple(basemap),
        has_buildings=has_buildings,
        online_basemaps=config.basemap_keys,
        maptiler_key=_resolve_api_key(config),
    )

    # `index.html` sits at the root because that is where a browser looks; everything it pulls in
    # lives under `assets/`, so the directory says at a glance what is page and what is machinery.
    copy_tree(ASSETS_DIR / "vendor", site_dir / "assets" / "vendor")
    shutil.copy2(ASSETS_DIR / "index.html", site_dir / "index.html")
    for name in ("app.js", "app.css", "LICENSES.md"):
        shutil.copy2(ASSETS_DIR / name, site_dir / "assets" / name)
    shutil.copy2(Path(__file__).resolve().parent / "serve.py", site_dir / "serve.py")
    # At the root beside `serve.py`, not under `assets/`: it is addressed to whoever receives the
    # directory, and the one thing they need to know is that opening `index.html` will not work.
    shutil.copy2(ASSETS_DIR / "README.md", site_dir / "README.md")
    shutil.copy2(run_dir / MANIFEST_FILE, site_dir / MANIFEST_FILE)
    (site_dir / "style.json").write_text(json.dumps(style, indent=2) + "\n", encoding="utf-8")

    report = SiteReport(
        site_dir=site_dir,
        tilesets=tilesets,
        n_units=len(table),
        render_columns=render_columns,
        detail_columns=detail_columns if has_detail else [],
        skipped=skipped,
    )
    (site_dir / SITE_REPORT).write_text(
        json.dumps(report.as_dict(), indent=2) + "\n", encoding="utf-8"
    )
    return report

distance_columns_present

distance_columns_present(columns: list[str]) -> list[str]

The 17-way distance columns among columns, in prototype order.

Exposed so the sidebar's bar chart and the tests agree on the ordering without either re-deriving it from a column name pattern.

Source code in src/lczkit/viz/site.py
def distance_columns_present(columns: list[str]) -> list[str]:
    """The 17-way distance columns among `columns`, in prototype order.

    Exposed so the sidebar's bar chart and the tests agree on the ordering without either
    re-deriving it from a column name pattern.
    """
    return [column for column in DISTANCE_COLUMNS if column in columns]

Tilesets

Attributes, not geometry, are what a unit tileset costs. MVT repeats a feature's whole attribute table in every tile at every zoom, so at 172 181 units a 38-column table costs more to tile than 892 000 building footprints. Hence the render/detail split: render attributes at every zoom, the rest once at maximum zoom where only a click reads them.

lczkit.viz.tiles

Vector tiles: GeoParquet in a GeoDataFrame, PMTiles out, tippecanoe in between.

The chain is GeoParquet -> FlatGeobuf via pyogrio -> tippecanoe -> PMTiles. Routing through GeoJSON instead is dramatically slower at buildings scale and is not used. tippecanoe is a subprocess, never linked or vendored, and it is an optional extra (lczkit[viz]) so that the classification pipeline does not acquire a 36 MB binary it never calls.

The binary is located through the installed package, not PATH. The tippecanoe PyPI wheel ships the real upstream binaries under tippecanoe.BIN_DIR, and resolving them that way means the version tippecanoe reports is the version the lockfile pinned. A PATH lookup would silently prefer whatever a system package manager had put there, which is exactly the reproducibility hole the manifest exists to close.

Every invocation is recorded verbatim, argv and all, in the site manifest. A recorded command line is the only way a reader can tell a tile that is empty because the data was empty from one that is empty because --drop-densest-as-needed threw it away.

tippecanoe's thread count is capped, and that is a bug workaround with a measurement behind it. On this project's 256-core node every tileset failed with Internal error: 745 shards not a power of 2, raised from tippecanoe's radix sort while reordering geometry. Sweeping the thread count showed 8, 16, 32, 48, 64, 96, 128 and 192 all succeed and only 256 fails, so the shard arithmetic breaks at the top of the range rather than at a particular value. Decoding two tilesets built at 8 and 128 threads showed identical tile content — the only bytes that differ are the output filename tippecanoe records in its own metadata — so capping costs nothing but wall time, and tile generation is minutes rather than hours. Like the multiprocessing start-method choice in lczkit.cleaning.streets, this is invisible on a laptop and fatal on a many-core machine.

TIPPECANOE_EXTRA module-attribute

TIPPECANOE_EXTRA = 'lczkit[viz]'

Install target named in the error when the binary is missing. One string, so the message and the packaging cannot drift apart.

MAX_THREADS module-attribute

MAX_THREADS = 32

Ceiling on tippecanoe's worker threads. See the module docstring: above roughly this, the gain is nil and at 256 the shard arithmetic fails outright. An operator who has already set TIPPECANOE_MAX_THREADS keeps their value — this is a floor under a broken default, not a policy about how many cores anyone may use.

TippecanoeMissingError

Bases: RuntimeError

Raised when a tileset is requested but tippecanoe is not installed.

TilesetReport dataclass

TilesetReport(name: str, path: Path, layers: tuple[str, ...], n_features: int, size_bytes: int, min_zoom: int, max_zoom: int, argv: tuple[str, ...], version: str, max_threads: str, seconds: float)

One tileset, and exactly how it was produced.

argv instance-attribute

argv: tuple[str, ...]

The full command line, including the binary's resolved path.

max_threads instance-attribute

max_threads: str

The TIPPECANOE_MAX_THREADS the run used. Recorded because it is a workaround for a machine-dependent failure, and a reader comparing two runs should be able to see it.

as_detail

as_detail() -> dict[str, object]

One tileset's row for the manifest: what was built, how big, and at which zooms.

Source code in src/lczkit/viz/tiles.py
def as_detail(self) -> dict[str, object]:
    """One tileset's row for the manifest: what was built, how big, and at which zooms."""
    return {
        "name": self.name,
        "file": self.path.name,
        "layers": list(self.layers),
        "n_features": self.n_features,
        "size_bytes": self.size_bytes,
        "min_zoom": self.min_zoom,
        "max_zoom": self.max_zoom,
        "seconds": round(self.seconds, 2),
        "tippecanoe_version": self.version,
        "tippecanoe_max_threads": self.max_threads,
        "tippecanoe_argv": list(self.argv),
    }

tippecanoe_binary

tippecanoe_binary() -> Path

Path to the pinned tippecanoe executable, or a message saying how to get one.

Source code in src/lczkit/viz/tiles.py
def tippecanoe_binary() -> Path:
    """Path to the pinned `tippecanoe` executable, or a message saying how to get one."""
    try:
        import tippecanoe
    except ModuleNotFoundError as error:
        raise TippecanoeMissingError(
            "tippecanoe is required to build a map site and is not installed. "
            f"Install the viz extra: pip install '{TIPPECANOE_EXTRA}'"
        ) from error
    binary = Path(tippecanoe.BIN_DIR) / "tippecanoe"
    if not binary.is_file():
        raise TippecanoeMissingError(
            f"the tippecanoe package is installed but {binary} is missing; "
            f"reinstall it: pip install --force-reinstall '{TIPPECANOE_EXTRA}'"
        )
    return binary

tippecanoe_available

tippecanoe_available() -> bool

Whether a tileset can be built here. For skipping tests, not for silently degrading.

Source code in src/lczkit/viz/tiles.py
def tippecanoe_available() -> bool:
    """Whether a tileset can be built here. For skipping tests, not for silently degrading."""
    try:
        tippecanoe_binary()
    except TippecanoeMissingError:
        return False
    return True

tippecanoe_version

tippecanoe_version() -> str

The version string the pinned binary reports, for the manifest.

Source code in src/lczkit/viz/tiles.py
def tippecanoe_version() -> str:
    """The version string the pinned binary reports, for the manifest."""
    result = subprocess.run(
        [str(tippecanoe_binary()), "--version"], capture_output=True, text=True, check=False
    )
    # tippecanoe prints its version banner on stderr and exits non-zero for `--version`.
    return (
        (result.stderr or result.stdout).strip().splitlines()[0]
        if result.stderr or result.stdout
        else "unknown"
    )

tippecanoe_environment

tippecanoe_environment() -> dict[str, str]

The subprocess environment, with the thread ceiling applied unless already set.

Source code in src/lczkit/viz/tiles.py
def tippecanoe_environment() -> dict[str, str]:
    """The subprocess environment, with the thread ceiling applied unless already set."""
    environment = dict(os.environ)
    if THREAD_LIMIT_VAR not in environment:
        # `sched_getaffinity` rather than `cpu_count`, matching `cleaning.streets`: on a scheduled
        # HPC node the affinity mask is the allocation, and the machine's core count is not.
        environment[THREAD_LIMIT_VAR] = str(min(len(os.sched_getaffinity(0)), MAX_THREADS))
    return environment

write_flatgeobuf

write_flatgeobuf(frame: GeoDataFrame, path: Path) -> int

Write frame to FlatGeobuf in EPSG:4326, returning the feature count.

Reprojected here rather than by the caller because tippecanoe reads coordinates as lon/lat and has no CRS machinery of its own: handing it the projected CRS every other stage of this package computes in would produce a tileset covering a few square metres off the coast of Africa, and it would do so without complaining.

Source code in src/lczkit/viz/tiles.py
def write_flatgeobuf(frame: gpd.GeoDataFrame, path: Path) -> int:
    """Write `frame` to FlatGeobuf in EPSG:4326, returning the feature count.

    Reprojected here rather than by the caller because tippecanoe reads coordinates as lon/lat and
    has no CRS machinery of its own: handing it the projected CRS every other stage of this package
    computes in would produce a tileset covering a few square metres off the coast of Africa, and it
    would do so without complaining.
    """
    if frame.crs is None:
        raise ValueError(f"{path.name}: cannot tile a layer with no CRS")
    exported = frame.to_crs(4326) if frame.crs.to_epsg() != 4326 else frame
    exported = exported[~exported.geometry.is_empty & exported.geometry.notna()]
    pyogrio.write_dataframe(exported, path, driver="FlatGeobuf")
    return len(exported)

build_tileset

build_tileset(layers: dict[str, GeoDataFrame], destination: Path, *, name: str, min_zoom: int, max_zoom: int, drop_densest: bool = True, simplification: int | None = None) -> TilesetReport

Tile one or more named layers into a single .pmtiles at destination.

Several layers in one tileset rather than one file each: a basemap's water, land use and streets are always drawn together, and MapLibre re-requests tiles per source, so splitting them would triple the request count for tiles that always arrive together anyway.

drop_densest is --drop-densest-as-needed, which drops features from tiles that would blow the size limit rather than emitting a tile a browser cannot parse. It is on for everything except the click-detail tileset, where a dropped feature is a unit whose sidebar would silently come up empty — there the right failure is a large tile, not a missing one.

simplification is passed only for the basemap. Context geometry carries no measurement, so it is the one thing in the site that may be coarsened for display; the unit and building tilesets keep tippecanoe's faithful default, because their vertices are the run's own output.

Source code in src/lczkit/viz/tiles.py
def build_tileset(
    layers: dict[str, gpd.GeoDataFrame],
    destination: Path,
    *,
    name: str,
    min_zoom: int,
    max_zoom: int,
    drop_densest: bool = True,
    simplification: int | None = None,
) -> TilesetReport:
    """Tile one or more named layers into a single `.pmtiles` at `destination`.

    Several layers in one tileset rather than one file each: a basemap's water, land use and streets
    are always drawn together, and MapLibre re-requests tiles per *source*, so splitting them would
    triple the request count for tiles that always arrive together anyway.

    `drop_densest` is `--drop-densest-as-needed`, which drops features from tiles that would blow
    the size limit rather than emitting a tile a browser cannot parse. It is on for everything
    except the click-detail tileset, where a dropped feature is a unit whose sidebar would silently
    come up empty — there the right failure is a large tile, not a missing one.

    `simplification` is passed only for the basemap. Context geometry carries no measurement, so it
    is the one thing in the site that may be coarsened for display; the unit and building tilesets
    keep tippecanoe's faithful default, because their vertices are the run's own output.
    """
    binary = tippecanoe_binary()
    environment = tippecanoe_environment()
    destination.parent.mkdir(parents=True, exist_ok=True)
    started = time.perf_counter()

    with tempfile.TemporaryDirectory(prefix="lczkit-tiles-") as scratch:
        inputs: list[str] = []
        n_features = 0
        for layer_name, frame in layers.items():
            source = Path(scratch) / f"{layer_name}.fgb"
            n_features += write_flatgeobuf(frame, source)
            inputs += ["--named-layer", f"{layer_name}:{source}"]

        argv = [
            str(binary),
            "--output",
            str(destination),
            "--minimum-zoom",
            str(min_zoom),
            "--maximum-zoom",
            str(max_zoom),
            "--force",
            "--quiet",
            # The per-layer statistics tippecanoe embeds are a second, coarser copy of the run's
            # own breaks. The site reads the manifest's, so shipping these would be a second
            # answer to a question the run already answered.
            "--no-tile-stats",
            *(
                ["--drop-densest-as-needed"]
                if drop_densest
                else ["--no-feature-limit", "--no-tile-size-limit"]
            ),
            *([f"--simplification={simplification}"] if simplification else []),
            *inputs,
        ]
        completed = subprocess.run(
            argv, capture_output=True, text=True, check=False, env=environment
        )
        if completed.returncode != 0:
            raise RuntimeError(
                f"tippecanoe failed for tileset {name!r} (exit {completed.returncode}, "
                f"{THREAD_LIMIT_VAR}={environment[THREAD_LIMIT_VAR]}):\n"
                f"{completed.stderr.strip()}"
            )

    return TilesetReport(
        name=name,
        path=destination,
        layers=tuple(layers),
        n_features=n_features,
        size_bytes=destination.stat().st_size,
        min_zoom=min_zoom,
        max_zoom=max_zoom,
        argv=tuple(argv),
        version=tippecanoe_version(),
        max_threads=environment[THREAD_LIMIT_VAR],
        seconds=time.perf_counter() - started,
    )

copy_tree

copy_tree(source: Path, destination: Path) -> None

Copy a vendored asset directory into a site, replacing whatever was there.

Source code in src/lczkit/viz/tiles.py
def copy_tree(source: Path, destination: Path) -> None:
    """Copy a vendored asset directory into a site, replacing whatever was there."""
    if destination.exists():
        shutil.rmtree(destination)
    shutil.copytree(source, destination)

Style

lczkit.viz.style

The MapLibre style, built in Python from a run manifest.

Why the style is generated here and not in JavaScript. The site never recomputes a parameter or a quantile — it renders what the run already decided. Building the style in Python makes that constraint testable: a test can assert that every LCZ colour equals classify.labels.legend() and that every choropleth's class boundaries are the manifest's own breaks, with nothing derived at draw time. The same assertions written against app.js would be assertions about a string.

It also keeps the browser code to what only the browser can do — pan, click, and toggle. app.js loads style.json, and switching a view calls setPaintProperty on one already-loaded layer, so no view change ever refetches a tile.

No glyphs and no sprite. MapLibre fetches both over HTTP when a style names them, and a style with neither is a style that cannot reach for anything outside the directory. The cost is that the map carries no text labels; for a class map with a legend that is a small price, and it is the difference between a directory that renders in ten years and one that renders until a font endpoint moves.

NODATA_COLOUR module-attribute

NODATA_COLOUR = '#3a3a3a'

Units with no value for the active variable. Deliberately not a ramp colour and not the background: a null parameter is a real and reportable state — aspect_ratio is null wherever no street reaches a building — and painting it as though it were a low value would hide that.

UNITS_FILL_LAYER module-attribute

UNITS_FILL_LAYER = 'units-fill'

The single layer every view paints. One layer rather than one per variable so that switching a view is a paint change over tiles already in memory rather than a refetch.

RASTER_BASEMAP_PREFIX module-attribute

RASTER_BASEMAP_PREFIX = 'basemap-raster-'

Leading string of every remote raster's source and layer id, which are the same string.

Only raster_id may use it, and nothing may match on it. The site's own linework layers are also basemap-*, and collecting them by prefix once put the remote raster into the choice that exists precisely to avoid the network. Both sets are built from the decision that separates them — see metadata.lczkit.basemap below.

GROUP_CONFIDENCE module-attribute

GROUP_CONFIDENCE = 'Confidence'

Selector groups, in the order selector_rank already puts their members in.

The groups are named here rather than derived in the front end for the same reason the labels are: the ordering is a decision this package made and a test asserts, and a second copy of it in JavaScript would be a second place for it to be wrong.

REGISTRY_LABELS module-attribute

REGISTRY_LABELS: dict[str, str] = {spec.name: spec.label for spec in PARAMETERS}

ParameterSpec.label for every parameter this version of the package knows about.

Consulted when a run's own manifest carries no label, which older runs do — including the three published ones. Without it, rebuilding an archived site with a newer lczkit would keep showing the labels the rebuild was meant to fix.

display_label

display_label(column: str, parameters: dict[str, str]) -> str

The human-readable name for column, or a readable fallback.

parameters maps a column to the label the run recorded. A run written before labels existed carries none, so the packaged registry answers next — otherwise rebuilding an archived run's site with a newer lczkit would still show "height of roughness elements m", and the three published sites are exactly such runs.

That is not the site recomputing something the run decided. A display name is presentation, not a measurement: the values, the breaks and the colours still come from the manifest, and DISPLAY_LABELS and HEIGHT_SOURCE_LABELS below already answer from the package. The run's own label still wins where it has one, so a manifest that named a column differently keeps its name.

Source code in src/lczkit/viz/style.py
def display_label(column: str, parameters: dict[str, str]) -> str:
    """The human-readable name for `column`, or a readable fallback.

    `parameters` maps a column to the `label` the *run* recorded. A run written before labels
    existed carries none, so the packaged registry answers next — otherwise rebuilding an archived
    run's site with a newer lczkit would still show "height of roughness elements m", and the three
    published sites are exactly such runs.

    That is not the site recomputing something the run decided. A display name is presentation, not
    a measurement: the values, the breaks and the colours still come from the manifest, and
    `DISPLAY_LABELS` and `HEIGHT_SOURCE_LABELS` below already answer from the package. The run's own
    label still wins where it has one, so a manifest that named a column differently keeps its name.
    """
    if column in parameters:
        return parameters[column]
    if column in REGISTRY_LABELS:
        return REGISTRY_LABELS[column]
    if column in DISPLAY_LABELS:
        return DISPLAY_LABELS[column]
    if column.startswith(FRACTION_PREFIX):
        source = column[len(FRACTION_PREFIX) :]
        return HEIGHT_SOURCE_LABELS.get(source, source.replace("_", " "))
    return column.replace("_", " ")

selector_group

selector_group(column: str) -> str

Which selector group column belongs to. Follows selector_rank, not a second ordering.

Source code in src/lczkit/viz/style.py
def selector_group(column: str) -> str:
    """Which selector group `column` belongs to. Follows `selector_rank`, not a second ordering."""
    if column == "lcz_primary":
        return GROUP_CLASSIFICATION
    if column == HEIGHT_COMPLETENESS_COLUMN or column.startswith(FRACTION_PREFIX):
        return GROUP_PROVENANCE
    if column == UNIQUENESS_COLUMN:
        return GROUP_CONFIDENCE
    return GROUP_PARAMETERS

selector_rank

selector_rank(column: str) -> tuple[int, int]

Where column sits in the layer selector.

The order is chosen here, not inherited. build_views used to emit views in whatever order the manifest's breaks arrived in, which is writer.py's continuous — every numeric column in DataFrame order. That is incidental, and it put height provenance last, below ten urban canopy parameters. height_completeness and height_tier_fractions are first-class layers and sit second in the selector, above the UCP choropleths. They are the visible form of what this package reports — Cairo at 0.4% tier-1 coverage against Berlin at 68.9% is the comparison the site exists to make legible.

Ties keep the manifest's order, so a parameter added later lands among the UCPs without needing an edit here.

Source code in src/lczkit/viz/style.py
def selector_rank(column: str) -> tuple[int, int]:
    """Where `column` sits in the layer selector.

    **The order is chosen here, not inherited.** `build_views` used to emit views in whatever order
    the manifest's `breaks` arrived in, which is `writer.py`'s `continuous` — every numeric column
    in DataFrame order. That is incidental, and it put height provenance *last*, below ten urban
    canopy parameters. `height_completeness` and
    `height_tier_fractions` are first-class layers and sit second in the selector, above the UCP
    choropleths. They are the visible form of what this package reports — Cairo at 0.4% tier-1
    coverage against Berlin at 68.9% is the comparison the site exists to make legible.

    Ties keep the manifest's order, so a parameter added later lands among the UCPs without needing
    an edit here.
    """
    if column == HEIGHT_COMPLETENESS_COLUMN:
        return (0, 0)
    if column.startswith(FRACTION_PREFIX):
        return (0, 1)
    if column == UNIQUENESS_COLUMN:
        # Not a parameter but a property of the classification, so it reads as a coda to the
        # parameters rather than one of them.
        return (2, 0)
    return (1, 0)

ramp_colours

ramp_colours(n: int) -> list[str]

n colours sampled evenly from SEQUENTIAL_RAMP, endpoints included.

Source code in src/lczkit/viz/style.py
def ramp_colours(n: int) -> list[str]:
    """`n` colours sampled evenly from `SEQUENTIAL_RAMP`, endpoints included."""
    if n <= 0:
        return []
    if n == 1:
        return [SEQUENTIAL_RAMP[-1]]
    last = len(SEQUENTIAL_RAMP) - 1
    return [SEQUENTIAL_RAMP[round(index * last / (n - 1))] for index in range(n)]

lcz_colour_expression

lcz_colour_expression(column: str = 'lcz_primary') -> list[Any]

A match expression mapping LCZ integer codes to the Demuzere colours.

Read from classify.labels, which a test already asserts equal to the committed reference table — so the map's colours and the output raster's colours cannot drift apart.

to-number is load-bearing, not defensive. tippecanoe's FlatGeobuf reader emits every integer attribute as a string — measured at int16, int32, int64 and uint8, while float64 comes through as a number. lcz_primary is the only integer column the site renders, so a match on the raw value found no label, every cell fell through to NODATA_COLOUR, and the default view of every published site was a field of blank grey squares. Coercing here rather than casting the column to float in write_flatgeobuf keeps a class code an integer everywhere it is read, and keeps the fix at the one place that depends on the type.

A missing value coerces to 0, which matches no label and so still takes NODATA_COLOUR.

Source code in src/lczkit/viz/style.py
def lcz_colour_expression(column: str = "lcz_primary") -> list[Any]:
    """A `match` expression mapping LCZ integer codes to the Demuzere colours.

    Read from `classify.labels`, which a test already asserts equal to the committed reference
    table — so the map's colours and the output raster's colours cannot drift apart.

    **`to-number` is load-bearing, not defensive.** tippecanoe's FlatGeobuf reader emits every
    integer attribute as a *string* — measured at int16, int32, int64 and uint8, while float64 comes
    through as a number. `lcz_primary` is the only integer column the site renders, so a `match` on
    the raw value found no label, every cell fell through to `NODATA_COLOUR`, and the default view
    of every published site was a field of blank grey squares. Coercing here rather than casting
    the column to float in `write_flatgeobuf` keeps a class code an integer everywhere it is read,
    and keeps the fix at the one place that depends on the type.

    A missing value coerces to 0, which matches no label and so still takes `NODATA_COLOUR`.
    """
    expression: list[Any] = ["match", ["to-number", ["get", column]]]
    for entry in LCZ_CLASSES:
        expression += [entry.code, entry.colour]
    expression.append(NODATA_COLOUR)
    return expression

choropleth_expression

choropleth_expression(column: str, breaks: list[float]) -> list[Any]

A step expression over the run's precomputed break points.

breaks are the k + 1 boundaries output.breaks wrote, so the interior boundaries are breaks[1:-1] and the number of classes is one more than that. Nothing is quantised, binned or quantiled here; the boundaries arrive already decided.

Guarded by has so a unit missing the parameter paints as missing rather than as the lowest class — the distinction the null-parameter policy exists to preserve.

Source code in src/lczkit/viz/style.py
def choropleth_expression(column: str, breaks: list[float]) -> list[Any]:
    """A `step` expression over the run's precomputed break points.

    `breaks` are the `k + 1` boundaries `output.breaks` wrote, so the interior boundaries are
    `breaks[1:-1]` and the number of classes is one more than that. Nothing is quantised, binned or
    quantiled here; the boundaries arrive already decided.

    Guarded by `has` so a unit missing the parameter paints as missing rather than as the lowest
    class — the distinction the null-parameter policy exists to preserve.
    """
    interior = breaks[1:-1]
    colours = ramp_colours(len(interior) + 1)
    step: list[Any] = ["step", ["to-number", ["get", column]], colours[0]]
    for boundary, colour in zip(interior, colours[1:], strict=True):
        step += [boundary, colour]
    return ["case", ["has", column], step, NODATA_COLOUR]

build_views

build_views(breaks: list[dict[str, Any]], columns: list[str], parameters: list[dict[str, str]]) -> list[dict[str, Any]]

One view per renderable variable, LCZ first and height provenance second.

A variable earns a view only if it is both in the tiles (columns) and has breaks in the manifest. Anything else would be a menu entry that paints nothing.

The continuous views are ordered by selector_rank rather than by the order the breaks arrive in — see that function for why the inherited order was wrong.

Source code in src/lczkit/viz/style.py
def build_views(
    breaks: list[dict[str, Any]], columns: list[str], parameters: list[dict[str, str]]
) -> list[dict[str, Any]]:
    """One view per renderable variable, LCZ first and height provenance second.

    A variable earns a view only if it is *both* in the tiles (`columns`) and has breaks in the
    manifest. Anything else would be a menu entry that paints nothing.

    The continuous views are ordered by `selector_rank` rather than by the order the breaks arrive
    in — see that function for why the inherited order was wrong.
    """
    units = {entry["name"]: entry.get("unit", "") for entry in parameters}
    descriptions = {entry["name"]: entry.get("description", "") for entry in parameters}
    labels = {entry["name"]: entry["label"] for entry in parameters if entry.get("label")}
    views: list[dict[str, Any]] = [
        {
            "id": "lcz",
            "column": "lcz_primary",
            "label": "LCZ class",
            "group": GROUP_CLASSIFICATION,
            "unit": "",
            "description": "Primary Local Climate Zone, Demuzere et al. (2022) colours",
            "kind": "categorical",
            "paint": lcz_colour_expression(),
            "legend": [
                {"colour": entry.colour, "label": f"{entry.label}{entry.name}"}
                for entry in LCZ_CLASSES
            ],
        }
    ]

    available = set(columns)
    continuous: list[dict[str, Any]] = []
    for entry in breaks:
        column = entry["column"]
        if column not in available or not entry.get("breaks"):
            continue
        boundaries = [float(value) for value in entry["breaks"]]
        if len(boundaries) < 2:
            continue
        interior = boundaries[1:-1]
        colours = ramp_colours(len(interior) + 1)
        edges = [boundaries[0], *interior, boundaries[-1]]
        legend: list[dict[str, Any]] = [
            {"colour": colour, "label": f"{low:.3g}{high:.3g}"}
            for colour, low, high in zip(colours, edges[:-1], edges[1:], strict=True)
        ]
        # A null parameter is a reportable state, not an absence — `aspect_ratio` is null wherever
        # no street reaches a building, which is most of LCZ 8. Without a row for it the reader
        # sees grey cells in the same shade on every layer and no way to learn what grey means.
        legend.append({"colour": NODATA_COLOUR, "label": "no value", "nodata": True})
        continuous.append(
            {
                "id": column,
                "column": column,
                "label": display_label(column, labels),
                "group": selector_group(column),
                "unit": units.get(column, ""),
                "description": descriptions.get(column, ""),
                "kind": "continuous",
                "method": entry.get("method", "quantile"),
                "paint": choropleth_expression(column, boundaries),
                "legend": legend,
            }
        )
    # Stable, so columns of equal rank keep the manifest's order.
    continuous.sort(key=lambda view: selector_rank(str(view["column"])))
    views.extend(continuous)
    return views

raster_id

raster_id(entry: BasemapProvider) -> str

The style id of entry's source and layer, which are deliberately the same string.

One id per provider, because each carries its own tile size and maximum zoom and a MapLibre source carries both — so several grounds cannot share one source whose tiles are swapped.

Source code in src/lczkit/viz/style.py
def raster_id(entry: basemaps.BasemapProvider) -> str:
    """The style id of `entry`'s source and layer, which are deliberately the same string.

    One id per provider, because each carries its own tile size and maximum zoom and a MapLibre
    source carries both — so several grounds cannot share one source whose tiles are swapped.
    """
    return f"{RASTER_BASEMAP_PREFIX}{entry.key}"

build_style

build_style(manifest: dict[str, Any], *, columns: list[str], bounds: tuple[float, float, float, float], centre: tuple[float, float], has_detail: bool, basemap_layers: tuple[str, ...], has_buildings: bool, online_basemaps: Sequence[str] = (), maptiler_key: str | None = None) -> dict[str, Any]

The complete style document, ready to be written as style.json.

columns is what the unit tileset actually carries, so a manifest listing breaks for a column that did not make it into the tiles produces no menu entry rather than a blank map. Likewise basemap_layers is what the basemap tileset actually contains: a style layer naming a source-layer that is not in the tileset renders nothing and reports nothing, which is the hardest kind of blank map to diagnose.

online_basemaps names remote raster grounds to add beneath everything, in picker order. They are the only thing in this document that reaches outside the directory, and there are none unless a caller asks — see lczkit.viz.basemaps for why that default is load-bearing rather than cautious. Each gets its own source and layer rather than sharing one whose tiles are swapped: tile size and maximum zoom differ per provider and a source carries both.

Source code in src/lczkit/viz/style.py
def build_style(
    manifest: dict[str, Any],
    *,
    columns: list[str],
    bounds: tuple[float, float, float, float],
    centre: tuple[float, float],
    has_detail: bool,
    basemap_layers: tuple[str, ...],
    has_buildings: bool,
    online_basemaps: Sequence[str] = (),
    maptiler_key: str | None = None,
) -> dict[str, Any]:
    """The complete style document, ready to be written as `style.json`.

    `columns` is what the unit tileset actually carries, so a manifest listing breaks for a column
    that did not make it into the tiles produces no menu entry rather than a blank map. Likewise
    `basemap_layers` is what the basemap tileset actually contains: a style layer naming a
    `source-layer` that is not in the tileset renders nothing and reports nothing, which is the
    hardest kind of blank map to diagnose.

    `online_basemaps` names remote raster grounds to add beneath everything, in picker order. They
    are the only thing in this document that reaches outside the directory, and there are none
    unless a caller asks — see `lczkit.viz.basemaps` for why that default is load-bearing rather
    than cautious. Each gets its own source and layer rather than sharing one whose tiles are
    swapped: tile size and maximum zoom differ per provider and a source carries both.
    """
    has_basemap = bool(basemap_layers)
    rasters = [basemaps.provider(key) for key in online_basemaps]
    views = build_views(manifest.get("breaks", []), columns, manifest.get("parameters", []))

    sources: dict[str, Any] = {
        UNITS_SOURCE: {
            "type": "vector",
            "url": "pmtiles://./tiles/units.pmtiles",
            # `unit_id` *is* the feature identity everywhere else in this package, so promoting it
            # makes the map agree with the rest of the pipeline. It also makes the selection
            # highlight work at all: `setFeatureState` needs an id, and tippecanoe assigns none
            # unless asked, so without this a click would silently highlight nothing.
            "promoteId": "unit_id",
        }
    }
    if has_detail:
        sources[UNITS_DETAIL_SOURCE] = {
            "type": "vector",
            "url": "pmtiles://./tiles/units_detail.pmtiles",
        }
    if has_basemap:
        sources[BASEMAP_SOURCE] = {"type": "vector", "url": "pmtiles://./tiles/basemap.pmtiles"}
    if has_buildings:
        sources[BUILDINGS_SOURCE] = {
            "type": "vector",
            "url": "pmtiles://./tiles/buildings.pmtiles",
        }
    for entry in rasters:
        sources[raster_id(entry)] = {
            "type": "raster",
            # Raises rather than shipping an unsubstituted `{key}`, which would 403 per tile and
            # look like an empty base map instead of a missing key.
            "tiles": basemaps.tile_urls(entry, maptiler_key),
            "tileSize": entry.tile_size,
            "maxzoom": entry.max_zoom,
            # MapLibre's attribution control reads this. Every provider here requires attribution,
            # which is why configuring one also switches that control on in the front end.
            "attribution": entry.attribution,
        }

    layers: list[dict[str, Any]] = [
        {"id": "background", "type": "background", "paint": {"background-color": BACKGROUND_COLOUR}}
    ]
    for entry in rasters:
        # Beneath everything, and all hidden at first: the run's own linework is the default ground,
        # so an archived site opened offline looks the way it always did until a reader asks for
        # tiles. They sit in one block directly above the background, so whichever the reader picks
        # is under the classification rather than over it.
        layers.append(
            {
                "id": raster_id(entry),
                "type": "raster",
                "source": raster_id(entry),
                "layout": {"visibility": "none"},
                "paint": {"raster-opacity": 1.0},
            }
        )
    # The layers the *run* persisted, as opposed to the remote raster. The base picker switches
    # between the two sets, so they have to be distinguishable by more than a name prefix.
    run_basemap_layers: list[str] = []
    if "land_use" in basemap_layers:
        layers.append(
            {
                "id": "basemap-land-use",
                "type": "fill",
                "source": BASEMAP_SOURCE,
                "source-layer": "land_use",
                "paint": {"fill-color": LAND_USE_COLOUR},
            }
        )
        run_basemap_layers.append("basemap-land-use")
    if "water" in basemap_layers:
        layers.append(
            {
                "id": "basemap-water",
                "type": "fill",
                "source": BASEMAP_SOURCE,
                "source-layer": "water",
                "paint": {"fill-color": WATER_COLOUR},
            }
        )
        run_basemap_layers.append("basemap-water")

    layers.append(
        {
            "id": UNITS_FILL_LAYER,
            "type": "fill",
            "source": UNITS_SOURCE,
            "source-layer": "units",
            "paint": {"fill-color": views[0]["paint"], "fill-opacity": 0.82},
        }
    )
    layers.append(
        {
            "id": "units-outline",
            "type": "line",
            "source": UNITS_SOURCE,
            "source-layer": "units",
            "minzoom": 13,
            "paint": {"line-color": UNIT_OUTLINE_COLOUR, "line-opacity": 0.25, "line-width": 0.5},
        }
    )

    if "streets" in basemap_layers:
        layers.append(
            {
                "id": "basemap-streets",
                "type": "line",
                "source": BASEMAP_SOURCE,
                "source-layer": "streets",
                "paint": {
                    "line-color": STREET_COLOUR,
                    "line-opacity": 0.75,
                    "line-width": ["interpolate", ["linear"], ["zoom"], 10, 0.3, 16, 1.8],
                },
            }
        )
        run_basemap_layers.append("basemap-streets")

    if has_buildings:
        layers.append(
            {
                "id": "buildings-3d",
                "type": "fill-extrusion",
                "source": BUILDINGS_SOURCE,
                "source-layer": "buildings",
                "minzoom": 14,
                "layout": {"visibility": "none"},
                "paint": {
                    "fill-extrusion-height": ["coalesce", ["to-number", ["get", "height"]], 3],
                    "fill-extrusion-base": 0,
                    "fill-extrusion-opacity": 0.9,
                    "fill-extrusion-color": "#c8cdd4",
                },
            }
        )

    # The selection highlight reads a feature-state rather than a filter, so clicking never
    # invalidates the tile and never triggers a re-request.
    layers.append(
        {
            "id": "units-selected",
            "type": "line",
            "source": UNITS_SOURCE,
            "source-layer": "units",
            "paint": {
                "line-color": "#ffffff",
                "line-width": ["case", ["boolean", ["feature-state", "selected"], False], 3, 0],
            },
        }
    )

    return {
        "version": 8,
        "name": f"lczkit {manifest.get('run_id', '')}".strip(),
        "sources": sources,
        "layers": layers,
        "metadata": {
            "lczkit": {
                "run_id": manifest.get("run_id"),
                "views": views,
                "fill_layer": UNITS_FILL_LAYER,
                "units_source": UNITS_SOURCE,
                "units_source_layer": "units",
                "detail_source": UNITS_DETAIL_SOURCE if has_detail else None,
                # Column names are passed to the browser rather than reconstructed there. The
                # distance columns are `lcz_d1..17` and the tier fractions are named after
                # whichever height sources fired, so a hardcoded list in JavaScript would be a
                # second definition of a schema that already has one.
                "distance_columns": list(DISTANCE_COLUMNS),
                "distance_labels": [entry.label for entry in LCZ_CLASSES],
                "height_prefixes": ["height_completeness", FRACTION_PREFIX],
                "buildings_layer": "buildings-3d" if has_buildings else None,
                "building_colour_by": _building_colour_expressions() if has_buildings else {},
                "bounds": list(bounds),
                "centre": list(centre),
                "nodata_code": NODATA_CODE,
                "nodata_colour": NODATA_COLOUR,
                # Which grounds the reader can choose between. `run_layers` is always present
                # because the run persisted its own water and streets, and it is an *overlay*: it
                # composes over whichever raster is chosen rather than replacing it. `rasters` is
                # empty unless a caller configured one, and an empty list is what makes the page
                # show no base-map picker at all.
                "basemap": {
                    # Collected as they were appended rather than matched on the "basemap-" prefix,
                    # which the raster layers also carry — prefix-matching here put the remote
                    # tiles into the offline choice and made "run's own linework" fetch the network.
                    "run_layers": run_basemap_layers,
                    "rasters": [
                        {
                            "id": raster_id(entry),
                            "key": entry.key,
                            "label": entry.label,
                            "licence": entry.licence,
                            # Drives the front end's opacity floor: the LCZ palette is a light
                            # figure on a dark ground, so over a light or busy ground the unit fill
                            # has to be drawn more opaquely to stay readable.
                            "dark": entry.dark,
                        }
                        for entry in rasters
                    ],
                },
                # The sidebar renders one row per parameter and used to title each with its column
                # name. These are `ParameterSpec.label`, plus the classification and provenance
                # columns the registry does not describe.
                "labels": {
                    **{
                        entry["name"]: entry["label"]
                        for entry in manifest.get("parameters", [])
                        if entry.get("label")
                    },
                    **DISPLAY_LABELS,
                },
                "height_source_labels": dict(HEIGHT_SOURCE_LABELS),
                "groups": [
                    GROUP_CLASSIFICATION,
                    GROUP_PROVENANCE,
                    GROUP_PARAMETERS,
                    GROUP_CONFIDENCE,
                ],
            }
        },
    }

Basemaps

Each provider records its licence and its usage terms, and the CLI prints them when one is selected — OpenStreetMap's own tile service in particular is a donated resource rather than a commercial one, and its usage policy applies to whoever opts in.

lczkit.viz.basemaps

Optional online raster base layers, and the attribution each one obliges the site to carry.

Read this before enabling one. A built site opens with no network and no software the reader must install, and stays valid years from now. That is not a preference — it is what makes a site archivable beside a paper. Everything here breaks it, so nothing here is on by default.

VizConfig.online_basemaps is empty unless a caller asks, and with it empty the emitted site contains no external reference at all — a test asserts exactly that, and a second test asserts that when one is configured the only file mentioning a remote host is style.json. The front end treats each raster as a layer that may fail: tiles that do not load leave every other layer working and say so, rather than producing a blank map.

Configuring several is normal and costs nothing until one is chosen: each becomes its own hidden source and layer, and the page's base picker switches between them. Sizes and zoom limits differ per provider, which is why they cannot share one source whose tiles are swapped at runtime.

Two providers need an API key, and the key ships in the site. MapLibre fetches tiles from the browser, so style.json carries the key in plain text and anyone holding the directory holds the key. It is deliberately kept out of the run manifest — see VizConfig.maptiler_key — but that bounds the exposure rather than removing it, and a key used this way should be origin-restricted at the provider.

A site built with one of these is not archival. The provider outlives the run only as long as it chooses to. The run's own Overture linework stays available in the same site and remains the default ground, so a reader who opens an old site offline still sees the geometry the classification was computed from.

Tile usage policies are the caller's obligation, not this module's. Each provider records its licence and the terms in its own docstring. The OpenStreetMap Foundation's tile servers in particular are a donated resource with an explicit usage policy: fine for reading a map, not for bulk or automated fetching, and a heavy consumer is expected to run its own tiles.

OPENSTREETMAP module-attribute

OPENSTREETMAP = BasemapProvider(key='osm', label='OpenStreetMap', tiles=('https://tile.openstreetmap.org/{z}/{x}/{y}.png',), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='ODbL 1.0 (data), CC-BY-SA 2.0 (tiles)', max_zoom=19, terms='The OSMF tile servers are a donated resource under an explicit usage policy: acceptable for a person reading a map, not for bulk or automated downloading. A site that will be opened often should point at its own tiles instead.', hosts=('tile.openstreetmap.org',))

The obvious choice, and the one to be most careful with — see terms.

CARTO_POSITRON module-attribute

CARTO_POSITRON = BasemapProvider(key='carto-positron', label='Carto Positron (light)', tiles=('https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', 'https://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', 'https://c.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attributions">CARTO</a>', licence='ODbL 1.0 (data), CC-BY 3.0 (style)', max_zoom=20, dark=False, hosts=('a.basemaps.cartocdn.com', 'b.basemaps.cartocdn.com', 'c.basemaps.cartocdn.com'))

Deliberately muted, which is the point: a basemap under a choropleth should not compete with it. Light, so the front end raises the unit fill's opacity to keep the LCZ palette readable over it.

CARTO_DARK_MATTER module-attribute

CARTO_DARK_MATTER = BasemapProvider(key='carto-dark', label='Carto Dark Matter', tiles=('https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 'https://b.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 'https://c.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png'), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attributions">CARTO</a>', licence='ODbL 1.0 (data), CC-BY 3.0 (style)', max_zoom=20, dark=True, hosts=('a.basemaps.cartocdn.com', 'b.basemaps.cartocdn.com', 'c.basemaps.cartocdn.com'))

The best fit for this site's palette, which was built for a light figure on a dark ground.

ESRI_WORLD_IMAGERY module-attribute

ESRI_WORLD_IMAGERY = BasemapProvider(key='esri-satellite', label='Esri World Imagery (satellite)', tiles=('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',), attribution='Imagery © <a href="https://www.esri.com">Esri</a>, Maxar, Earthstar Geographics, and the GIS User Community', licence='Esri Terms of Use — free to use with attribution', max_zoom=19, terms="Esri's World Imagery service is free to use in a map that carries its attribution, which this site does. It is not a bulk imagery source and Esri may rate-limit or withdraw it.", hosts=('server.arcgisonline.com',))

Satellite imagery without a key, and the reason this package ships no Google tiles.

Google's mt*.google.com/vt endpoint is undocumented and using it outside a Google Maps API breaks their terms of service, so it cannot carry a licence string and has no place in a table whose point is that every ground records one.

MAPTILER_HYBRID module-attribute

MAPTILER_HYBRID = BasemapProvider(key='maptiler-hybrid', label='MapTiler Satellite Hybrid', tiles=('https://api.maptiler.com/maps/hybrid/256/{z}/{x}/{y}.jpg?key={key}',), attribution='© <a href="https://www.maptiler.com/copyright/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='MapTiler Cloud terms — requires an API key', max_zoom=20, terms="Requires a MapTiler API key, which is written into the site's style.json in plain text because the browser fetches the tiles. Anyone given the site directory has the key: restrict it by origin in the MapTiler console, or hand out a site built without it.", hosts=('api.maptiler.com',), requires_key=True, key_name='MAPTILER_API_KEY')

Satellite imagery with roads and place names over it — the closest thing here to what people mean by "Google satellite", from a provider whose terms permit it.

MAPTILER_TOPO module-attribute

MAPTILER_TOPO = BasemapProvider(key='maptiler-topo', label='MapTiler Topo', tiles=('https://api.maptiler.com/maps/topo-v2/256/{z}/{x}/{y}.png?key={key}',), attribution='© <a href="https://www.maptiler.com/copyright/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='MapTiler Cloud terms — requires an API key', max_zoom=22, terms="Requires a MapTiler API key, which is written into the site's style.json in plain text because the browser fetches the tiles. Anyone given the site directory has the key: restrict it by origin in the MapTiler console, or hand out a site built without it.", hosts=('api.maptiler.com',), requires_key=True, key_name='MAPTILER_API_KEY')

Terrain shading and contours. The one ground here that shows relief, which is the context an LCZ map most often lacks: a valley floor and a hillside classify alike and behave differently.

DEFAULT_BASEMAP_KEYS module-attribute

DEFAULT_BASEMAP_KEYS: tuple[str, ...] = tuple(key for key, entry in PROVIDERS.items() if not entry.requires_key)

What lczkit run and lczkit site build offer when the caller names nothing.

Derived from requires_key rather than listed, because that is the rule. A ground that needs no key costs a reader nothing to be offered and publishes no secret; a keyed one writes an API key into the built site, which is a decision someone has to make on purpose. A keyless provider added later joins this set by being keyless, and a keyed one cannot join it by being forgotten.

This is a command-line default, not the library's. VizConfig.online_basemaps is still empty by default, so build_site() and a rebuild of an archived manifest reach no network unless told to — that is the property the no-external-reference test pins, and it is unchanged. A site built by the command line names these tile hosts in its style.json; a site built through the library names none. Pass --basemap none for an archival build.

BasemapProvider dataclass

BasemapProvider(key: str, label: str, tiles: tuple[str, ...], attribution: str, licence: str, max_zoom: int = 19, tile_size: int = 256, terms: str = '', dark: bool = False, hosts: tuple[str, ...] = tuple(), requires_key: bool = False, key_name: str = '')

One remote raster tile source, with everything the style and the page need to use it.

label instance-attribute

label: str

What the layer is called in the front end's base picker.

tiles instance-attribute

tiles: tuple[str, ...]

Tile URL templates. More than one is a subdomain rotation.

attribution instance-attribute

attribution: str

Shown by MapLibre's attribution control. Required by every provider here, and the reason the control is switched on whenever a raster basemap is configured.

terms class-attribute instance-attribute

terms: str = ''

The usage constraint a caller takes on by selecting this provider.

dark class-attribute instance-attribute

dark: bool = False

Whether the tiles are dark. The unit fill and the LCZ palette are built for a dark ground, so a light basemap needs the fill drawn more opaquely to stay legible.

hosts class-attribute instance-attribute

hosts: tuple[str, ...] = field(default_factory=tuple)

The hosts this provider contacts, so a test can assert the site reaches nothing else.

requires_key class-attribute instance-attribute

requires_key: bool = False

Whether tiles carry a {key} placeholder that must be filled before the site is written.

lczkit.viz.style substitutes it and raises when it cannot, because the failure is otherwise silent: a tile URL still containing {key} is a well-formed URL that returns 403 per tile, and MapLibre reports that as an empty basemap rather than as a configuration error.

key_name class-attribute instance-attribute

key_name: str = ''

The environment variable holding this provider's key, named in the error when it is absent.

Documentation only — nothing in this module reads the environment. Every environment read happens in the config layer, so lczkit.config.maptiler_key() is what actually resolves it.

provider

provider(key: str) -> BasemapProvider

The provider called key, or a KeyError naming the ones that exist.

Source code in src/lczkit/viz/basemaps.py
def provider(key: str) -> BasemapProvider:
    """The provider called `key`, or a `KeyError` naming the ones that exist."""
    try:
        return PROVIDERS[key]
    except KeyError:
        raise KeyError(f"unknown basemap {key!r}; choose from {sorted(PROVIDERS)}") from None

tile_urls

tile_urls(entry: BasemapProvider, api_key: str | None) -> list[str]

entry's tile templates with {key} filled in, or a ValueError naming the variable.

{z}, {x} and {y} are left alone — MapLibre substitutes those per tile, and only {key} is replaced here. Raising when a keyed provider has no key is the point of the function: an unsubstituted template is a well-formed URL that 403s on every tile, so the site would build cleanly and show an empty basemap with nothing anywhere saying why.

Source code in src/lczkit/viz/basemaps.py
def tile_urls(entry: BasemapProvider, api_key: str | None) -> list[str]:
    """`entry`'s tile templates with `{key}` filled in, or a `ValueError` naming the variable.

    `{z}`, `{x}` and `{y}` are left alone — MapLibre substitutes those per tile, and only `{key}`
    is replaced here. Raising when a keyed provider has no key is the point of the function: an
    unsubstituted template is a well-formed URL that 403s on every tile, so the site would build
    cleanly and show an empty basemap with nothing anywhere saying why.
    """
    if not entry.requires_key:
        return list(entry.tiles)
    if not api_key:
        raise ValueError(
            f"base map {entry.key!r} needs an API key; set {entry.key_name} in your .env "
            f"(or drop {entry.key!r} from the configured base maps)"
        )
    return [url.replace("{key}", api_key) for url in entry.tiles]

external_hosts

external_hosts() -> frozenset[str]

Every host any provider can contact.

Exists so tests/test_viz_site.py can assert that a site configured with one of these reaches that provider and nothing else, rather than dropping the no-external-reference guarantee.

Source code in src/lczkit/viz/basemaps.py
def external_hosts() -> frozenset[str]:
    """Every host any provider can contact.

    Exists so `tests/test_viz_site.py` can assert that a site configured with one of these reaches
    that provider and nothing else, rather than dropping the no-external-reference guarantee.
    """
    return frozenset(host for entry in PROVIDERS.values() for host in entry.hosts)

Server

lczkit.viz.serve

A standard-library static server that answers HTTP Range requests.

python serve.py [--port 8000] [--directory .]

This file is copied verbatim into every site directory, which is why it imports nothing outside the standard library and takes no arguments the site does not already know. A reader who receives the directory years from now needs a Python interpreter and nothing else.

Why it exists at all. PMTiles works by asking for byte ranges of one file over HTTP, and http.server.SimpleHTTPRequestHandler does not implement Range — it answers 200 with the whole body, every time, for every tile. A 60 MB tileset would then be re-sent for each of hundreds of tile reads. So the forty lines below are the difference between a site that loads and one that does not, and they are cheaper than taking on a web-server dependency for them.

Why a server is needed rather than opening index.html directly. The Fetch standard leaves file: URLs unhandled, so fetch() against one returns a network error in both Chrome and Firefox, and PMTiles is built on fetch. Nothing here reaches the network: the server is local, the assets are vendored, and the map has no basemap API key and no CDN link. "Offline" is satisfied; "no process at all" is not achievable with range-requested tiles in a current browser.

RangeRequestHandler

Bases: SimpleHTTPRequestHandler

SimpleHTTPRequestHandler plus single-range bytes= support and the right MIME types.

end_headers

end_headers() -> None

Advertise range support on every response, then close the header block.

Source code in src/lczkit/viz/serve.py
def end_headers(self) -> None:
    """Advertise range support on every response, then close the header block."""
    # Advertised unconditionally: pmtiles.js checks for it before issuing a ranged read, and a
    # server that supports ranges but does not say so is treated as one that does not.
    self.send_header("Accept-Ranges", "bytes")
    self.send_header("Cache-Control", "no-cache")
    super().end_headers()

send_head

send_head() -> IO[bytes] | None

Answer a Range request with 206 Partial Content, or defer to the base class.

This is the whole reason the site ships its own server. SimpleHTTPRequestHandler has no range support, so it would re-send an entire tileset per tile — and PMTiles reads a map by issuing one ranged read per tile.

A request with no Range header, or for a directory, goes to the base class untouched. A start past the end of the file gets 416 with a Content-Range stating the real size, which is what lets a client that guessed wrong recover. Sets _remaining for copyfile.

Source code in src/lczkit/viz/serve.py
def send_head(self) -> IO[bytes] | None:  # type: ignore[override]
    """Answer a `Range` request with `206 Partial Content`, or defer to the base class.

    This is the whole reason the site ships its own server. `SimpleHTTPRequestHandler` has
    no range support, so it would re-send an entire tileset per tile — and PMTiles reads a
    map by issuing one ranged read per tile.

    A request with no `Range` header, or for a directory, goes to the base class untouched.
    A start past the end of the file gets `416` with a `Content-Range` stating the real size,
    which is what lets a client that guessed wrong recover. Sets `_remaining` for `copyfile`.
    """
    header = self.headers.get("Range")
    if header is None:
        return super().send_head()

    start, end = _parse_range(header)
    if start is None:
        self.send_error(HTTPStatus.BAD_REQUEST, "malformed Range header")
        return None

    path = Path(self.translate_path(self.path))
    if path.is_dir():
        return super().send_head()
    try:
        handle = path.open("rb")
    except OSError:
        self.send_error(HTTPStatus.NOT_FOUND, "file not found")
        return None

    size = path.stat().st_size
    if start < 0:
        start, end = max(0, size + start), None
    if start >= size:
        handle.close()
        self.send_response(HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
        self.send_header("Content-Range", f"bytes */{size}")
        self.end_headers()
        return None

    last = size - 1 if end is None else min(end, size - 1)
    handle.seek(start)
    self.send_response(HTTPStatus.PARTIAL_CONTENT)
    self.send_header("Content-Type", self.guess_type(str(path)))
    self.send_header("Content-Range", f"bytes {start}-{last}/{size}")
    self.send_header("Content-Length", str(last - start + 1))
    self.end_headers()
    self._remaining = last - start + 1
    return handle

copyfile

copyfile(source: IO[bytes], outputfile: IO[bytes]) -> None

Write exactly the bytes send_head promised, or the whole file if it promised none.

_remaining is cleared before the loop rather than after, so a connection that drops part-way cannot leave a stale byte count for the next request on the same handler.

Source code in src/lczkit/viz/serve.py
def copyfile(self, source: IO[bytes], outputfile: IO[bytes]) -> None:  # type: ignore[override]
    """Write exactly the bytes `send_head` promised, or the whole file if it promised none.

    `_remaining` is cleared before the loop rather than after, so a connection that drops
    part-way cannot leave a stale byte count for the next request on the same handler.
    """
    remaining = self._remaining
    if remaining is None:
        super().copyfile(source, outputfile)
        return
    self._remaining = None
    while remaining > 0:
        block = source.read(min(CHUNK, remaining))
        if not block:
            break
        outputfile.write(block)
        remaining -= len(block)

serve

serve(directory: Path, port: int = 8000, *, bind: str = '127.0.0.1') -> None

Serve directory until interrupted.

Source code in src/lczkit/viz/serve.py
def serve(directory: Path, port: int = 8000, *, bind: str = "127.0.0.1") -> None:
    """Serve `directory` until interrupted."""
    os.chdir(directory)
    with _Server((bind, port), RangeRequestHandler) as server:
        bound = server.server_address[1]
        print(f"lczkit site on http://{bind}:{bound}/  (ctrl-c to stop)", flush=True)
        server.serve_forever()

main

main() -> None

Command-line entry point: serve the directory this file sits in, over loopback.

Defaulting --directory to the script's own parent is what makes a built site openable by python serve.py from inside it, with no arguments and nothing installed.

Source code in src/lczkit/viz/serve.py
def main() -> None:
    """Command-line entry point: serve the directory this file sits in, over loopback.

    Defaulting `--directory` to the script's own parent is what makes a built site openable by
    `python serve.py` from inside it, with no arguments and nothing installed.
    """
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--port", type=int, default=8000)
    parser.add_argument("--bind", default="127.0.0.1")
    parser.add_argument("--directory", type=Path, default=Path(__file__).resolve().parent)
    args = parser.parse_args()
    serve(args.directory, args.port, bind=args.bind)