"""Land/sea mask: shapefile reader, rasteriser and the tile format (LMT1 tiles, LMI1 index, LMP1 pack). Shared by build.py (writes tiles) and check.py (reads them back). Pure Python 3 + numpy; no GIS libraries. The format is specified in README.md ("Format"); the constants and layouts below are the reference. Conventions used everywhere: * A tile covers 1 x 1 degree: latitude [south, south+1), longitude [west, west+1), both whole degrees. * A tile is `rows` x `cols` cells (rows = cells per degree of latitude, cols = cells per degree of longitude). Row 0 is the southernmost row, column 0 the westernmost. Cell (r, c) covers lat [south + r/rows, south + (r+1)/rows) and lon [west + c/cols, west + (c+1)/cols), and its value is the source geometry sampled at the cell centre. * Bit 1 = land, bit 0 = water (sea). Bits are packed MSB-first, each row padded to a whole byte with 0 bits. * All integers little-endian. """ from __future__ import annotations import math import os import re import struct import zlib from dataclasses import dataclass from pathlib import Path import numpy as np EARTH_RADIUS = 6378137.0 # EPSG:3857 sphere radius (metres) # Tile status codes in the index (2 bits per tile). NO_DATA, ALL_WATER, ALL_LAND, MIXED = 0, 1, 2, 3 STATUS_NAMES = {NO_DATA: "no-data", ALL_WATER: "water", ALL_LAND: "land", MIXED: "mixed"} # Tile payload encoding. 1 = raw DEFLATE of the packed bitset; other values are reserved for later formats (a row-XOR # pre-filter was tried and made the UK tiles about 2.5% larger, so it is not offered). ENC_BITS = 1 TILE_MAGIC, INDEX_MAGIC, PACK_MAGIC = b"LMT1", b"LMI1", b"LMP1" FORMAT_VERSION = 1 TILE_HEADER = struct.Struct("<4sBBHHhhHI") # magic, version, encoding, rows, cols, south, west, reserved, crc32 INDEX_HEADER = struct.Struct("<4sBBHHhhHHHI") # magic, version, reserved, rows, cols, south, west, nLat, nLon, reserved, date PACK_ENTRY = struct.Struct(" float: """The source's latitude limit: data can only exist within +-max_lat.""" return MERCATOR_MAX_LAT if self.name == "EPSG:3857" else 90.0 def ground_scale(self, lat): """Metres on the ground per source unit (x and y) near `lat`.""" if self.name == "EPSG:3857": return math.cos(math.radians(lat)) return None # degrees: callers handle lat/lon metres themselves # Spherical (Web) Mercator's latitude limit: the square world of EPSG:3857, y = +-pi*R. Its sources have no data # beyond it, so tiles reaching past it are left "not covered" rather than filled with water. MERCATOR_MAX_LAT = math.degrees(2 * math.atan(math.exp(math.pi)) - math.pi / 2) # 85.0511287798... # What a .prj must say to be read as EPSG:3857: the ESRI and OGC names of spherical "Pseudo" Mercator only. Plain # "Mercator" (World Mercator, EPSG:3395, on the ellipsoid) and "Transverse_Mercator" (British National Grid, UTM) # are different projections and are refused. _PRJ_3857 = re.compile(r'Mercator_Auxiliary_Sphere|Pseudo[-_ ]Mercator|Popular_Visualisation|' r'AUTHORITY\["EPSG",\s*"3857"\]|"EPSG:3857"', re.I) def projection_from_prj(shp_path: Path, override: str | None = None) -> Projection: """EPSG:3857 or EPSG:4326 from the shapefile's .prj (or `override`, "3857" / "4326"); stops on anything else.""" if override: names = {"3857": "EPSG:3857", "4326": "EPSG:4326", "EPSG:3857": "EPSG:3857", "EPSG:4326": "EPSG:4326"} if override not in names: raise SystemExit(f"unsupported CRS {override!r}: only 3857 and 4326") return Projection(names[override]) prj = Path(shp_path).with_suffix(".prj") text = prj.read_text(errors="replace").strip() if prj.exists() else "" if text.startswith("PROJCS[") or text.startswith("PROJCRS["): if _PRJ_3857.search(text): return Projection("EPSG:3857") elif (text.startswith("GEOGCS[") or text.startswith("GEOGCRS[")) and re.search(r"WGS[ _]?(19)?84", text): return Projection("EPSG:4326") raise SystemExit(f"cannot use the CRS in {prj}: only EPSG:3857 (Web Mercator, auxiliary sphere) and EPSG:4326 " f"(WGS 84 lat/lon) are supported. If the .prj is just unusual, pass --crs 3857 or --crs 4326.") def source_date_from_readme(shp_path: Path) -> str | None: """osmdata.openstreetmap.de packages carry README.txt with 'Date of the data used is 2026-10-06T00:00:00Z'.""" readme = Path(shp_path).parent / "README.txt" if readme.exists(): m = re.search(r"Date of the data used is (\d{4}-\d{2}-\d{2})", readme.read_text(errors="replace")) if m: return m.group(1) return None # ---------------------------------------------------------------------------------------------------------------- # Shapefile reader (ESRI Shapefile Technical Description, 1998): polygon records only (types 5, 15, 25; XY used). _REC_HEAD = struct.Struct(">2i") # record number, content length in 16-bit words (big-endian) _REC_BOX = struct.Struct(" int: """Check the 100-byte main header; returns the file length in bytes.""" head = f.read(100) if len(head) < 100 or struct.unpack(">i", head[0:4])[0] != 9994: raise ValueError(f"{shp_path}: not a shapefile") shape_type, = struct.unpack("i", head[24:28])[0] * 2 def _record_offsets(shp_path: Path, file_len: int): """Byte offsets of every record from the .shx index beside the .shp, or None when there is no usable .shx.""" shx = Path(shp_path).with_suffix(".shx") if not shx.exists(): return None raw = shx.read_bytes() # 8 bytes per record: 7 MB for the 873,437 records of the full OSM land polygons if len(raw) < 100 or struct.unpack(">i", raw[0:4])[0] != 9994 or (len(raw) - 100) % 8: raise ValueError(f"{shx}: not a shapefile index") words = np.frombuffer(raw, ">i4", offset=100).reshape(-1, 2) offsets = words[:, 0].astype(np.int64) * 2 if len(offsets) and (offsets.min() < 100 or offsets.max() + 8 > file_len): raise ValueError(f"{shx}: offsets outside {shp_path.name}") return offsets.tolist() def read_polygons(shp_path: Path, bbox=None): """Yield (record_number, (xmin, ymin, xmax, ymax), rings) for polygon records whose bbox meets `bbox`. `bbox` is one (xmin, ymin, xmax, ymax) box, a list of them (a record is read if it meets any), or None (all). `rings` is a list of (n, 2) float64 arrays, each closed (first point == last point). Shapefile rings are clockwise for outer boundaries and anticlockwise for holes; a record may hold several of each. The file is streamed, never read whole. With the .shx index beside it (the usual case), each record's 52-byte head (its bounding box) is read, and then the points of the records that meet `bbox`: for Britain and Ireland from the 1.3 GB full-detail OSM land polygons that is 45 MB of heads (all 873,437 records) and 44 MB of points (23,861 records), about a second with the file in the disk cache. The heads are spread through the whole file, so with a cold cache the OS reads most of it from disk; the process's memory still follows the region. Without a .shx the records are walked in order, each read and dropped in turn. Records come out in file order either way. """ shp_path = Path(shp_path) boxes = None if bbox is None else ([tuple(bbox)] if np.isscalar(bbox[0]) else [tuple(b) for b in bbox]) def meets(box): return boxes is None or any(not (box[2] < b[0] or box[0] > b[2] or box[3] < b[1] or box[1] > b[3]) for b in boxes) def parse(rec_no, content: bytes): rtype, *box, n_parts, n_points = _REC_BOX.unpack_from(content, 0) parts = np.frombuffer(content, " float: """Shoelace area in source units; negative = clockwise (outer ring in shapefile terms).""" x, y = ring[:, 0], ring[:, 1] return 0.5 * float(np.sum(x[:-1] * y[1:] - x[1:] * y[:-1])) @dataclass class Edges: """Every ring edge, (x0, y0) -> (x1, y1). The four arrays are views of one array holding all the rings' points, one ring after another with a NaN point between them. No copy is made per edge, and nothing needs filtering out: the joins into and out of a NaN point compare false with every scanline, and horizontal edges cross no row centre, so the rasteriser skips both. """ x0: np.ndarray y0: np.ndarray x1: np.ndarray y1: np.ndarray count: int = 0 # edges that can cross a scanline (not horizontal), for reporting @staticmethod def from_rings(rings: list[np.ndarray]) -> "Edges": if not rings: e = np.zeros(0) return Edges(e, e, e, e, 0) pts = np.empty((sum(len(r) for r in rings) + len(rings) - 1, 2)) pos = 0 for k, r in enumerate(rings): if k: pts[pos] = np.nan pos += 1 pts[pos:pos + len(r)] = r pos += len(r) y0, y1 = pts[:-1, 1], pts[1:, 1] count = int(np.count_nonzero(y0 != y1)) - 2 * (len(rings) - 1) # NaN != y: two per join return Edges(pts[:-1, 0], y0, pts[1:, 0], y1, count) def __len__(self): return self.count # ---------------------------------------------------------------------------------------------------------------- # Rasteriser: scanline through every cell-centre row, signed edge crossings, nonzero winding (or even-odd). class BandIndex: """The edges sorted by their southern end, so the edges that can cross a band's rows are found without scanning them all: a whole-world build from the full-detail source has about 80 million.""" def __init__(self, edges: Edges): ymin = np.minimum(edges.y0, edges.y1) order = np.argsort(ymin, kind="stable") self.order = order[:len(order) - int(np.count_nonzero(np.isnan(ymin)))] # NaN joins sort last: drop them del order self.ymin = ymin[self.order] del ymin self.ymax = np.maximum(edges.y0, edges.y1) self.reach = float(np.max(self.ymax[self.order] - self.ymin)) if len(self.order) else 0.0 # tallest edge def select(self, y_lo: float, y_hi: float) -> np.ndarray: """Indices, ascending, of every edge with ymin < y_hi and ymax > y_lo (and maybe a few more).""" a = np.searchsorted(self.ymin, y_lo - self.reach, "left") b = np.searchsorted(self.ymin, y_hi, "left") cand = self.order[a:b] return np.sort(cand[self.ymax[cand] > y_lo]) def rasterise_band(edges: Edges, proj: Projection, lat0: int, west: int, n_tiles: int, rows: int, cols: int, rule: str = "nonzero", subset: np.ndarray | None = None): """Rasterise one 1-degree latitude band [lat0, lat0+1) for tiles west .. west+n_tiles-1. Returns (land, winding): `land` is a bool array (rows, n_tiles*cols), row 0 south; `winding` the signed winding number (int16) at each cell centre, for diagnostics (|w| >= 2 where source polygons overlap). Every edge of every polygon that reaches the band is used, including parts outside the tiles, so polygons that cross tile or region edges are handled without clipping: a cell's value depends only on the crossings to its west along its own row, and crossings west of the first tile are folded into column 0. `subset` (from BandIndex.select) limits the search to edges that can reach the band; without it every edge is looked at. The result is the same either way. """ lat_c = lat0 + (np.arange(rows) + 0.5) / rows yc = proj.y_of_lat(lat_c) # increasing northwards if subset is None: subset = np.arange(len(edges.y0)) ymin = np.minimum(edges.y0[subset], edges.y1[subset]) ymax = np.maximum(edges.y0[subset], edges.y1[subset]) hit = np.nonzero((ymin <= yc[-1]) & (ymax > yc[0]))[0] sel = subset[hit] ymin, ymax = ymin[hit], ymax[hit] n_cols = n_tiles * cols if len(sel) == 0: z = np.zeros((rows, n_cols), dtype=np.int16) return z != 0, z x0, y0, x1, y1 = edges.x0[sel], edges.y0[sel], edges.x1[sel], edges.y1[sel] # Rows whose centre y lies in [ymin, ymax): half-open, so a vertex exactly on a row counts once. i0 = np.searchsorted(yc, ymin, "left") i1 = np.searchsorted(yc, ymax, "left") count = i1 - i0 keep = count > 0 x0, y0, x1, y1, i0, count = x0[keep], y0[keep], x1[keep], y1[keep], i0[keep], count[keep] edge_of = np.repeat(np.arange(len(count)), count) starts = np.repeat(np.cumsum(count) - count, count) row = i0[edge_of] + (np.arange(len(edge_of)) - starts) ex0, ey0, ex1, ey1 = x0[edge_of], y0[edge_of], x1[edge_of], y1[edge_of] xc = ex0 + (yc[row] - ey0) * (ex1 - ex0) / (ey1 - ey0) lon = proj.lon_of_x(xc) sign = np.where(ey1 > ey0, 1, -1).astype(np.int32) # upward edge +1, downward -1 (same parity either way) # A crossing at longitude `lon` lies west of cell centre j (west + (j+0.5)/cols) for every j >= first. first = np.floor((lon - west) * cols - 0.5).astype(np.int64) + 1 inside = first < n_cols # crossings east of the last cell change nothing first = np.clip(first[inside], 0, n_cols) # crossings west of the first cell centre count for all cells flat = row[inside] * (n_cols + 1) + first acc = np.zeros(rows * (n_cols + 1), dtype=np.int32) # 52 MB a 14-tile band at 960 cells np.add.at(acc, flat, sign[inside]) acc = acc.reshape(rows, n_cols + 1) np.cumsum(acc, axis=1, out=acc) winding = acc[:, :n_cols] land = (winding != 0) if rule == "nonzero" else ((winding & 1) == 1) return land, winding.astype(np.int16) # ---------------------------------------------------------------------------------------------------------------- # Format: tiles. def wrap_lon(west: int) -> int: """A whole-degree longitude in [-180, 180): tiles east of the antimeridian are named and stored that way.""" return (west + 180) % 360 - 180 def tile_name(south: int, west: int) -> str: return f"{'N' if south >= 0 else 'S'}{abs(south):02d}{'E' if west >= 0 else 'W'}{abs(west):03d}.lmt" def encode_tile(land: np.ndarray, south: int, west: int) -> bytes: rows, cols = land.shape packed = np.packbits(land.astype(np.uint8), axis=1, bitorder="big") # (rows, ceil(cols/8)), MSB first crc = zlib.crc32(packed.tobytes()) & 0xFFFFFFFF comp = zlib.compressobj(9, zlib.DEFLATED, -15, 9) # raw DEFLATE (RFC 1951), no zlib header body = comp.compress(packed.tobytes()) + comp.flush() header = TILE_HEADER.pack(TILE_MAGIC, FORMAT_VERSION, ENC_BITS, rows, cols, south, west, 0, crc) return header + body @dataclass class Tile: south: int west: int rows: int cols: int packed: np.ndarray # (rows, stride) uint8, MSB-first bits, 1 = land def land_at_cell(self, r: int, c: int) -> bool: return bool(self.packed[r, c >> 3] & (0x80 >> (c & 7))) def unpack(self) -> np.ndarray: return np.unpackbits(self.packed, axis=1, count=self.cols, bitorder="big").astype(bool) def decode_tile(blob: bytes) -> Tile: magic, version, encoding, rows, cols, south, west, _, crc = TILE_HEADER.unpack_from(blob, 0) if magic != TILE_MAGIC or version != FORMAT_VERSION: raise ValueError(f"not an LMT{FORMAT_VERSION} tile") stride = (cols + 7) // 8 raw = zlib.decompress(blob[TILE_HEADER.size:], -15) if len(raw) != rows * stride: raise ValueError(f"tile {south},{west}: {len(raw)} bytes, expected {rows * stride}") if encoding != ENC_BITS: raise ValueError(f"tile {south},{west}: unknown encoding {encoding}") packed = np.frombuffer(raw, dtype=np.uint8).reshape(rows, stride) if zlib.crc32(packed.tobytes()) & 0xFFFFFFFF != crc: raise ValueError(f"tile {south},{west}: CRC mismatch") if cols % 8 and (packed[:, -1] & ((1 << (8 - cols % 8)) - 1)).any(): raise ValueError(f"tile {south},{west}: row padding bits are not 0") return Tile(south, west, rows, cols, np.ascontiguousarray(packed)) # ---------------------------------------------------------------------------------------------------------------- # Format: index. @dataclass class Index: rows: int cols: int south: int west: int n_lat: int n_lon: int date: int # YYYYMMDD of the source data status: np.ndarray # (n_lat, n_lon) uint8, row 0 south def encode(self) -> bytes: flat = self.status.reshape(-1).astype(np.uint8) pad = (-len(flat)) % 4 flat = np.concatenate([flat, np.zeros(pad, np.uint8)]).reshape(-1, 4) codes = (flat[:, 0] << 6) | (flat[:, 1] << 4) | (flat[:, 2] << 2) | flat[:, 3] header = INDEX_HEADER.pack(INDEX_MAGIC, FORMAT_VERSION, 0, self.rows, self.cols, self.south, self.west, self.n_lat, self.n_lon, 0, self.date) return header + codes.astype(np.uint8).tobytes() @staticmethod def decode(blob: bytes) -> "Index": magic, version, _, rows, cols, south, west, n_lat, n_lon, _, date = INDEX_HEADER.unpack_from(blob, 0) if magic != INDEX_MAGIC or version != FORMAT_VERSION: raise ValueError(f"not an LMI{FORMAT_VERSION} index") n = n_lat * n_lon codes = np.frombuffer(blob, np.uint8, (n + 3) // 4, INDEX_HEADER.size) status = np.stack([(codes >> 6) & 3, (codes >> 4) & 3, (codes >> 2) & 3, codes & 3], axis=1).reshape(-1)[:n] return Index(rows, cols, south, west, n_lat, n_lon, date, status.reshape(n_lat, n_lon).copy()) def status_at(self, tile_south: int, tile_west: int) -> int: """Column j counts eastwards from the index's west edge modulo 360, so an index may run across the antimeridian (west 170, nLon 20 covers 170 E to 170 W). For an index that doesn't, this is just west - west0.""" i, j = tile_south - self.south, (tile_west - self.west) % 360 if 0 <= i < self.n_lat and 0 <= j < self.n_lon: return int(self.status[i, j]) return NO_DATA def tiles(self): """(south, west, status) for every tile in the grid, south to north then west to east; west in [-180, 180).""" for i in range(self.n_lat): for j in range(self.n_lon): yield self.south + i, wrap_lon(self.west + j), int(self.status[i, j]) def covers(self, lat: float, lon: float) -> bool: """Whether (lat, lon) lies inside the index's box (its tile may still be "not covered").""" if not (math.isfinite(lat) and math.isfinite(lon)): return False i = math.floor(lat) - self.south j = (math.floor(lon) - self.west) % 360 return 0 <= i < self.n_lat and 0 <= j < self.n_lon # ---------------------------------------------------------------------------------------------------------------- # Format: pack (index + every mixed tile in one file, for bundling). def encode_pack(index_blob: bytes, tiles: list[tuple[int, int, bytes]]) -> bytes: """tiles: (south, west, tile blob) for every MIXED tile, in index order (south to north, west to east).""" head = PACK_MAGIC + struct.pack(" np.ndarray: """`is_land` for arrays of points, with the same arithmetic: int8, 1 land, 0 water, -1 not covered.""" lat = np.asarray(lat, dtype=np.float64) lon = np.asarray(lon, dtype=np.float64) out = np.full(np.broadcast(lat, lon).shape, -1, dtype=np.int8) lat, lon = np.broadcast_arrays(lat, lon) ok = np.isfinite(lat) & np.isfinite(lon) & (lat >= -90.0) & (lat <= 90.0) if not ok.any(): return out la, lo = lat[ok], lon[ok] wrap = ~((lo >= -180.0) & (lo < 180.0)) lo = np.where(wrap, np.mod(lo + 180.0, 360.0) - 180.0, lo) rows, cols = self.index.rows, self.index.cols g_row = np.floor(la * rows).astype(np.int64) g_col = np.floor(lo * cols).astype(np.int64) south, west = g_row // rows, g_col // cols # floor division, as in is_land val = np.full(len(la), -1, dtype=np.int8) key = (south - south.min()) * 1000 + (west + 500) order = np.argsort(key, kind="stable") bounds = np.flatnonzero(np.diff(key[order])) + 1 for grp in np.split(order, bounds): s, w = int(south[grp[0]]), int(west[grp[0]]) t = self.tile(s, w) if isinstance(t, int): val[grp] = -1 if t == NO_DATA else (1 if t == ALL_LAND else 0) else: r, c = g_row[grp] - s * rows, g_col[grp] - w * cols val[grp] = (t.packed[r, c >> 3] >> (7 - (c & 7))) & 1 out[ok] = val return out def window(self, g_row0: int, g_row1: int, g_col0: int, g_col1: int) -> np.ndarray: """Cells [g_row0, g_row1) x [g_col0, g_col1) in global cell indices (row = floor(lat*rows), col = floor(lon*cols)) as int8: 1 land, 0 water, -1 no data.""" R, C = self.index.rows, self.index.cols out = np.full((g_row1 - g_row0, g_col1 - g_col0), -1, dtype=np.int8) for ts in range(g_row0 // R, (g_row1 - 1) // R + 1): for tw in range(g_col0 // C, (g_col1 - 1) // C + 1): t = self.tile(ts, tw) r0, r1 = max(g_row0, ts * R), min(g_row1, (ts + 1) * R) c0, c1 = max(g_col0, tw * C), min(g_col1, (tw + 1) * C) dst = out[r0 - g_row0:r1 - g_row0, c0 - g_col0:c1 - g_col0] if isinstance(t, int): dst[:] = -1 if t == NO_DATA else (1 if t == ALL_LAND else 0) else: dst[:] = t.unpack()[r0 - ts * R:r1 - ts * R, c0 - tw * C:c1 - tw * C] return out