#!/usr/bin/env python3 """Check the land/sea mask tiles: read them back through the format and test them. python3 tools/landmask/check.py [--out tools/landmask/out] [--shp PATH/land-polygons-split-4326/land_polygons.shp] 1. Format: index.lmi, every tiles/*.lmt and landmask.lmp decode (CRC checked), tile headers match the index, the folder and the pack hold identical bits, and there is a tile file for exactly the index's mixed tiles. 2. Known places: asserts sea / land at named points (exit status 1 if any fails) and reports harbours, estuaries, lakes and small islands for information, each with the distance to the centre of the nearest mask cell of the other kind. The places are in Britain and Ireland; any outside the tileset's box are skipped, so the script runs unchanged on another region's output (the format checks and the source comparison still apply there). 3. The app's arrow lattice (0.02 degree, points at (i + 1/2) x 0.02 snapped to 0.001 degree as WeatherOverlay.landCheckPoint does): how many points the mask calls water, and how many a 3 x 3 cell margin would take away. Then the Bognor Regis area on that lattice. 4. With --shp (the source the tiles were built from): an independent point-in-polygon test (a northward ray, a different code path from build.py's westward scanlines) at a. cell centres next to the coast and random cell centres: must agree exactly (this is what the mask stores); b. random points anywhere: disagreements are expected only within half a cell's diagonal of the coastline (sampling at cell centres), and the median and largest distance from the source coastline among them are reported; c. the coastal strip: points spread evenly along the source coastline and placed up to 300 m off it either side, and the share the mask gets wrong among those truly within 25, 50, 100 and 200 m of the nearest coastline, and among those placed up to that far off (the accuracy that matters for arrows near the shore; it falls as the cells get smaller); d. small islands (whole source rings up to 60 ha): how many have a cell centre on them, so are land in the mask. It also gives the source's own answer and the distance to the source coastline for each known place. Tiles marked "not covered" (outside the source's extent, e.g. EPSG:3857 beyond +-85.05 degrees) are left out of the comparison. NOTICE.txt without an ODbL 4.6 offer URL is reported (not a failure: it is set at release). """ from __future__ import annotations import argparse import math import sys 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 M_PER_DEG = 111195.0 # metres per degree of latitude (mean Earth radius 6371 km) # (name, lat, lon, note). Sea and land are asserted; the rest are reported only. The asserted points are the brief's # where the source supports them; where it doesn't, the brief's point is reported with the reason and, if the place # has water at all, a nearby point in it is asserted instead. Keep each place on one line: tools/golden reads these # lists with a one-line pattern. SEA = [ ("Solent (mid)", 50.78, -1.20, ""), ("Needles Channel", 50.66, -1.60, ""), ("Poole Bay", 50.70, -1.85, ""), ("Poole Harbour (open water)", 50.6975, -2.0025, "the brief's 50.69,-1.98 is on Brownsea Island"), ("Bristol Channel", 51.35, -3.30, ""), ("Menai Strait (mid-channel)", 53.2145, -4.1940, "the brief's 53.21,-4.19 is on the mainland shore, 570 m SE"), ("Strangford Lough entrance", 54.37, -5.55, ""), ("Dover Strait", 51.0, 1.4, ""), ("Thames (Sea Reach, off Canvey)", 51.495, 0.60, "the source's Thames ends 7 km upstream, at 0.50 E"), ("Humber (2 km below the bridge)", 53.705, -0.42, "the source's Humber ends 1.3 km upstream, at 0.44 W"), ("Dublin Bay", 53.33, -6.12, ""), ] LAND = [ ("Flansham", 50.800, -0.605, ""), ("Yapton", 50.81, -0.57, ""), ("Romney Marsh", 51.03, 0.90, ""), ("The Fens (Wisbech)", 52.66, 0.16, ""), ("Somerset Levels", 51.15, -2.85, ""), ("Canvey Island", 51.52, 0.58, ""), ("London", 51.5, -0.12, "the source's Thames ends at 0.50 E"), ("Dublin city", 53.35, -6.26, ""), # Islands of 7-10 ha that the simplified source had no polygon for. ("St Michael's Mount (island)", 50.1172, -5.4775, "8.6 ha"), ("Looe Island", 50.3369, -4.4519, "9 ha"), ("Burgh Island", 50.2797, -3.9007, "8.4 ha"), ("Bass Rock (island)", 56.0773, -2.6406, "7.6 ha"), ("Craigleith (island)", 56.0735, -2.7200, "7.4 ha"), ("Inner Farne (island)", 55.6164, -1.6554, "6.8 ha"), ("Dalkey Island", 53.2722, -6.0844, "9.5 ha"), ] REPORTED = [ # expected water unless noted # The brief's points that the full OSM land polygons put on land. OSM's coastline (natural=coastline, the only # thing the land polygons are made from) crosses these rivers downstream; the water above that is mapped as # river (natural=water), which the land polygons leave as land. ("Thames at Gravesend (brief)", 51.445, 0.37, "land: the coastline crosses the Thames at 0.50 E, 9 km downstream"), ("Thames at Westminster (brief)", 51.50, -0.122, "land: the coastline crosses the Thames at 0.50 E"), ("Thames at Tower Bridge", 51.5055, -0.0754, "land: the coastline crosses the Thames at 0.50 E"), ("Humber at the bridge (brief)", 53.71, -0.45, "land: the coastline crosses the Humber at 0.44 W, 600 m below"), ("Dublin port (brief)", 53.345, -6.20, "land: the coastline crosses the Liffey at 6.195 W, 750 m NNE"), ("Menai Strait (brief's point)", 53.21, -4.19, "land: on the mainland shore, 400 m from the strait"), ("Poole Harbour (brief's point)", 50.69, -1.98, "land: Brownsea Island (west end)"), ("Chichester Harbour", 50.80, -0.90, ""), ("Langstone Harbour", 50.82, -1.02, ""), ("Portsmouth Harbour", 50.82, -1.11, ""), ("Southampton Water", 50.865, -1.365, ""), ("Morecambe Bay", 54.10, -2.95, "drying flats are water: the coastline is the high-water line"), ("The Wash", 52.95, 0.25, "drying flats are water: the coastline is the high-water line"), ("Off Felpham (1.5 km out)", 50.772, -0.650, ""), ("Felpham village", 50.790, -0.650, "land"), ("Lough Neagh (lake)", 54.60, -6.45, "land: inland water is not in the source"), ("Loch Ness (lake)", 57.26, -4.51, "land: inland water is not in the source"), ("Great Mewstone (island)", 50.3073, -4.1067, "3.2 ha"), ] def parse_args(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--out", default=str(HERE / "out"), help="tile folder (default tools/landmask/out)") p.add_argument("--shp", help="source shapefile for the independent comparison (optional)") p.add_argument("--samples", type=int, default=200000, help="random points per comparison (default 200000)") p.add_argument("--seed", type=int, default=1) return p.parse_args(argv) # ---------------------------------------------------------------------------------------------------------------- def check_format(out: Path) -> lm.LandMask: folder = lm.LandMask(out) idx = folder.index print(f"index: {idx.n_lat} x {idx.n_lon} tiles from {idx.south},{idx.west}; {idx.rows} x {idx.cols} cells per " f"tile; source date {idx.date}") mixed = {(s, w) for s, w, st in idx.tiles() if st == lm.MIXED} files = {p.name for p in (out / "tiles").glob("*.lmt")} expected = {lm.tile_name(s, w) for s, w in mixed} assert files == expected, f"tile files differ from the index: extra {files - expected}, missing {expected - files}" pack_path = out / "landmask.lmp" pack = lm.LandMask(pack_path) if pack_path.exists() else None if pack: assert pack.index.encode() == idx.encode(), "pack index differs from index.lmi" assert set(pack._blobs) == mixed, "pack tiles differ from the index" for s, w in sorted(mixed): t = folder.tile(s, w) # decodes, checks the CRC and the header against the index assert isinstance(t, lm.Tile) if pack: assert np.array_equal(pack.tile(s, w).packed, t.packed), f"pack and folder differ at {lm.tile_name(s, w)}" bits = t.unpack() assert 0 < bits.sum() < bits.size, f"{lm.tile_name(s, w)} is marked mixed but is uniform" counts = {lm.STATUS_NAMES[k]: int((idx.status == k).sum()) for k in range(4)} print(f"format OK: {counts}; {len(mixed)} tile files" + (" and the pack decode identically" if pack else "")) notice = out / "NOTICE.txt" text = notice.read_text() if notice.exists() else "" if "© OpenStreetMap contributors" not in text or "odbl" not in text.lower(): raise AssertionError("NOTICE.txt is missing or lacks the OpenStreetMap attribution and the ODbL") if "available free of charge at:" not in text: print("note: NOTICE.txt has no ODbL 4.6 offer URL yet (build.py --offer-url); set it before release") return folder def nearest_other_m(mask: lm.LandMask, lat: float, lon: float, radius_m: float = 6000.0): """Distance (m) from (lat, lon) to the centre of the nearest cell of the other kind, or None beyond radius.""" R, C = mask.index.rows, mask.index.cols here = mask.is_land(lat, lon) if here is None: return None kx = math.cos(math.radians(lat)) dr = int(radius_m / (M_PER_DEG / R)) + 1 dc = int(radius_m / (M_PER_DEG * kx / C)) + 1 gr, gc = math.floor(lat * R), math.floor(lon * C) win = mask.window(gr - dr, gr + dr + 1, gc - dc, gc + dc + 1) rr, cc = np.nonzero(win == (0 if here else 1)) if len(rr) == 0: return None clat = (gr - dr + rr + 0.5) / R clon = (gc - dc + cc + 0.5) / C d = np.hypot((clat - lat) * M_PER_DEG, (clon - lon) * M_PER_DEG * kx) d = float(d.min()) return d if d <= radius_m else None # ---------------------------------------------------------------------------------------------------------------- # Independent reference: point in polygon by a northward ray (nonzero winding), and distance to the coastline. def _expand(lo: np.ndarray, hi: np.ndarray): """(k, v) for every whole v in each inclusive range [lo[k], hi[k]], as two arrays (empty ranges give nothing).""" n = np.maximum(hi - lo + 1, 0) k = np.repeat(np.arange(len(n)), n) return k, np.arange(int(n.sum())) - np.repeat(np.cumsum(n) - n - lo, n) class _Buckets: """Items filed under every whole key in their [lo, hi] range, for lookup by key (compressed rows).""" def __init__(self, lo: np.ndarray, hi: np.ndarray, n_keys: int): item, key = _expand(lo, hi) order = np.argsort(key, kind="stable") self.items = item[order] self.starts = np.searchsorted(key[order], np.arange(n_keys + 1)) def pairs(self, keys: np.ndarray): """(query, item) for each query's key and each item filed under it.""" q, pos = _expand(self.starts[keys], self.starts[keys + 1] - 1) return q, self.items[pos] class Reference: """The source, read on its own: whether points are land, and how far they are from the coastline. Land: nonzero winding of a ray due north, a different code path from build.py's westward scanlines. A ring can only wind round a point inside its bounding box (any other ring crosses the ray as often one way as the other), so each point is tested against those rings alone, and within a ring against the edges filed under the point's longitude. That keeps the 2.6 million edges of the full-detail OSM land polygons for Britain and Ireland quick. Coastline: every edge except the straight cuts that split the source into pieces of about 1 x 1 degree (an axis-parallel edge on its ring's bounding box within 0.002 degrees of a whole degree; the pieces overlap there in a strip about 110 m wide, reaching 55 m either side of the degree line, and those cuts are not coast). Distances use a local flat-Earth approximation in metres. """ GRID = 0.01 # degrees: the coastline's lookup grid def __init__(self, shp: Path, region): south, north, west, east = region self.proj = p = lm.projection_from_prj(shp) runs = [(west, min(east, 180))] + ([(-180, east - 360)] if east > 180 else []) lim = p.max_lat y0, y1 = float(p.y_of_lat(max(south, -lim))), float(p.y_of_lat(min(north, lim))) # Only rings that meet the region can hold a point in it, so only those are read. boxes = [(float(p.x_of_lon(w)), y0, float(p.x_of_lon(e)), y1) for w, e in runs] self.rings = [r for _, _, rs in lm.read_polygons(shp, boxes) for r in rs] self.box = np.array([(r[:, 0].min(), r[:, 1].min(), r[:, 0].max(), r[:, 1].max()) for r in self.rings], dtype=np.float64).reshape(-1, 4) self._buckets: dict[int, tuple] = {} self.region = (max(south, -lim), min(north, lim), west, east) # Coastline edges in degrees, longitudes unwrapped into the region's own run (only matters across 180). self._lon0, self._lat0 = west - 1.0, self.region[0] - 1.0 n_e = np.array([len(r) - 1 for r in self.rings], dtype=np.int64) a = np.concatenate([r[:-1] for r in self.rings]) if self.rings else np.zeros((0, 2)) b = np.concatenate([r[1:] for r in self.rings]) if self.rings else np.zeros((0, 2)) # The cuts: axis-parallel edges on their ring's bounding box, within 0.002 degrees of a whole degree. cand = np.flatnonzero((a[:, 0] == b[:, 0]) | (a[:, 1] == b[:, 1])) ring_of = np.repeat(np.arange(len(self.rings)), n_e)[cand] ca, cb, rb = a[cand], b[cand], self.box[ring_of] def whole(v): return np.abs(v - np.round(v)) < 0.002 on_box = ((ca[:, 0] == cb[:, 0]) & ((ca[:, 0] == rb[:, 0]) | (ca[:, 0] == rb[:, 2])) & whole(p.lon_of_x(ca[:, 0]))) \ | ((ca[:, 1] == cb[:, 1]) & ((ca[:, 1] == rb[:, 1]) | (ca[:, 1] == rb[:, 3])) & whole(p.lat_of_y(ca[:, 1]))) self.cut_ring = np.zeros(len(self.rings), bool) self.cut_ring[ring_of[on_box]] = True # rings that are pieces of something bigger, not whole islands self.n_cut = int(on_box.sum()) keep = np.ones(len(a), bool) keep[cand[on_box]] = False keep &= (a[:, 0] != b[:, 0]) | (a[:, 1] != b[:, 1]) del cand, ring_of, ca, cb, rb lat_a, lat_b = p.lat_of_y(a[keep, 1]), p.lat_of_y(b[keep, 1]) lon_a, lon_b = self._unwrap(p.lon_of_x(a[keep, 0])), self._unwrap(p.lon_of_x(b[keep, 0])) del a, b, keep self.coast = (lon_a, lat_a, lon_b, lat_b) # The coastline's lookup grid: every edge filed under each GRID-degree cell its bounding box meets. g = self.GRID self._nx = int(math.ceil((east - west + 2.0) / g)) + 1 self._ny = int(math.ceil((self.region[1] - self.region[0] + 2.0) / g)) + 1 e, ix = _expand(self._ix(np.minimum(lon_a, lon_b)), self._ix(np.maximum(lon_a, lon_b))) iy0, iy1 = self._iy(np.minimum(lat_a, lat_b)), self._iy(np.maximum(lat_a, lat_b)) e2, iy = _expand(iy0[e], iy1[e]) e, key = e[e2], iy * self._nx + ix[e2] del e2, iy, ix, iy0, iy1 order = np.argsort(key, kind="stable") self._grid_items = e[order] self._grid_starts = np.searchsorted(key[order], np.arange(self._nx * self._ny + 1)) # -- land ------------------------------------------------------------------------------------------------ def _ring_buckets(self, k: int): if k not in self._buckets: r = self.rings[k] ax, ay, bx, by = r[:-1, 0], r[:-1, 1], r[1:, 0], r[1:, 1] x0, x1 = self.box[k, 0], self.box[k, 2] nb = int(min(4096, max(1, len(ax) // 8))) w = (x1 - x0) / nb if x1 > x0 else 1.0 def bin_of(x): return np.clip(np.floor((x - x0) / w).astype(np.int64), 0, nb - 1) buckets = _Buckets(bin_of(np.minimum(ax, bx)), bin_of(np.maximum(ax, bx)), nb) self._buckets[k] = (ax, ay, bx, by, bin_of, buckets) return self._buckets[k] def _ring_winding(self, k: int, X: np.ndarray, Y: np.ndarray) -> np.ndarray: ax, ay, bx, by, bin_of, buckets = self._ring_buckets(k) out = np.zeros(len(X)) step = 20000 for s in range(0, len(X), step): q, e = buckets.pairs(bin_of(X[s:s + step])) Xq, Yq = X[s:s + step][q], Y[s:s + step][q] a_x, b_x = ax[e], bx[e] straddle = (a_x <= Xq) != (b_x <= Xq) # half-open: a vertex on the ray counts once q, e, Xq, Yq, a_x, b_x = q[straddle], e[straddle], Xq[straddle], Yq[straddle], a_x[straddle], b_x[straddle] a_y, b_y = ay[e], by[e] yx = a_y + (Xq - a_x) * (b_y - a_y) / (b_x - a_x) hit = yx > Yq sign = np.where(b_x > a_x, 1.0, -1.0) # eastward edge above the point: +1 (clockwise outer ring) out[s:s + step] += np.bincount(q[hit], weights=sign[hit], minlength=len(X[s:s + step])) return np.rint(out).astype(np.int64) def winding(self, lat, lon) -> np.ndarray: lat = np.atleast_1d(np.asarray(lat, float)) lon = (np.atleast_1d(np.asarray(lon, float)) + 180.0) % 360.0 - 180.0 px, py = self.proj.x_of_lon(lon), self.proj.y_of_lat(lat) out = np.zeros(len(px), dtype=np.int64) order = np.argsort(px, kind="stable") xs = px[order] lo = np.searchsorted(xs, self.box[:, 0], "left") hi = np.searchsorted(xs, self.box[:, 2], "right") for k in np.nonzero(hi > lo)[0]: cand = order[lo[k]:hi[k]] cand = cand[(py[cand] >= self.box[k, 1]) & (py[cand] <= self.box[k, 3])] if len(cand): out[cand] += self._ring_winding(int(k), px[cand], py[cand]) return out def is_land(self, lat, lon) -> np.ndarray: return self.winding(lat, lon) != 0 # -- coastline ------------------------------------------------------------------------------------------- def _unwrap(self, lon): return self._lon0 + np.mod(np.asarray(lon, float) - self._lon0, 360.0) def _ix(self, lon_u): return np.clip(np.floor((lon_u - self._lon0) / self.GRID).astype(np.int64), 0, self._nx - 1) def _iy(self, lat): return np.clip(np.floor((np.asarray(lat, float) - self._lat0) / self.GRID).astype(np.int64), 0, self._ny - 1) def coast_distance_m(self, lat, lon, radius_m: float = 10000.0) -> np.ndarray: """Distance (m) from each point to the nearest source coastline edge; NaN when none is within radius_m.""" lat = np.atleast_1d(np.asarray(lat, float)) lon_u = self._unwrap(np.atleast_1d(np.asarray(lon, float))) out = np.full(len(lat), np.nan) if not len(self._grid_items) or not len(lat): return out coslat = np.cos(np.radians(lat)) ky = int(math.ceil(radius_m / (M_PER_DEG * self.GRID))) kx = int(math.ceil(radius_m / (M_PER_DEG * max(0.01, float(coslat.min())) * self.GRID))) dy, dx = (g.ravel() for g in np.meshgrid(np.arange(-ky, ky + 1), np.arange(-kx, kx + 1), indexing="ij")) iy0, ix0, starts = self._iy(lat), self._ix(lon_u), self._grid_starts def keys(a, b): # grid cells round points a..b-1 (one repeated at the grid's border only repeats a distance) iy = np.clip(iy0[a:b, None] + dy[None, :], 0, self._ny - 1) ix = np.clip(ix0[a:b, None] + dx[None, :], 0, self._nx - 1) return iy * self._nx + ix # Points in batches of about a million (point, edge) pairs, so memory stays small whatever the radius. per_point = np.concatenate([(starts[k + 1] - starts[k]).sum(axis=1) for k in (keys(a, a + 4096) for a in range(0, len(lat), 4096))]) cum = np.cumsum(per_point) ax, ay, bx, by = self.coast a = 0 while a < len(lat): b = max(a + 1, int(np.searchsorted(cum, (cum[a - 1] if a else 0) + 1_000_000, "right"))) key = keys(a, b) pt = np.repeat(np.arange(b - a), key.shape[1]) key = key.ravel() q, pos = _expand(starts[key], starts[key + 1] - 1) if len(q): q, e = pt[q], self._grid_items[pos] la, lu = lat[a:b][q], lon_u[a:b][q] sx = M_PER_DEG * coslat[a:b][q] Ax, Ay = (ax[e] - lu) * sx, (ay[e] - la) * M_PER_DEG Bx, By = (bx[e] - lu) * sx, (by[e] - la) * M_PER_DEG ex, ey = Bx - Ax, By - Ay L2 = ex * ex + ey * ey t = np.clip(-(Ax * ex + Ay * ey) / np.where(L2 > 0, L2, 1.0), 0.0, 1.0) best = np.full(b - a, np.inf) np.minimum.at(best, q, np.hypot(Ax + t * ex, Ay + t * ey)) best[best > radius_m] = np.nan out[a:b] = best a = b return out def coastal_points(self, rng, n: int, band_m: float): """n points spread evenly along the source coastline (by length), each moved up to band_m metres off it at right angles, uniformly either side: (lat, lon, signed offset in metres).""" ax, ay, bxu, by = self.coast # longitudes unwrapped, so no edge jumps 360 degrees k = M_PER_DEG * np.cos(np.radians(0.5 * (ay + by))) ex, ey = (bxu - ax) * k, (by - ay) * M_PER_DEG length = np.hypot(ex, ey) cum = np.cumsum(length) pos = rng.uniform(0.0, cum[-1], n) e = np.minimum(np.searchsorted(cum, pos, "right"), len(cum) - 1) t = (pos - (cum[e] - length[e])) / np.where(length[e] > 0, length[e], 1.0) off = rng.uniform(-band_m, band_m, n) nx, ny = -ey[e] / length[e], ex[e] / length[e] # unit normal in metres lat = ay[e] + t * (by[e] - ay[e]) + off * ny / M_PER_DEG lon = ax[e] + t * (bxu[e] - ax[e]) + off * nx / k[e] return lat, (lon + 180.0) % 360.0 - 180.0, off def islands(self, max_ha: float): """Whole source rings (not pieces of a bigger polygon) of at most max_ha: (ring index, area in ha).""" out = [] for k, r in enumerate(self.rings): if self.cut_ring[k]: continue lat_c = float(self.proj.lat_of_y(0.5 * (self.box[k, 1] + self.box[k, 3]))) x, y = self.proj.lon_of_x(r[:, 0]), self.proj.lat_of_y(r[:, 1]) area = 0.5 * abs(float(np.sum(x[:-1] * y[1:] - x[1:] * y[:-1]))) * M_PER_DEG ** 2 \ * math.cos(math.radians(lat_c)) / 1e4 if area <= max_ha: out.append((k, area)) return out def fmt_m(d, beyond="> 6 km"): return f"{d:,.0f} m" if d is not None and math.isfinite(d) else beyond def check_places(mask: lm.LandMask, ref: Reference | None): failures = [] skipped = [] def row(name, lat, lon, want, note): if not mask.index.covers(lat, lon): skipped.append(name) return got = mask.is_land(lat, lon) kind = {True: "land", False: "water", None: "no data"}[got] other = nearest_other_m(mask, lat, lon) line = (f" {name:<30} {lat:8.4f},{lon:9.4f} mask {kind:<6} " f"nearest {'water' if got else 'land'} cell {fmt_m(other):>8}") if ref is not None: src = bool(ref.is_land(lat, lon)[0]) d = float(ref.coast_distance_m(lat, lon, 10000.0)[0]) line += f" | source {'land' if src else 'water'}, coastline {fmt_m(d, '> 10 km'):>8}" if note: line += f" ({note})" if want is not None: ok = got == want line = (" PASS" if ok else " FAIL") + line[1:] if not ok: failures.append(name) print(line) for title, places, want in (("Sea (asserted)", SEA, False), ("Land (asserted)", LAND, True), ("Harbours, estuaries, lakes, small islands (reported)", REPORTED, None)): if any(mask.index.covers(la, lo) for _, la, lo, _ in places): print(f"\n{title}:" if want is False else f"{title}:") for n, la, lo, note in places: row(n, la, lo, want, note) total = len(SEA) + len(LAND) + len(REPORTED) if skipped: print(f"\nKnown places: {len(skipped)} of {total} are outside this tileset's box and were skipped " f"(the list is for Britain and Ireland)") return failures def app_snap(v): """WeatherOverlay.landCheckPoint: whole 0.00001 degree units first, then whole 0.001 degrees, halves upwards.""" return np.floor(np.round(np.asarray(v, float) * 1e5) / 100 + 0.5) / 1000 def app_lattice(lo: float, hi: float, step: float) -> np.ndarray: """The app's arrow points along one axis inside [lo, hi): (i + 1/2) x step (WeatherOverlay.GridKey), snapped.""" pts = app_snap((np.arange(math.floor(lo / step) - 1, math.ceil(hi / step) + 1) + 0.5) * step) return pts[(pts >= lo) & (pts < hi)] def lattice_stats(mask: lm.LandMask, step: float = 0.02): """Water points on the app's lattice over the whole tileset, and what a 3 x 3 cell margin (a point is water only if its cell and the 8 around it are all water) would take away. Neighbours outside the tileset are ignored.""" idx = mask.index R, C = idx.rows, idx.cols lats = app_lattice(idx.south, idx.south + idx.n_lat, step) lons = app_lattice(idx.west, idx.west + idx.n_lon, step) g_rows = np.floor(lats * R).astype(np.int64) g_cols = np.floor(lons * C).astype(np.int64) g_row0, g_col0 = idx.south * R, idx.west * C big = mask.window(g_row0 - 1, (idx.south + idx.n_lat) * R + 1, g_col0 - 1, (idx.west + idx.n_lon) * C + 1) rr = (g_rows - g_row0 + 1)[:, None] cc = (g_cols - g_col0 + 1)[None, :] here = big[rr, cc] near_land = np.zeros(here.shape, bool) for dr in (-1, 0, 1): for dc in (-1, 0, 1): near_land |= big[rr + dr, cc + dc] == 1 water = here == 0 kept = water & ~near_land n_water, n_removed = int(water.sum()), int((water & near_land).sum()) print(f"\nApp lattice, {step} deg ((i + 1/2) x step, snapped to 0.001 deg): {lats.size * lons.size:,} points, " f"{n_water:,} water, {int((here == 1).sum()):,} land, {int((here == -1).sum()):,} not covered") if n_water: print(f" a 3 x 3 cell margin would remove {n_removed:,} of the {n_water:,} water points " f"({100 * n_removed / n_water:.2f}%), leaving {int(kept.sum()):,}") def bognor_lattice(mask: lm.LandMask): """The original problem area at the app's 0.02 degree lattice: L = land, . = water.""" if not mask.index.covers(50.78, -0.64): return lons = app_lattice(-0.80, -0.48, 0.02) lats = app_lattice(50.70, 50.87, 0.02)[::-1] print("\nBognor Regis area on the app's 0.02 deg lattice (rows north to south, L land . water):") print(" " + " ".join(f"{abs(x):.2f}"[1:] for x in lons) + " (deg W)") for la in lats: cells = ["L" if mask.is_land(la, lo) else "." for lo in lons] print(f" {la:.2f} " + " ".join(cells)) def compare_with_source(mask: lm.LandMask, ref: Reference, n: int, seed: int): idx = mask.index R, C = idx.rows, idx.cols rng = np.random.default_rng(seed) print(f"\nIndependent comparison with the source ({ref.proj.name}, northward ray, nonzero winding; " f"{len(ref.rings):,} rings, {len(ref.coast[0]):,} coastline edges" + (f", {ref.n_cut:,} edges of the cuts between source pieces left out of the coastline" if ref.n_cut else "") + "):") nearest_equator = 0.0 if idx.south < 0 < idx.south + idx.n_lat else min(abs(idx.south), abs(idx.south + idx.n_lat)) half_diag = 0.5 * math.hypot(M_PER_DEG / R, M_PER_DEG * math.cos(math.radians(nearest_equator)) / C) def covered(lat, lon): """Mask answers at the points (True / False), and which points it covers at all.""" v = mask.lookup(lat, lon) return v == 1, v >= 0 # a. cell centres: next to the coast (cells with a neighbour of the other kind) and uniformly random coast_cells = [] for s, w, st in idx.tiles(): if st == lm.MIXED: t = mask.tile(s, w) if isinstance(t, lm.Tile): b = t.unpack() edge = np.zeros_like(b) edge[1:, :] |= b[1:, :] != b[:-1, :] edge[:-1, :] |= b[1:, :] != b[:-1, :] edge[:, 1:] |= b[:, 1:] != b[:, :-1] edge[:, :-1] |= b[:, 1:] != b[:, :-1] rr, cc = np.nonzero(edge) coast_cells.append(np.stack([s * R + rr, w * C + cc], axis=1)) coast_cells = np.concatenate(coast_cells) if coast_cells else np.zeros((0, 2), np.int64) pick = coast_cells[rng.choice(len(coast_cells), min(n, len(coast_cells)), replace=False)] rand = np.stack([rng.integers(idx.south * R, (idx.south + idx.n_lat) * R, n), rng.integers(idx.west * C, (idx.west + idx.n_lon) * C, n)], axis=1) bad_total = 0 for label, cells in (("cell centres next to the coast", pick), ("random cell centres", rand)): lat = (cells[:, 0] + 0.5) / R lon = (cells[:, 1] + 0.5) / C got, cov = covered(lat, lon) lat, lon, got = lat[cov], lon[cov], got[cov] want = ref.is_land(lat, lon) if len(lat) else np.zeros(0, bool) bad = np.nonzero(got != want)[0] bad_total += len(bad) extra = f" (of {len(coast_cells):,})" if cells is pick else "" extra += f", {int((~cov).sum()):,} not covered left out" if (~cov).any() else "" print(f" {label}: {len(lat):,} checked{extra}, {len(bad)} disagree" + ("" if not len(bad) else f", e.g. {lat[bad[0]]:.5f},{lon[bad[0]]:.5f}")) # b. random points anywhere in the region lat = rng.uniform(idx.south, idx.south + idx.n_lat, n) lon = rng.uniform(idx.west, idx.west + idx.n_lon, n) got, cov = covered(lat, lon) lat, lon, got = lat[cov], lon[cov], got[cov] if len(lat): want = ref.is_land(lat, lon) bad = np.nonzero(got != want)[0] print(f" random points: {len(lat):,} checked, {len(bad)} differ from the source " f"({100 * len(bad) / len(lat):.3f}%): {int(((~want) & got)[bad].sum())} source water / mask land, " f"{int((want & ~got)[bad].sum())} source land / mask water") if len(bad): d = ref.coast_distance_m(lat[bad], lon[bad], 2000.0) print(f" distance from the source coastline: median {np.nanmedian(d):.0f} m, max {np.nanmax(d):.0f} m " f"(half a cell's diagonal is {half_diag:.0f} m)") # c. the coastal strip: points spread evenly along the coastline by length, placed up to 300 m off it either # side. A point's true distance to the nearest coastline can be less than its offset (another stretch of coast # may be nearer), so the share wrong is given both ways: by true distance (what "within 50 m of the coast" # means) and by offset. The sample reaches 300 m so that the 200 m true-distance group is complete except in # channels under about 500 m wide. band = 300.0 lat, lon, off = ref.coastal_points(rng, n, band) got, cov = covered(lat, lon) lat, lon, off, got = lat[cov], lon[cov], off[cov], got[cov] if len(lat): want = ref.is_land(lat, lon) wrong = got != want dist_m = ref.coast_distance_m(lat, lon, band) # NaN beyond band, which compares false below print(f" coastal strip: {len(lat):,} points spread evenly along the source coastline, each placed up to " f"{band:.0f} m off it either side; share the mask gets wrong:") for label, measure in (("truly within", dist_m), ("placed up to", np.abs(off))): for dist in (25, 50, 100, 200): sel = measure <= dist k = max(1, int(sel.sum())) print(f" {label} {dist:>3} m: {100 * int(wrong[sel].sum()) / k:5.2f}% of {int(sel.sum()):,} " f"({100 * int((wrong & got)[sel].sum()) / k:.2f}% water called land, " f"{100 * int((wrong & ~got)[sel].sum()) / k:.2f}% land called water)") if wrong.any(): d = dist_m[wrong] print(f" the wrong points are at most {np.nanmax(d):.0f} m from the source coastline, median " f"{np.nanmedian(d):.0f} m (half a cell's diagonal is {half_diag:.0f} m)") # d. small islands: whole source rings, and how many have a cell centre inside (so land in the mask) s0, s1, w0, w1 = idx.south, idx.south + idx.n_lat, idx.west, idx.west + idx.n_lon classes = [(0, 1), (1, 5), (5, 10), (10, 60)] found = {c: [0, 0] for c in classes} for k, area in ref.islands(classes[-1][1]): b = ref.box[k] lat0, lat1 = float(ref.proj.lat_of_y(b[1])), float(ref.proj.lat_of_y(b[3])) lon0, lon1 = float(ref.proj.lon_of_x(b[0])), float(ref.proj.lon_of_x(b[2])) if not (s0 <= lat0 and lat1 < s1 and w0 <= lon0 and lon1 < w1): continue rows = np.arange(math.ceil(lat0 * R - 0.5), math.floor(lat1 * R - 0.5) + 1) cols = np.arange(math.ceil(lon0 * C - 0.5), math.floor(lon1 * C - 0.5) + 1) kept = False if len(rows) and len(cols): clat, clon = np.meshgrid((rows + 0.5) / R, (cols + 0.5) / C, indexing="ij") clat, clon = clat.ravel(), clon.ravel() inside = ref._ring_winding(k, ref.proj.x_of_lon(clon), ref.proj.y_of_lat(clat)) != 0 kept = bool(inside.any()) and bool((mask.lookup(clat[inside], clon[inside]) == 1).any()) for c in classes: if c[0] < area <= c[1]: found[c][0] += 1 found[c][1] += kept print(" small islands (whole source rings) with a cell centre on them, so land in the mask: " + ", ".join(f"{a}-{b} ha {found[(a, b)][1]:,} of {found[(a, b)][0]:,}" for a, b in classes)) return bad_total def main(argv=None): a = parse_args(argv) out = Path(a.out) mask = check_format(out) ref = None if a.shp: idx = mask.index ref = Reference(Path(a.shp), (idx.south, idx.south + idx.n_lat, idx.west, idx.west + idx.n_lon)) failures = check_places(mask, ref) lattice_stats(mask) bognor_lattice(mask) bad_cells = compare_with_source(mask, ref, a.samples, a.seed) if ref is not None else 0 print() if failures: print(f"FAILED places: {', '.join(failures)}") if bad_cells: print(f"FAILED: {bad_cells} cell centres disagree with the independent source test") if not failures and not bad_cells: print("All checks passed.") return 1 if failures or bad_cells else 0 if __name__ == "__main__": sys.exit(main())