#!/usr/bin/env python3 """Build land/sea mask tiles from OpenStreetMap land polygons. python3 tools/landmask/build.py --shp PATH/land-polygons-split-4326/land_polygons.shp \ --offer-url https://focusscout.app/data/landmask/ Defaults: latitude 49..61 N, longitude -11..3 E, 960 cells per degree of latitude and of longitude, nonzero winding, output in tools/landmask/out/. See README.md for the format and the licence terms. The shapefile is streamed through its .shx index: each record's 52-byte head (its bounding box) is read, and the points only of the records that meet the region (for the default region, 45 MB of heads and 44 MB of points from the 1.3 GB full-detail file), so the memory used follows the region, not the world. Any region: --south/--north/--west/--east in whole degrees. A region across the antimeridian is given with an east edge past 180 (--west 170 --east 190 is 170 E to 170 W). With an EPSG:3857 source, tiles reaching past its +-85.0511 degree limit are written as "not covered". Reproducible: the same shapefile, flags and zlib build give byte-identical output (no timestamps are written; the date in the index and manifest is the source data's date, read from the package's README.txt or given with --source-date). The decoded bits don't depend on zlib: each tile header carries their CRC-32. """ from __future__ import annotations import argparse import hashlib import json import math import platform import sys import time import zlib from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) import landmask as lm # noqa: E402 HERE = Path(__file__).resolve().parent ATTRIBUTION = "© OpenStreetMap contributors" NOTICE = """Land/sea mask tiles for LightWatch (Focus Scout) Contains information from OpenStreetMap, {attribution}. Source: OpenStreetMap land polygons ({source_name}), data of {date}, from https://osmdata.openstreetmap.de/data/land-polygons.html These tiles are a Derivative Database of OpenStreetMap and are made available under the Open Database License (ODbL) v1.0: https://opendatacommons.org/licenses/odbl/1-0/ See https://www.openstreetmap.org/copyright {offer} """ OFFER = """A complete machine-readable copy of this database (landmask.lmp, with this notice) is available free of charge at: {url}""" NO_OFFER = """OFFER NOT SET: before these tiles, or anything made with them, are made public, publish landmask.lmp and this notice at a public URL and rebuild with --offer-url (ODbL 4.6).""" def parse_args(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--shp", required=True, help="OSM land polygons shapefile (EPSG:3857 or EPSG:4326)") p.add_argument("--crs", choices=["3857", "4326"], help="override the CRS read from the .prj") p.add_argument("--out", default=str(HERE / "out"), help="output folder (default: tools/landmask/out)") p.add_argument("--south", type=int, default=49, help="southern edge, whole degrees (default 49)") p.add_argument("--north", type=int, default=61, help="northern edge, whole degrees, exclusive (default 61)") p.add_argument("--west", type=int, default=-11, help="western edge, whole degrees (default -11)") p.add_argument("--east", type=int, default=3, help="eastern edge, whole degrees, exclusive (default 3); past 180 for a region across the " "antimeridian (--west 170 --east 190)") p.add_argument("--cells-per-degree", type=int, default=960, help="cells per degree of latitude (default 960 = 1/960 deg, about 116 m N-S)") p.add_argument("--lon-cells-per-degree", type=int, help="cells per degree of longitude (default: same as latitude, so cells are never wider than " "they are tall)") p.add_argument("--rule", choices=["nonzero", "evenodd"], default="nonzero", help="fill rule (default nonzero: where source polygons overlap it stays land, holes stay water)") p.add_argument("--source-date", help="YYYY-MM-DD of the source data (default: read from README.txt beside --shp)") p.add_argument("--source-name", help="source package name for the notice (default: the shapefile's folder name)") p.add_argument("--offer-url", help="public URL where landmask.lmp and NOTICE.txt are published (ODbL 4.6 offer); " "written into NOTICE.txt and manifest.json") p.add_argument("--no-pack", action="store_true", help="skip landmask.lmp (index + tiles in one file)") p.add_argument("--chunk-tiles", type=int, default=24, help="tile columns rasterised per pass (the pass's grid takes about rows x chunk x cols x 8 " "bytes; the band's edges come on top; default 24)") a = p.parse_args(argv) if not (-90 <= a.south < a.north <= 90): p.error("region must satisfy -90 <= south < north <= 90") if not (-180 <= a.west < 180 and a.west < a.east <= a.west + 360): p.error("region must satisfy -180 <= west < 180 and west < east <= west + 360 " "(for a region across the antimeridian give east past 180, e.g. --west 170 --east 190)") a.lon_cells_per_degree = a.lon_cells_per_degree or a.cells_per_degree if not (8 <= a.cells_per_degree <= 65535 and 8 <= a.lon_cells_per_degree <= 65535): p.error("cells per degree must be 8..65535") return a def main(argv=None): a = parse_args(argv) t_start = time.time() shp = Path(a.shp).resolve() out = Path(a.out).resolve() proj = lm.projection_from_prj(shp, a.crs) date = a.source_date or lm.source_date_from_readme(shp) if not date: raise SystemExit("no source date: pass --source-date YYYY-MM-DD") date_int = int(date.replace("-", "")) source_name = a.source_name or shp.parent.name rows, cols = a.cells_per_degree, a.lon_cells_per_degree # Longitude runs: one, or two when the region crosses the antimeridian (west .. 180 and -180 .. east - 360). # Each run is rasterised separately, so no pass ever spans the jump from +180 to -180. runs = [(a.west, min(a.east, 180))] + ([(-180, a.east - 360)] if a.east > 180 else []) # Latitudes the source can have data at. Tiles reaching past them (EPSG:3857 beyond +-85.0511) are "not # covered", not water: the source simply stops there. lat_ok = [(a.south + i >= -proj.max_lat) and (a.south + i + 1 <= proj.max_lat) for i in range(a.north - a.south)] if not all(lat_ok): print(f"note: {proj.name} has no data beyond +-{proj.max_lat:.4f} deg; " f"{lat_ok.count(False)} tile rows there are written as not covered") # Every polygon whose bbox meets the region. Polygons wholly outside it cannot change any cell in it: a closed # ring entirely west of a point adds zero net winding along the point's row, and one entirely east adds none. lim = proj.max_lat by0 = float(proj.y_of_lat(max(a.south, -lim))) by1 = float(proj.y_of_lat(min(a.north, lim))) boxes = [(float(proj.x_of_lon(w)), by0, float(proj.x_of_lon(e)), by1) for w, e in runs] rings, n_polys, n_holes, hole_list = [], 0, 0, [] for rec_no, box, prings in lm.read_polygons(shp, boxes): n_polys += 1 for r in prings: rings.append(r) if lm.ring_signed_area(r) > 0: # anticlockwise = hole n_holes += 1 cx, cy = r[:-1].mean(axis=0) hole_list.append((rec_no, float(proj.lat_of_y(cy)), float(proj.lon_of_x(cx)))) n_rings = len(rings) edges = lm.Edges.from_rings(rings) del rings # the edges hold everything the rasteriser needs print(f"source {shp.name} ({proj.name}, {date}): {n_polys} polygons, {n_rings} rings " f"({n_holes} holes), {len(edges)} edges meet the region") n_lat, n_lon = a.north - a.south, a.east - a.west status = np.zeros((n_lat, n_lon), dtype=np.uint8) blobs: list[tuple[int, int, bytes]] = [] tile_stats = {} overlap_cells = 0 chunks = [] # (column of the first tile in the index, its west edge in [-180, 180), tile count) for w0, e0 in runs: for w in range(w0, e0, a.chunk_tiles): chunks.append(((w - a.west) % 360, w, min(a.chunk_tiles, e0 - w))) # The edges each 1-degree band needs, found once, so no pass scans every edge (a world build has 80 million). band_index = lm.BandIndex(edges) in_band = [band_index.select(float(proj.y_of_lat(a.south + i)), float(proj.y_of_lat(a.south + i + 1))) if lat_ok[i] else None for i in range(n_lat)] del band_index for i in range(n_lat): lat0 = a.south + i if not lat_ok[i]: continue # status stays NO_DATA for j0, chunk_west, n in chunks: land, winding = lm.rasterise_band(edges, proj, lat0, chunk_west, n, rows, cols, a.rule, in_band[i]) overlap_cells += int(np.count_nonzero(winding >= 2) + np.count_nonzero(winding <= -2)) for k in range(n): west = chunk_west + k bits = land[:, k * cols:(k + 1) * cols] n_land = int(bits.sum()) if n_land == 0: status[i, j0 + k] = lm.ALL_WATER elif n_land == bits.size: status[i, j0 + k] = lm.ALL_LAND else: status[i, j0 + k] = lm.MIXED blob = lm.encode_tile(bits, lat0, west) blobs.append((lat0, west, blob)) tile_stats[lm.tile_name(lat0, west)] = { "bytes": len(blob), "landFraction": round(n_land / bits.size, 4), "bitsCrc32": f"{lm.TILE_HEADER.unpack_from(blob)[-1]:08x}", "sha256": hashlib.sha256(blob).hexdigest()} blobs.sort(key=lambda t: (t[0], (t[1] - a.west) % 360)) # index order: south to north, then west to east index = lm.Index(rows, cols, a.south, a.west, n_lat, n_lon, date_int, status) index_blob = index.encode() # Write: replace earlier .lmt files so tiles that became uniform don't linger. tiles_dir = out / "tiles" tiles_dir.mkdir(parents=True, exist_ok=True) for old in tiles_dir.glob("*.lmt"): old.unlink() for south, west, blob in blobs: (tiles_dir / lm.tile_name(south, west)).write_bytes(blob) (out / "index.lmi").write_bytes(index_blob) pack_info = None pack_path = out / "landmask.lmp" if not a.no_pack: pack = lm.encode_pack(index_blob, blobs) pack_path.write_bytes(pack) pack_info = {"file": pack_path.name, "bytes": len(pack), "sha256": hashlib.sha256(pack).hexdigest()} elif pack_path.exists(): pack_path.unlink() offer = OFFER.format(url=a.offer_url) if a.offer_url else NO_OFFER (out / "NOTICE.txt").write_text(NOTICE.format(attribution=ATTRIBUTION, source_name=source_name, date=date, offer=offer)) counts = {lm.STATUS_NAMES[s]: int(np.count_nonzero(status == s)) for s in (lm.ALL_WATER, lm.ALL_LAND, lm.MIXED, lm.NO_DATA)} sizes = sorted(s["bytes"] for s in tile_stats.values()) mid_lat = (a.south + a.north) / 2 manifest = { "format": "LightWatch land mask, LMT1/LMI1/LMP1 version 1 (tools/landmask/README.md)", "meaning": "bit 1 = land, 0 = water (sea); sampled at cell centres; inland water (lakes) is land", "source": {"name": source_name, "file": shp.name, "crs": proj.name, "date": date, "url": "https://osmdata.openstreetmap.de/data/land-polygons.html", "polygonsUsed": n_polys, "ringsUsed": n_rings, "holesUsed": n_holes}, "licence": "ODbL-1.0 (Derivative Database of OpenStreetMap)", "attribution": ATTRIBUTION, "offerUrl": a.offer_url, "region": {"south": a.south, "north": a.north, "west": a.west, "east": a.east}, "cellsPerDegree": {"lat": rows, "lon": cols}, "cellSizeMetres": {"northSouth": round(111195 / rows, 1), f"eastWestAt{mid_lat:g}N": round(111195 * math.cos(math.radians(mid_lat)) / cols, 1)}, "identity": "compressed bytes depend on the zlib build; the decoded bits are identified by index.lmi " "(uncompressed) and each tile's bitsCrc32", "build": {"rule": a.rule, "encoding": "1 (packed bits, raw DEFLATE RFC 1951, level 9)", "zlib": zlib.ZLIB_VERSION, "numpy": np.__version__, "python": platform.python_version(), "command": "python3 tools/landmask/build.py --shp <" + shp.name + "> " + " ".join( f"--{k.replace('_', '-')} {v}" for k, v in [("south", a.south), ("north", a.north), ("west", a.west), ("east", a.east), ("cells_per_degree", rows), ("lon_cells_per_degree", cols), ("rule", a.rule)]) + (f" --offer-url {a.offer_url}" if a.offer_url else "")}, "tiles": counts, "overlapCells": overlap_cells, "bytes": {"index": len(index_blob), "tiles": sum(sizes), "pack": pack_info["bytes"] if pack_info else None}, "index": {"file": "index.lmi", "sha256": hashlib.sha256(index_blob).hexdigest()}, "pack": pack_info, "holes": [{"record": r, "lat": round(la, 4), "lon": round(lo, 4)} for r, la, lo in hole_list], "mixedTiles": dict(sorted(tile_stats.items())), } (out / "manifest.json").write_text(json.dumps(manifest, indent=1, ensure_ascii=False) + "\n") print(f"tiles: {counts['water']} all water, {counts['land']} all land, {counts['mixed']} mixed" + (f", {counts['no-data']} not covered" if counts['no-data'] else "") + f" ({n_lat * n_lon} total); cells where source polygons overlap (land): {overlap_cells}") if sizes: print(f"mixed tile bytes: min {sizes[0]}, median {float(np.median(sizes)):g}, max {sizes[-1]}, " f"sum {sum(sizes)}") print(f"index {len(index_blob)} B" + (f", pack {pack_info['bytes']} B" if pack_info else "") + f"; wrote {out} in {time.time() - t_start:.1f} s") if not a.offer_url: print("note: no --offer-url, so NOTICE.txt says the ODbL 4.6 offer is not set; set it before release") if __name__ == "__main__": main()