GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / cosmic / tools/lidar

LiDAR Build Tiles and 2 more files

A Python command-line tool in the tools folder of Cosmic that reads probe and LiDAR terrain, using EPSG:27700 and EPSG:3857. It encodes image (`encode_image`) and writes PMTiles (`write_pmtiles`).

549 lines of Python from cosmic, data-centres-gb, in 3 files. Topic: Maps, GIS and field navigation. Section 470 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. LiDAR Build Tiles geodesy · cosmic / tools/lidar/build_tiles.py lines 1–275
  2. LiDAR Fetch DTM storage · cosmic / tools/lidar/fetch_dtm.py lines 1–157
  3. Test OSM Data Centres test · data-centres-gb / tests/test_202608281053_osm_data_centres.py lines 1–117

LiDAR Build Tiles

A Python command-line tool in the tools folder of Cosmic that reads probe and LiDAR terrain, using EPSG:27700 and EPSG:3857. It encodes image (`encode_image`) and writes PMTiles (`write_pmtiles`).

geodesycosmic / tools/lidar/build_tiles.py · lines 1–275 of 275 · Entry point · pattern _gdal (shared by 2 files)

What it does
It loads probe and LiDAR terrain. Defines 14 functions or classes, including tile_res, lonlat_to_tile, tile_bounds_3857, tile_range, terrarium_encode. Uses libraries __future__, argparse, io, json, math. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: command-line arguments. Out: JSON file index.json; JSON file probe.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
EA 1 m DTM (EPSG:27700) -> Terrarium height tiles on the Web-Mercator `z/x/y` grid (TRIGPOINT-62, LiDAR PoC). It accepts `--src`, `--square` and `--bng`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/lidar · Python CLI
Uses
LiDAR Fetch DTM (import), __future__, argparse, io, json, math, statistics, subprocess, sys
Used by
none found
Produces
tile_res, lonlat_to_tile, tile_bounds_3857, tile_range, terrarium_encode, terrarium_decode, encode_image, square_bbox_ll, projection_used, warp_zoom, stats, write_pmtiles
Defines here
tile_res, lonlat_to_tile, tile_bounds_3857, tile_range, terrarium_encode, terrarium_decode, encode_image, _gdal, square_bbox_ll, projection_used, warp_zoom, stats, write_pmtiles, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/lidar/build_tiles.py:1-275 · blob 54038464a66b08bcec561b622e4d10ee0af5cdde · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unknown
#!/usr/bin/env python3
"""EA 1 m DTM (EPSG:27700) -> Terrarium height tiles on the Web-Mercator z/x/y grid (TRIGPOINT-62, LiDAR PoC).

Each zoom is warped straight from the 1 m source (never from encoded tiles), on bounds snapped to the exact
tile grid, so every height tile lines up 1:1 with the Esri/AWS z/x/y tiles. Heights are quantised to --vstep metres
and encoded Terrarium (h = R*256 + G + B/256 - 32768, the AWS elevation-tiles-prod encoding Pilot already reads).
Pixels with no LiDAR (sea, voids, outside the source) get alpha 0, so the reader falls back to AWS there; tiles with
no LiDAR at all are not written.

Outputs, under --out:
  <dir>/{z}/{x}/{y}.png|webp   small tile files (what Pages serves)
  <name>.pmtiles               the same tiles in one PMTiles v3 file (for object storage later), if pmtiles is installed
  index.json                   square, bbox, zooms, URL template, every tile's bytes, per-zoom byte stats, source,
                               licence, reprojection used
  probe.json                   (--probe) z16 bytes for other encodings, measured on the same tiles
Needs GDAL Python bindings (apt python3-gdal), numpy, Pillow.
Run:  python3 build_tiles.py --src work/src/*.tif --square TR06 --sources work/src/sources.json --out work/out
"""
from __future__ import annotations

import argparse, io, json, math, statistics, subprocess, sys, time
from pathlib import Path

import numpy as np
from PIL import Image

R = 6378137.0
ORIGIN = math.pi * R                       # 20037508.342789244
NODATA = -99999.0
ATTRIBUTION = 'Contains Environment Agency information © Environment Agency and/or database right, OGL v3'


def tile_res(z: int) -> float:
    return 2 * ORIGIN / (256 * 2 ** z)


def lonlat_to_tile(lon: float, lat: float, z: int) -> tuple[float, float]:
    n = 2 ** z
    r = math.radians(lat)
    return (lon + 180) / 360 * n, (1 - math.log(math.tan(r) + 1 / math.cos(r)) / math.pi) / 2 * n


def tile_bounds_3857(x: int, y: int, z: int) -> tuple[float, float, float, float]:
    s = 2 * ORIGIN / 2 ** z
    return -ORIGIN + x * s, ORIGIN - (y + 1) * s, -ORIGIN + (x + 1) * s, ORIGIN - y * s


def tile_range(bbox_ll: tuple[float, float, float, float], z: int) -> tuple[int, int, int, int]:
    """(x0, y0, x1, y1) inclusive tile range covering a lon/lat bbox (w, s, e, n)."""
    w, s, e, n = bbox_ll
    x0, y0 = lonlat_to_tile(w, n, z)
    x1, y1 = lonlat_to_tile(e, s, z)
    return int(math.floor(x0)), int(math.floor(y0)), int(math.floor(x1 - 1e-9)), int(math.floor(y1 - 1e-9))


def terrarium_encode(h: np.ndarray, vstep: float) -> np.ndarray:
    """float heights (NaN = none) -> HxWx4 uint8 RGBA, alpha 0 where NaN. Quantised to vstep metres."""
    ok = np.isfinite(h)
    q = np.where(ok, h, 0.0).astype(np.float64)
    if vstep > 0:
        q = np.round(q / vstep) * vstep
    v = np.clip(q + 32768.0, 0, 65535.99609375)
    fl = np.floor(v)
    out = np.zeros(h.shape + (4,), np.uint8)
    out[..., 0] = (fl // 256).astype(np.uint8)
    out[..., 1] = (fl % 256).astype(np.uint8)
    out[..., 2] = np.floor((v - fl) * 256).astype(np.uint8)
    out[..., 3] = np.where(ok, 255, 0).astype(np.uint8)
    out[~ok, :3] = 0
    return out


def terrarium_decode(rgba: np.ndarray) -> np.ndarray:
    r, g, b = (rgba[..., i].astype(np.float64) for i in range(3))
    h = r * 256 + g + b / 256 - 32768
    if rgba.shape[-1] == 4:
        h = np.where(rgba[..., 3] > 0, h, np.nan)
    return h


def encode_image(rgba: np.ndarray, fmt: str) -> bytes:
    """PNG (RGB when every pixel has data, else RGBA) or lossless WebP."""
    full = bool((rgba[..., 3] == 255).all())
    im = Image.fromarray(rgba[..., :3] if full else rgba, 'RGB' if full else 'RGBA')
    b = io.BytesIO()
    if fmt == 'webp':
        im.save(b, 'WEBP', lossless=True, quality=100, method=6, exact=True)
    else:
        im.save(b, 'PNG', optimize=True, compress_level=9)
    return b.getvalue()


def _gdal():
    from osgeo import gdal
    gdal.UseExceptions()
    return gdal


def square_bbox_ll(bng: tuple[int, int, int, int]):
    """WGS84 lon/lat bbox (w, s, e, n) of a BNG box, densified edges, with whatever transformation PROJ picks."""
    from osgeo import osr
    src = osr.SpatialReference(); src.ImportFromEPSG(27700)
    dst = osr.SpatialReference(); dst.ImportFromEPSG(4326)
    dst.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    src.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    ct = osr.CoordinateTransformation(src, dst)
    e0, n0, e1, n1 = bng
    pts = [(e0 + (e1 - e0) * i / 20, n) for i in range(21) for n in (n0, n1)] + \
          [(e, n0 + (n1 - n0) * i / 20) for i in range(21) for e in (e0, e1)]
    ll = [ct.TransformPoint(e, n)[:2] for e, n in pts]
    return (min(p[0] for p in ll), min(p[1] for p in ll), max(p[0] for p in ll), max(p[1] for p in ll))


def projection_used() -> dict:
    """The EPSG:27700 -> EPSG:3857 operation PROJ chooses here (first candidate), and whether it is OSTN15."""
    try:
        out = subprocess.run(['projinfo', '-s', 'EPSG:27700', '-t', 'EPSG:3857', '--spatial-test', 'intersects',
                              '--summary'], capture_output=True, text=True, timeout=60).stdout
        lines = [l.strip() for l in out.splitlines() if l.strip() and not l.startswith('Candidate')]
        first = lines[0] if lines else ''
        return {'operation': first, 'ostn15': 'OSTN15' in first}
    except Exception as e:
        return {'operation': f'unknown ({e})', 'ostn15': False}


def warp_zoom(src_paths: list[str], rng, z: int, resample: str) -> np.ndarray:
    """Float32 heights (NaN = none) for tile range rng at zoom z, warped from the 1 m source on the tile grid."""
    from osgeo import gdal
    x0, y0, x1, y1 = rng
    w0, _, _, n1 = tile_bounds_3857(x0, y0, z)
    _, s0, e1, _ = tile_bounds_3857(x1, y1, z)
    vrt = gdal.BuildVRT('/vsimem/src.vrt', src_paths)
    nd = vrt.GetRasterBand(1).GetNoDataValue()
    res = tile_res(z)
    ds = gdal.Warp('', vrt, format='MEM', dstSRS='EPSG:3857', outputBounds=(w0, s0, e1, n1),
                   width=(x1 - x0 + 1) * 256, height=(y1 - y0 + 1) * 256, resampleAlg=resample,
                   srcNodata=nd, dstNodata=NODATA, outputType=gdal.GDT_Float32, multithread=True,
                   warpMemoryLimit=1024, errorThreshold=0.0)
    a = ds.GetRasterBand(1).ReadAsArray().astype(np.float32)
    assert abs(ds.GetGeoTransform()[1] - res) < 1e-6, 'warp did not land on the tile grid'
    ds = None; vrt = None; gdal.Unlink('/vsimem/src.vrt')
    a[(a <= NODATA + 1) | (a < -1000) | (a > 2000)] = np.nan    # EA heights are metres ODN; outside this is not ground
    return a


def stats(sizes: list[int]) -> dict:
    if not sizes:
        return {'count': 0}
    s = sorted(sizes)
    return {'count': len(s), 'bytes_total': sum(s), 'bytes_mean': round(sum(s) / len(s)),
            'bytes_median': int(statistics.median(s)), 'bytes_p95': s[min(len(s) - 1, int(0.95 * len(s)))],
            'bytes_min': s[0], 'bytes_max': s[-1]}


def write_pmtiles(path: Path, tiles: dict, zooms, bbox_ll, fmt: str, meta: dict) -> bool:
    try:
        from pmtiles.tile import zxy_to_tileid, TileType, Compression
        from pmtiles.writer import Writer
    except Exception:
        print('pmtiles not installed; skipping the .pmtiles file', file=sys.stderr)
        return False
    w_, s_, e_, n_ = bbox_ll
    with open(path, 'wb') as f:
        wr = Writer(f)
        for tid, data in sorted((zxy_to_tileid(z, x, y), d) for (z, x, y), d in tiles.items()):
            wr.write_tile(tid, data)
        wr.finalize({'tile_type': TileType.WEBP if fmt == 'webp' else TileType.PNG,
                     'tile_compression': Compression.NONE, 'min_zoom': min(zooms), 'max_zoom': max(zooms),
                     'min_lon_e7': int(w_ * 1e7), 'min_lat_e7': int(s_ * 1e7), 'max_lon_e7': int(e_ * 1e7),
                     'max_lat_e7': int(n_ * 1e7), 'center_zoom': max(zooms),
                     'center_lon_e7': int((w_ + e_) / 2 * 1e7), 'center_lat_e7': int((s_ + n_) / 2 * 1e7)}, meta)
    return True


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--src', nargs='+', required=True, help='EPSG:27700 GeoTIFF(s) covering the square')
    ap.add_argument('--square', default='TR06')
    ap.add_argument('--bng', nargs=4, type=int, help='e0 n0 e1 n1 (default: from --sources or the square name)')
    ap.add_argument('--sources', type=Path, help='sources.json from fetch_dtm.py')
    ap.add_argument('--out', type=Path, required=True)
    ap.add_argument('--zooms', nargs='+', type=int, default=[14, 15, 16])
    ap.add_argument('--format', choices=('png', 'webp'), default='png')
    ap.add_argument('--vstep', type=float, default=0.0625, help='height quantum in metres (0 = keep 1/256 m)')
    ap.add_argument('--resample', default='average')
    ap.add_argument('--probe', action='store_true', help='also measure z16 bytes for other encodings')
    ap.add_argument('--probe-every', type=int, default=25, help='probe every Nth z16 tile (WebP method 6 is slow)')
    ap.add_argument('--max-total-mb', type=float, default=300.0, help='fail above this (protects the 1 GB Pages site)')
    ap.add_argument('--run-url', default='')
    a = ap.parse_args(argv)

    src_meta = json.loads(a.sources.read_text()) if a.sources and a.sources.is_file() else {}
    if a.bng:
        bng = tuple(a.bng)
    elif src_meta.get('bng_bbox'):
        bng = tuple(src_meta['bng_bbox'])
    else:
        sys.path.insert(0, str(Path(__file__).resolve().parent))
        from fetch_dtm import os_ref_to_en
        e0, n0 = os_ref_to_en(a.square); bng = (e0, n0, e0 + 10000, n0 + 10000)
    _gdal()
    sq = a.square.lower()
    bbox_ll = square_bbox_ll(bng)
    proj = projection_used()
    print(f'{a.square}: BNG {bng} -> lon/lat {tuple(round(v, 5) for v in bbox_ll)}; {proj["operation"]}')

    tiles: dict[tuple[int, int, int], bytes] = {}
    sizes: dict[int, list[int]] = {}
    probe: dict = {}
    t0 = time.time()
    for z in sorted(a.zooms):
        rng = tile_range(bbox_ll, z)
        h = warp_zoom(a.src, rng, z, a.resample)
        x0, y0, x1, y1 = rng
        sizes[z] = []
        for ty in range(y0, y1 + 1):
            for tx in range(x0, x1 + 1):
                blk = h[(ty - y0) * 256:(ty - y0 + 1) * 256, (tx - x0) * 256:(tx - x0 + 1) * 256]
                if not np.isfinite(blk).any():
                    continue
                rgba = terrarium_encode(blk, a.vstep)
                data = encode_image(rgba, a.format)
                tiles[(z, tx, ty)] = data
                sizes[z].append(len(data))
                p = a.out / sq / str(z) / str(tx) / f'{ty}.{a.format}'
                p.parent.mkdir(parents=True, exist_ok=True)
                p.write_bytes(data)
                if a.probe and z == max(a.zooms) and len(sizes[z]) % a.probe_every == 1:
                    for name, vs, fm in (('png_vstep_1/256', 0, 'png'), ('png_vstep_0.0625', 0.0625, 'png'),
                                         ('png_vstep_0.25', 0.25, 'png'), ('webp_vstep_0.0625', 0.0625, 'webp'),
                                         ('webp_vstep_1/256', 0, 'webp')):
                        probe.setdefault(name, []).append(len(encode_image(terrarium_encode(blk, vs), fm)))
        print(f'z{z}: range x {x0}-{x1} y {y0}-{y1}, {len(sizes[z])} tiles, {sum(sizes[z]):,} B '
              f'({time.time() - t0:.0f} s)')
        del h

    total = sum(len(d) for d in tiles.values())
    zst = {str(z): stats(sizes[z]) for z in sorted(sizes)}
    z16 = sizes.get(max(a.zooms), [])
    tile_m = 2 * ORIGIN / 2 ** max(a.zooms) * math.cos(math.radians((bbox_ll[1] + bbox_ll[3]) / 2))
    rel = f'{sq}/{{z}}/{{x}}/{{y}}.{a.format}'
    entry = {
        'id': a.square.upper(), 'bng_bbox': list(bng), 'bbox': [round(v, 6) for v in bbox_ll],
        'zooms': sorted(a.zooms), 'encoding': 'terrarium', 'format': a.format, 'vstep_m': a.vstep,
        'nodata': 'alpha 0', 'tile_px': 256, 'tile_m_at_centre': round(tile_m, 1),
        'tiles_url': rel, 'pmtiles': f'lidar-{sq}.pmtiles',
        'tiles': {f'{z}/{x}/{y}': len(d) for (z, x, y), d in sorted(tiles.items())},
        'stats': zst, 'total_bytes': total,
        'built_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'build_seconds': round(time.time() - t0),
        'reprojection': proj, 'resample': a.resample,
        'source': {k: src_meta.get(k) for k in ('source', 'product', 'publisher', 'host', 'fetched_utc', 'files')}
                  if src_meta else {'files': [Path(p).name for p in a.src]},
        'licence': 'OGL-3.0', 'licence_url': 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/',
        'attribution': ATTRIBUTION, 'run_url': a.run_url,
    }
    a.out.mkdir(parents=True, exist_ok=True)
    idx = {'schema': 'cosmic.lidar-index.v1', 'generated_utc': entry['built_utc'], 'squares': [entry]}
    (a.out / 'index.json').write_text(json.dumps(idx, separators=(',', ':')))
    if probe:
        (a.out / 'probe.json').write_text(json.dumps({'note': f'every {a.probe_every}th z{max(a.zooms)} tile, same heights',
                                                       **{k: stats(v) for k, v in probe.items()}}, indent=1))
    pm = write_pmtiles(a.out.parent / f'lidar-{sq}.pmtiles', tiles, a.zooms, bbox_ll, a.format,
                       {'name': f'EA LiDAR DTM {a.square.upper()}', 'attribution': ATTRIBUTION, 'encoding': 'terrarium',
                        'vstep_m': a.vstep, 'licence': 'OGL-3.0'})
    print(json.dumps({'total_bytes': total, 'tiles': len(tiles), 'stats': zst, 'pmtiles': pm}, indent=1))
    if z16 and statistics.median(z16) > 150_000:
        print(f'::warning::z16 median {int(statistics.median(z16)):,} B is over the VERDICT stop line (150 KB)')
    if total > a.max_total_mb * 1e6:
        print(f'::error::{total:,} B is over --max-total-mb {a.max_total_mb}', file=sys.stderr)
        return 3
    return 0


if __name__ == '__main__':
    sys.exit(main())

LiDAR Fetch DTM

A Python command-line tool in the tools folder of Cosmic that fetches ea LiDAR DTM 1m items, sources and LiDAR terrain, using EPSG:27700 and SHA-256 from Environment Agency.

storagecosmic / tools/lidar/fetch_dtm.py · lines 1–157 of 157 · Entry point · pattern _exists (shared by 3 files)

What it does
It fetches ea LiDAR DTM 1m items, sources and LiDAR terrain. Defines 9 functions or classes, including os_ref_to_en, idx, _get, _download, _exists. Uses libraries __future__, argparse, hashlib, json, sys. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'dtm'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: data source: Environment Agency; JSON file ea-lidar-dtm-1m-items.json; command-line arguments. Out: JSON file sources.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: LiDAR Build Tiles (cosmic).
What it achieves
It fetches sourcecoop (`fetch_sourcecoop`) and fetches wcs (`fetch_wcs`). Download the Environment Agency 1 m LiDAR DTM for one OS 10 km square (TRIGPOINT-62, LiDAR PoC). It accepts `--square`, `--out` and `--source`.
Why it matters
Imported by LiDAR Build Tiles.
Application
cosmic · tools/lidar · Python CLI
Uses
__future__, argparse, hashlib, json, sys, time, urllib.error, urllib.request
Used by
imported by LiDAR Build Tiles (import)
Produces
os_ref_to_en, sourcecoop_hrefs, fetch_sourcecoop, fetch_wcs, main
Defines here
os_ref_to_en, idx, _get, _download, _exists, sourcecoop_hrefs, fetch_sourcecoop, fetch_wcs, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/lidar/fetch_dtm.py:1-157 · blob c4e55c33846fdb239cf5198e40263f07ede1ca63 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
"""Download the Environment Agency 1 m LiDAR DTM for one OS 10 km square (TRIGPOINT-62, LiDAR PoC).

Free sources only, tried in this order:
  1. Source Cooperative "rebalance-earth/ea-dem" COGs (EA LIDAR Composite DTM 1 m, OGL v3, EPSG:27700,
     5 km tiles named <10km square><quadrant>_DTM_1m.tif, e.g. TR06ne_DTM_1m.tif). The STAC item list
     ea-lidar-dtm-1m-items.json gives the hrefs (DTM/DEFLATE/...); the LERC copy (2 cm max error, smaller) is tried
     first at the same name under DTM/LERC/.
  2. The EA's own WCS 2.0.1 GetCoverage service for the same product (the service the estate already used;
     ventus-grid-engine docs/site-tile.md). It refused about 10 requests in 3 minutes, so requests are 40 s apart.

Writes <out>/*.tif and <out>/sources.json (URL, bytes, sha256 of every file). Standard library only.
Run:  python3 fetch_dtm.py --square TR06 --out work/src [--source auto|sourcecoop|ea-wcs]
"""
from __future__ import annotations

import argparse, hashlib, json, sys, time, urllib.error, urllib.request
from pathlib import Path

SC_BASE = 'https://data.source.coop/rebalance-earth/ea-dem/'
SC_ITEMS = SC_BASE + 'ea-lidar-dtm-1m-items.json'
WCS_BASE = 'https://environment.data.gov.uk/spatialdata/lidar-composite-digital-terrain-model-dtm-1m/wcs'
WCS_COVERAGE = '13787b9a-26a4-4775-8523-806d13af58fc__Lidar_Composite_Elevation_DTM_1m'
UA = 'cosmic-lidar-poc/1 (GitHub Actions)'
QUADS = {'sw': (0, 0), 'se': (5000, 0), 'nw': (0, 5000), 'ne': (5000, 5000)}


def os_ref_to_en(ref: str) -> tuple[int, int]:
    """OS grid reference of a 10 km square ('TR06') -> (easting, northing) of its south-west corner in metres."""
    ref = ref.strip().upper().replace(' ', '')
    if len(ref) != 4 or not ref[:2].isalpha() or not ref[2:].isdigit():
        raise ValueError(f'expected a 10 km square like TR06, got {ref!r}')
    def idx(c):
        i = ord(c) - ord('A')
        return i - 1 if i > 7 else i          # the grid has no I
    l1, l2 = idx(ref[0]), idx(ref[1])
    e100 = ((l1 - 2) % 5) * 5 + (l2 % 5)
    n100 = (19 - (l1 // 5) * 5) - (l2 // 5)
    return e100 * 100000 + int(ref[2]) * 10000, n100 * 100000 + int(ref[3]) * 10000


def _get(url: str, timeout: int = 120, method: str = 'GET') -> urllib.request.addinfourl:
    req = urllib.request.Request(url, method=method, headers={'User-Agent': UA})
    return urllib.request.urlopen(req, timeout=timeout)


def _download(url: str, dst: Path, tries: int = 3) -> dict:
    for k in range(tries):
        try:
            h = hashlib.sha256(); n = 0; t0 = time.time()
            with _get(url, timeout=300) as r, open(dst, 'wb') as f:
                while True:
                    b = r.read(1 << 20)
                    if not b:
                        break
                    f.write(b); h.update(b); n += len(b)
            return {'url': url, 'file': dst.name, 'bytes': n, 'sha256': h.hexdigest(), 'seconds': round(time.time() - t0, 1)}
        except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
            if isinstance(e, urllib.error.HTTPError) and e.code in (403, 404):
                raise
            print(f'  retry {k + 1}/{tries} {url}: {e}', file=sys.stderr); time.sleep(10 * (k + 1))
    raise RuntimeError(f'could not download {url}')


def _exists(url: str) -> bool:
    try:
        with _get(url, timeout=60, method='HEAD') as r:
            return r.status == 200
    except Exception:
        return False


def sourcecoop_hrefs(square: str) -> list[str]:
    """DEFLATE hrefs of the 5 km tiles in this square, from the STAC item list (fallback: the known file names)."""
    sq = square.upper()
    try:
        with _get(SC_ITEMS, timeout=300) as r:
            items = json.load(r)
        hrefs = []
        for f in items.get('features', []):
            tile = str(f.get('properties', {}).get('ea:os_grid_tile', ''))
            if tile.upper().startswith(sq) and len(tile) == len(sq) + 2:
                href = (f.get('assets', {}).get('dtm') or {}).get('href')
                if href:
                    hrefs.append(href)
        print(f'STAC: {len(hrefs)} tiles for {sq}')
        if hrefs:
            return sorted(hrefs)
    except Exception as e:
        print(f'STAC item list unavailable ({e}); using the file-name pattern', file=sys.stderr)
    return [f'{SC_BASE}DTM/DEFLATE/{sq}{q}_DTM_1m.tif' for q in QUADS]


def fetch_sourcecoop(square: str, out: Path) -> list[dict]:
    got = []
    for href in sourcecoop_hrefs(square):
        name = href.rsplit('/', 1)[1]
        lerc = href.replace('/DTM/DEFLATE/', '/DTM/LERC/')
        for url, variant in ((lerc, 'LERC'), (href, 'DEFLATE')):
            if url == lerc and (lerc == href or not _exists(lerc)):
                continue
            try:
                rec = _download(url, out / name); rec['variant'] = variant
                got.append(rec); print(f"  {name} {variant} {rec['bytes']:,} B in {rec['seconds']} s"); break
            except urllib.error.HTTPError as e:
                print(f'  {url}: HTTP {e.code}', file=sys.stderr)
    return got


def fetch_wcs(square: str, out: Path, pause: float = 40.0) -> list[dict]:
    e0, n0 = os_ref_to_en(square)
    cuts = [0, 3400, 6800, 10000]          # 3 x 3 boxes of <= 3.4 km (<= 46 MB float32 each)
    got = []
    for j in range(3):
        for i in range(3):
            a, b, c, d = e0 + cuts[i], e0 + cuts[i + 1], n0 + cuts[j], n0 + cuts[j + 1]
            url = (f'{WCS_BASE}?service=WCS&version=2.0.1&request=GetCoverage&CoverageId={WCS_COVERAGE}'
                   f'&format=image/tiff&subset=E({a},{b})&subset=N({c},{d})')
            if got:
                time.sleep(pause)           # polite pace (estate rule: >= 40 s apart)
            rec = _download(url, out / f'{square}_wcs_{i}{j}.tif'); rec['variant'] = 'WCS float32'
            got.append(rec); print(f"  box {i}{j} {rec['bytes']:,} B in {rec['seconds']} s")
    return got


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--square', default='TR06')
    ap.add_argument('--out', type=Path, required=True)
    ap.add_argument('--source', choices=('auto', 'sourcecoop', 'ea-wcs'), default='auto')
    a = ap.parse_args(argv)
    a.out.mkdir(parents=True, exist_ok=True)
    e0, n0 = os_ref_to_en(a.square)
    files, used = [], None
    if a.source in ('auto', 'sourcecoop'):
        files = fetch_sourcecoop(a.square, a.out); used = 'sourcecoop'
    if not files and a.source in ('auto', 'ea-wcs'):
        files = fetch_wcs(a.square, a.out); used = 'ea-wcs'
    if not files:
        print('no DTM downloaded from any source', file=sys.stderr); return 2
    meta = {
        'square': a.square.upper(), 'bng_bbox': [e0, n0, e0 + 10000, n0 + 10000], 'crs': 'EPSG:27700',
        'source': used,
        'product': 'Environment Agency LIDAR Composite DTM, 1 m (National LIDAR Programme and earlier surveys)',
        'publisher': 'Environment Agency', 'licence': 'OGL-3.0',
        'licence_url': 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/',
        'host': {'sourcecoop': 'https://source.coop/rebalance-earth/ea-dem', 'ea-wcs': WCS_BASE}[used],
        'fetched_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'files': files,
        'bytes': sum(f['bytes'] for f in files),
    }
    (a.out / 'sources.json').write_text(json.dumps(meta, indent=1))
    print(f"{len(files)} files, {meta['bytes']:,} B from {used}")
    return 0


if __name__ == '__main__':
    sys.exit(main())

Test OSM Data Centres

A test in the tests folder of Data Centres GB. It sets up (`setUp`) and is built from the OSM data centres tests class (`OSMDataCentresTests`).

testdata-centres-gb / tests/test_202608281053_osm_data_centres.py · lines 1–117 of 117 · version 2026-08-28 10:53 · Entry point

What it does
It tests its inputs. Defines 8 functions or classes, including OSMDataCentresTests, setUp, test_doctor_and_query_rights_boundary, test_normalisation_preserves_source_identity_and_abstains, test_contributor_identity_is_not_in_published_schema_or_rows. Uses libraries __future__, copy, importlib.util, json, tempfile. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Downstream impact
Used directly by 1 file: CI Workflow (data-centres-gb).
What it achieves
Defines `OSMDataCentresTests`, `setUp`, `test_doctor_and_query_rights_boundary` and 5 more.
Why it matters
Run by CI Workflow.
Application
data-centres-gb · tests · test
Uses
__future__, copy, importlib.util, json, tempfile, unittest, pathlib
Used by
run by CI Workflow (workflow run)
Produces
OSMDataCentresTests
Defines here
OSMDataCentresTests, setUp, test_doctor_and_query_rights_boundary, test_normalisation_preserves_source_identity_and_abstains, test_contributor_identity_is_not_in_published_schema_or_rows, test_build_verify_and_double_compile_are_deterministic, test_rejects_empty_partial_wrong_endpoint_and_duplicate_payloads, test_bbc_record_is_link_only_and_not_project_bound
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-centres-gb@12c24a653e9d4eb3507857fd6e6d169b2dd1ff63 tests/test_202608281053_osm_data_centres.py:1-117 · blob 9a0941cfc33ab3f4a51feeeae85bacc7a1641978 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
from __future__ import annotations

import copy
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "build/python/202608281053-osm-data-centres.py"
SPEC = importlib.util.spec_from_file_location("osm_data_centres_202608281053", MODULE_PATH)
assert SPEC and SPEC.loader
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)
SOURCE_COMMIT = "a" * 40


class OSMDataCentresTests(unittest.TestCase):
    def setUp(self) -> None:
        self.fixture = MODULE.load_json(ROOT / MODULE.FIXTURE_REL)

    def test_doctor_and_query_rights_boundary(self) -> None:
        result = MODULE.doctor(ROOT)
        self.assertEqual(result["status"], "PASS")
        manifest = MODULE.load_json(ROOT / MODULE.MANIFEST_REL)
        self.assertEqual(manifest["excluded_sources"]["datacentermap"]["network_requests"], 0)
        self.assertEqual(manifest["excluded_sources"]["datacentermap"]["rows_copied"], 0)
        self.assertEqual(manifest["visual_validation"]["openinframap"]["network_requests"], 0)
        self.assertEqual(manifest["overpass"]["query_sha256"], MODULE.query_sha(ROOT))

    def test_normalisation_preserves_source_identity_and_abstains(self) -> None:
        elements, relationships = MODULE.normalise(self.fixture, ROOT)
        self.assertEqual(
            [row[0] for row in elements],
            ["DCGB-OSM-NODE-1001", "DCGB-OSM-RELATION-3003", "DCGB-OSM-WAY-2002"],
        )
        self.assertEqual(len(relationships), len(elements) * 2)
        relationship_columns = {name: index for index, (name, _type, _required) in enumerate(MODULE.RELATIONSHIP_SCHEMA)}
        for row in relationships:
            self.assertIsNone(row[relationship_columns["data_centre_id"]])
            self.assertIsNone(row[relationship_columns["company_number"]])
            self.assertIsNone(row[relationship_columns["match_score"]])
            self.assertEqual(row[relationship_columns["score_method"]], "NOT_SCORED")
            self.assertEqual(row[relationship_columns["adjudication_decision"]], "ABSTAIN")
            self.assertFalse(row[relationship_columns["eligible_for_join"]])

        renamed = copy.deepcopy(self.fixture)
        renamed["payload"]["elements"][0]["tags"]["name"] = "Renamed without identity drift"
        renamed_elements, _ = MODULE.normalise(renamed, ROOT)
        self.assertEqual([row[0] for row in elements], [row[0] for row in renamed_elements])

    def test_contributor_identity_is_not_in_published_schema_or_rows(self) -> None:
        names = {name for name, _type, _required in MODULE.ELEMENT_SCHEMA}
        self.assertTrue({"user", "uid", "changeset"}.isdisjoint(names))
        elements, _relationships = MODULE.normalise(self.fixture, ROOT)
        columns = {name: index for index, (name, _type, _required) in enumerate(MODULE.ELEMENT_SCHEMA)}
        for row in elements:
            tags = json.loads(row[columns["tags_json"]])
            self.assertTrue({"user", "uid", "changeset"}.isdisjoint(tags))

    def test_build_verify_and_double_compile_are_deterministic(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            base = Path(temporary)
            left, right = base / "left", base / "right"
            MODULE.build(ROOT, ROOT / MODULE.FIXTURE_REL, left, SOURCE_COMMIT)
            MODULE.build(ROOT, ROOT / MODULE.FIXTURE_REL, right, SOURCE_COMMIT)
            verified = MODULE.verify(left, ROOT, ROOT / MODULE.FIXTURE_REL, SOURCE_COMMIT)
            compared = MODULE.compare(left, right)
            self.assertEqual(verified["element_rows"], 3)
            self.assertEqual(verified["relationship_rows"], 6)
            self.assertEqual(verified["company_numbers_asserted"], 0)
            self.assertEqual(compared["status"], "PASS")
            audit = MODULE.load_json(left / MODULE.AUDIT_REL)
            self.assertFalse(audit["raw_fetch_landed"])
            self.assertEqual(audit["network"]["companies_fetch_requests"], 0)
            self.assertEqual(audit["rights"]["datacentermap_ingestion"], "PROHIBITED")
            self.assertLess(
                (left / MODULE.ELEMENTS_REL).stat().st_size,
                len(json.dumps(self.fixture).encode("utf-8")) * 10,
            )

    def test_rejects_empty_partial_wrong_endpoint_and_duplicate_payloads(self) -> None:
        empty = copy.deepcopy(self.fixture)
        empty["payload"]["elements"] = []
        with self.assertRaises(RuntimeError):
            MODULE.normalise(empty, ROOT)

        partial = copy.deepcopy(self.fixture)
        partial["payload"]["remark"] = "runtime error: query timed out"
        with self.assertRaises(RuntimeError):
            MODULE.normalise(partial, ROOT)

        wrong_endpoint = copy.deepcopy(self.fixture)
        wrong_endpoint["endpoint"] = "https://www.datacentermap.com/api"
        with self.assertRaises(RuntimeError):
            MODULE.normalise(wrong_endpoint, ROOT)

        duplicate = copy.deepcopy(self.fixture)
        duplicate["payload"]["elements"].append(
            copy.deepcopy(duplicate["payload"]["elements"][0])
        )
        with self.assertRaises(RuntimeError):
            MODULE.normalise(duplicate, ROOT)

    def test_bbc_record_is_link_only_and_not_project_bound(self) -> None:
        evidence = MODULE.load_json(ROOT / MODULE.EVIDENCE_REL)
        self.assertIsNone(evidence["summary"])
        self.assertEqual(evidence["raw_html_bytes"], 0)
        self.assertEqual(evidence["article_body_bytes"], 0)
        self.assertEqual(evidence["project_binding_count"], 0)
        self.assertFalse(evidence["eligible_for_news_signal"])


if __name__ == "__main__":
    unittest.main()