In this section
- LiDAR Slope Tiles storage · lidar / src/slope_tiles.py lines 1–280
- Test Earthworks test · lidar / tests/test_earthworks.py lines 1–111
- Test Pair test · lidar / tests/test_pair.py lines 1–167
- Test Roundtrip test · lidar / tests/test_roundtrip.py lines 1–104
LiDAR Slope Tiles
A Python command-line tool that reads slope receipt, using EPSG:27700 and SHA-256. It writes tiles (`write_tiles`) and is built from the neighbours step (`neighbours`) and the horn step (`horn`).
storagelidar / src/slope_tiles.py · lines 1–280 of 280 · Entry point · pattern witness (shared by 3 files)
- What it does
- It loads slope receipt. Defines 15 functions or classes, including neighbours, horn, zevenbergen_thorne, pad, slope_pct. Uses libraries argparse, hashlib, json, os, struct. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (repository name word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. README: "Derive slope and aspect tiles (`src/slope_tiles.py`) and earthworks volumes for trenches and platforms (`src/earthworks_pair.py`), each checked the same way."
- Inputs & outputs
- In: JSON file slope-tiles.json; JSON file slope_receipt.json; JSON file source.json; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 1 file: Test Slope (lidar).
- What it achieves
- Slope and aspect tiles from a south-up 1 m height grid, computed as a pair on the GPU. It accepts `--site`, `--out` and `--cpu`.
- Why it matters
- Checked by Test Slope.
- Application
- lidar · src · Python CLI
- Uses
- argparse, hashlib, json, os, struct, sys, time, datetime
- Used by
- imported by Test Slope (sys.path import)
- Produces
- neighbours, horn, zevenbergen_thorne, pad, slope_pct, classify, octant, laplacian, witness, encode, decode, write_tiles
- Defines here
- neighbours, horn, zevenbergen_thorne, pad, slope_pct, classify, octant, laplacian, witness, encode, decode, write_tiles, to_host, run, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 src/slope_tiles.py:1-280 · blob aac448a94397757fbdfd963a4f84c1186298b767 · 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: supporting_data
"""Slope and aspect tiles from a south-up 1 m height grid, computed as a pair on the GPU.
Two channels, photons back (the electron/positron pattern of pair_gpu.py):
electron Horn's 3x3 method: dz/de = ((c + 2f + i) - (a + 2d + g)) / 8h, dz/dn likewise over
the rows. It weights the whole window, so it smooths.
positron Zevenbergen-Thorne: dz/de = (f - d) / 2h, dz/dn = (b - h) / 2h. Only the four
rook neighbours; sharper, noisier.
photons nodes where |slope_Horn - slope_ZT| > 1 percentage point. They are COUNTED and
located, never suppressed. The two methods differ by a third-derivative term, so
photons are expected at breaks of slope (banks, ditch edges, walls); the receipt says
how many photons sit on the top 5 % of |Laplacian| (curvature) against 5 % by chance.
witness the whole grid again on the CPU in NumPy by a different code path (sliding 3x3
windows and weight kernels, not shifted slices); both methods must agree with the
GPU within 1e-9 percent, and the classes must be identical.
Slope in percent = 100 * sqrt(p^2 + q^2). Aspect is the DOWNSLOPE compass direction,
azimuth = atan2(-p, -q) clockwise from grid north, as an octant 0..7 = N NE E SE S SW W NW,
8 = flat (slope < 0.5 %), 255 = no data. Slope classes (Horn): 0: 0-2, 1: 2-5, 2: 5-10,
3: 10-15, 4: 15-25, 5: >25 percent; 255 = no data (site border, or a missing neighbour).
.gst v1 ("GGS1"), little-endian, 32-byte header then two u8 bodies:
0 char[4] "GGS1" | 4 u16 version=1 | 6 u16 samples=257 | 8 u16 spacing_mm | 10 u16 flags=0
12 i32 origin_e_m | 16 i32 origin_n_m (SW corner) | 20 u8 classes=6 | 21 u8 method=1 (Horn)
22 u16 reserved=0 | 24 u32 nodata_count | 28 u32 steep_count (class >= 3, i.e. >= 10 %)
32 u8[257*257] slope class, then u8[257*257] aspect; rows SOUTH to NORTH, each WEST to EAST.
Tiles sit on the .ght grid (256 m, edges shared with neighbours) and are indexed in
slope-tiles.json with sha256s; the pair receipt lands beside it as slope_receipt.json.
E:/swarm/gpu-bench/venv/Scripts/python.exe src/slope_tiles.py --site E:/lidar-out/open-land-01
"""
import argparse, hashlib, json, os, struct, sys, time
from datetime import datetime, timezone
import numpy as np
try:
import cupy as cp
cp.cuda.runtime.getDeviceCount()
except Exception: # no card: the same arithmetic runs in NumPy and says so
cp = None
TILE_M = 256
N = TILE_M + 1
EDGES = (2.0, 5.0, 10.0, 15.0, 25.0) # percent; class k covers [EDGES[k-1], EDGES[k])
LABELS = ("0-2", "2-5", "5-10", "10-15", "15-25", ">25")
FLAT_PCT = 0.5
TOL_PP = 1.0 # percentage points: the photon bound
TOL_WIT = 1e-9
NODATA = 255
FLAT = 8
MAGIC = b"GGS1"
HEADER = struct.Struct("<4sHHHHiiBBHII")
assert HEADER.size == 32
INDEX = "slope-tiles.json"
RECEIPT = "slope_receipt.json"
# ---------------------------------------------------------------- the two methods (GPU or NumPy)
def neighbours(xp, z):
"""3x3 neighbours of every interior node, south-up: a b c is the NORTH row, g h i the south."""
s = z[:-2, :]; m = z[1:-1, :]; n_ = z[2:, :]
a, b, c = n_[:, :-2], n_[:, 1:-1], n_[:, 2:]
d, f = m[:, :-2], m[:, 2:]
g, h, i = s[:, :-2], s[:, 1:-1], s[:, 2:]
return a, b, c, d, f, g, h, i
def horn(xp, z, sp):
a, b, c, d, f, g, h, i = neighbours(xp, z)
p = ((c + 2 * f + i) - (a + 2 * d + g)) / (8 * sp)
q = ((a + 2 * b + c) - (g + 2 * h + i)) / (8 * sp)
return p, q
def zevenbergen_thorne(xp, z, sp):
a, b, c, d, f, g, h, i = neighbours(xp, z)
return (f - d) / (2 * sp), (b - h) / (2 * sp)
def pad(xp, core):
"""Interior result -> full grid with NaN on the border ring."""
out = xp.full((core.shape[0] + 2, core.shape[1] + 2), xp.nan)
out[1:-1, 1:-1] = core
return out
def slope_pct(xp, p, q):
return 100.0 * xp.sqrt(p * p + q * q)
def classify(xp, s):
cls = xp.searchsorted(xp.asarray(EDGES), s, side="right").astype(xp.uint8)
cls[~xp.isfinite(s)] = NODATA
return cls
def octant(xp, p, q, s):
az = (xp.degrees(xp.arctan2(-p, -q)) + 360.0) % 360.0
o = (xp.floor(az / 45.0 + 0.5) % 8).astype(xp.uint8)
o[s < FLAT_PCT] = FLAT
o[~xp.isfinite(s)] = NODATA
return o
def laplacian(xp, z, sp):
a, b, c, d, f, g, h, i = neighbours(xp, z)
return (b + d + f + h - 4 * z[1:-1, 1:-1]) / (sp * sp)
# ---------------------------------------------------------------- CPU witness: another code path
def witness(z, sp):
"""Both methods by weight kernels over sliding windows (NumPy, float64)."""
w = np.lib.stride_tricks.sliding_window_view(z, (3, 3)) # w[r, c, dr, dc], dr=0 is SOUTH
kx_h = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) / (8 * sp)
ky_h = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) / (8 * sp)
kx_z = np.array([[0, 0, 0], [-1, 0, 1], [0, 0, 0]]) / (2 * sp)
ky_z = np.array([[0, -1, 0], [0, 0, 0], [0, 1, 0]]) / (2 * sp)
k = lambda ker: np.einsum("rcij,ij->rc", w, ker)
return (k(kx_h), k(ky_h)), (k(kx_z), k(ky_z))
# ---------------------------------------------------------------- tiles
def encode(cls, asp, e0, n0, spacing_mm=1000):
if cls.shape != (N, N) or asp.shape != (N, N):
raise ValueError(f"slope tile must be {N}x{N}")
nod = int((cls == NODATA).sum()); steep = int(((cls >= 3) & (cls != NODATA)).sum())
head = HEADER.pack(MAGIC, 1, N, spacing_mm, 0, int(e0), int(n0), len(LABELS), 1, 0, nod, steep)
return head + np.ascontiguousarray(cls, np.uint8).tobytes() + np.ascontiguousarray(asp, np.uint8).tobytes()
def decode(blob):
if len(blob) < HEADER.size:
raise ValueError("short .gst blob")
magic, ver, n, sp, flags, e0, n0, ncls, method, _, nod, steep = HEADER.unpack_from(blob, 0)
if magic != MAGIC or ver != 1:
raise ValueError(f"bad magic/version {magic!r} {ver}")
if len(blob) != HEADER.size + 2 * n * n:
raise ValueError(f".gst size {len(blob)} != {HEADER.size + 2 * n * n}")
body = np.frombuffer(blob, np.uint8, offset=HEADER.size)
head = dict(samples=n, spacing_mm=sp, origin_e_m=e0, origin_n_m=n0, classes=ncls, method=method,
nodata_count=nod, steep_count=steep)
return head, body[:n * n].reshape(n, n), body[n * n:].reshape(n, n)
def write_tiles(out_dir, cls, asp, oe, on, site_name, spacing_mm=1000):
rows, cols = cls.shape
if (rows - 1) % TILE_M or (cols - 1) % TILE_M:
raise ValueError(f"grid {cls.shape} is not k*256+1 per side")
os.makedirs(os.path.join(out_dir, "tiles"), exist_ok=True)
entries = []
for iy in range((rows - 1) // TILE_M):
for ix in range((cols - 1) // TILE_M):
r0, c0 = iy * TILE_M, ix * TILE_M
sc, sa = cls[r0:r0 + N, c0:c0 + N], asp[r0:r0 + N, c0:c0 + N]
blob = encode(sc, sa, oe + c0, on + r0, spacing_mm)
key = f"{ix}_{iy}"; rel = f"tiles/{key}.gst"
with open(os.path.join(out_dir, rel), "wb") as f:
f.write(blob)
valid = sc != NODATA
share = [round(float((sc[valid] == k).mean()), 6) if valid.any() else 0.0 for k in range(len(LABELS))]
entries.append(dict(key=key, file=rel, sha256=hashlib.sha256(blob).hexdigest(), e0=int(oe + c0),
n0=int(on + r0), bytes=len(blob), steep=int(((sc >= 3) & valid).sum()), share=share))
index = dict(format="gst1", crs="EPSG:27700", site=dict(name=site_name, origin_e=int(oe), origin_n=int(on)),
tile_m=TILE_M, spacing_m=spacing_mm / 1000, method="horn", classes_pct=LABELS,
aspect="0..7 downslope N NE E SE S SW W NW, 8 flat (<0.5 %), 255 no data",
tiles=entries, generated_utc=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))
with open(os.path.join(out_dir, INDEX), "w", encoding="utf-8", newline="\n") as f:
json.dump(index, f, indent=1)
return index
# ---------------------------------------------------------------- the pair
def to_host(a):
return cp.asnumpy(a) if cp is not None and isinstance(a, cp.ndarray) else np.asarray(a)
def run(grid, oe=0, on=0, sp=1.0, use_gpu=True, witness_on=True):
"""grid: south-up float64 (NaN = no data). Returns (receipt, slope classes, aspect octants, photon mask)."""
t0 = time.perf_counter()
xp = cp if (use_gpu and cp is not None) else np
device = cp.cuda.runtime.getDeviceProperties(0)["name"].decode() if xp is not np else "cpu (numpy)"
z = xp.asarray(grid, dtype=xp.float64)
ph, qh = horn(xp, z, sp); pz, qz = zevenbergen_thorne(xp, z, sp)
sh, sz = slope_pct(xp, ph, qh), slope_pct(xp, pz, qz)
diff = xp.abs(sh - sz)
valid = xp.isfinite(diff)
photon = valid & (diff > TOL_PP)
lap = xp.abs(laplacian(xp, z, sp))
nvalid = int(valid.sum()); nph = int(photon.sum())
# where the photons are: on breaks of slope (top 5 % of |Laplacian|) or not
lv = lap[valid]
cut = float(xp.percentile(lv, 95)) if nvalid else 0.0
brk = xp.isfinite(lap) & (lap >= cut) & (lap > 1e-6) # 1e-6 per m: above float noise
near_brk = brk.copy() # within one node of a break
near_brk[1:, :] |= brk[:-1, :]; near_brk[:-1, :] |= brk[1:, :]
near_brk[:, 1:] |= near_brk[:, :-1].copy(); near_brk[:, :-1] |= near_brk[:, 1:].copy()
near_brk &= valid
on_break = int((photon & near_brk).sum())
chance = float(near_brk.sum()) / nvalid if nvalid else 0.0
ph_host = to_host(photon)
rr, cc = np.nonzero(ph_host)
cells = {}
for r, c in zip((rr + 1) // 16, (cc + 1) // 16):
cells[(r, c)] = cells.get((r, c), 0) + 1
hot = sorted(cells.items(), key=lambda kv: -kv[1])[:8]
d_host = to_host(diff)
worst = []
if nph:
top = np.argsort(np.where(ph_host, d_host, -1).ravel())[::-1][:8]
for k in top:
r, c = divmod(int(k), d_host.shape[1])
worst.append(dict(e=oe + c + 1, n=on + r + 1, horn_pct=round(float(to_host(sh[r, c])), 3),
zt_pct=round(float(to_host(sz[r, c])), 3), diff_pp=round(float(d_host[r, c]), 3)))
sfull = pad(xp, sh)
cls = to_host(classify(xp, sfull)); asp = to_host(octant(xp, pad(xp, ph), pad(xp, qh), sfull))
vc = cls != NODATA
share = {LABELS[k]: round(float((cls[vc] == k).mean()), 6) for k in range(len(LABELS))}
rec = dict(
device=device, nodes=int(grid.size), valid=nvalid, tol_pp=TOL_PP,
electron=dict(method="horn", mean_pct=round(float(sh[valid].mean()), 4) if nvalid else None,
max_pct=round(float(sh[valid].max()), 3) if nvalid else None),
positron=dict(method="zevenbergen-thorne", mean_pct=round(float(sz[valid].mean()), 4) if nvalid else None,
max_pct=round(float(sz[valid].max()), 3) if nvalid else None),
photons=nph, photon_share=round(nph / nvalid, 6) if nvalid else 0.0,
max_diff_pp=round(float(diff[valid].max()), 4) if nvalid else 0.0,
breaks=dict(laplacian_p95_per_m=round(cut, 5), photons_within_1m_of_top5pct_curvature=on_break,
share_on_breaks=round(on_break / nph, 4) if nph else None, by_chance=round(chance, 4)),
hot_16m_cells=[dict(e=int(oe + c * 16), n=int(on + r * 16), photons=int(v)) for (r, c), v in hot],
worst=worst, share=share)
if witness_on:
g = np.asarray(grid, np.float64)
(hp, hq), (zp, zq) = witness(g, sp)
wh, wz = 100 * np.hypot(hp, hq), 100 * np.hypot(zp, zq)
both = np.isfinite(wh) & np.isfinite(to_host(sh))
dh = np.abs(wh - to_host(sh))[both]; dz = np.abs(wz - to_host(sz))[both]
wcls = np.full(g.shape, NODATA, np.uint8); wcls[1:-1, 1:-1] = np.where(
np.isfinite(wh), np.digitize(np.nan_to_num(wh), EDGES), NODATA)
wph = int((np.abs(wh - wz) > TOL_PP)[both].sum())
# a class may flip only where the slope sits within TOL_WIT of a class edge (an ulp tie)
near = np.zeros(g.shape, bool)
near[1:-1, 1:-1] = np.isfinite(wh) & (np.abs(np.nan_to_num(wh)[..., None] - np.asarray(EDGES)).min(-1) <= TOL_WIT)
flip = wcls != cls
rec["witness"] = dict(nodes=int(both.sum()), horn_max_diff=float(dh.max()) if dh.size else 0.0,
zt_max_diff=float(dz.max()) if dz.size else 0.0,
class_mismatch=int((flip & ~near).sum()), edge_ties=int((flip & near).sum()),
photons_cpu=wph,
photons=int((dh > TOL_WIT).sum() + (dz > TOL_WIT).sum() + (flip & ~near).sum()
+ abs(wph - nph)))
rec["wall_s"] = round(time.perf_counter() - t0, 3)
return rec, cls, asp, ph_host
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--site", required=True, help="folder with source.npy and source.json")
ap.add_argument("--out", help="default SITE/slope")
ap.add_argument("--cpu", action="store_true")
a = ap.parse_args(argv)
meta = json.load(open(os.path.join(a.site, "source.json")))
grid = np.load(os.path.join(a.site, "source.npy"))
if meta.get("rows", "south-to-north") != "south-to-north":
raise SystemExit("source rows must run south to north")
oe, on, sp = meta["origin_e_m"], meta["origin_n_m"], float(meta.get("spacing_m", 1))
rec, cls, asp, _ = run(grid, oe, on, sp, use_gpu=not a.cpu)
out = a.out or os.path.join(a.site, "slope")
index = write_tiles(out, cls, asp, oe, on, os.path.basename(os.path.normpath(a.site)), int(round(sp * 1000)))
rec.update(tiles=len(index["tiles"]), script_sha256=hashlib.sha256(open(__file__, "rb").read()).hexdigest(),
index_sha256=hashlib.sha256(open(os.path.join(out, INDEX), "rb").read()).hexdigest())
with open(os.path.join(out, RECEIPT), "w", encoding="utf-8", newline="\n") as f:
json.dump(rec, f, indent=1)
print(json.dumps({k: rec[k] for k in ("device", "valid", "photons", "photon_share", "max_diff_pp", "breaks",
"share", "witness", "tiles", "wall_s", "index_sha256")}, indent=1))
print("hot 16 m cells:", rec["hot_16m_cells"][:5])
return 0 if rec.get("witness", {}).get("photons", 0) == 0 else 1
if __name__ == "__main__":
sys.exit(main())Test Earthworks
A test in the tests folder of LiDAR that checks LiDAR Earthworks Pair. It is built from the plane step (`plane`), the close step (`close`) and the one step (`one`).
testlidar / tests/test_earthworks.py · lines 1–111 of 111 · Entry point · pattern plane (shared by 2 files)
- What it does
- It tests its inputs. Defines 9 functions or classes, including plane, close, one, test_flat_straight, test_sloped_along_and_across. Uses libraries inspect, json, math, os, pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (repository name word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- Out: JSON file source.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `src/earthworks_pair.py` on synthetic planes with known volumes. It writes `source.json`.
- Why it matters
- Guards the behaviour of LiDAR Earthworks Pair.
- Application
- lidar · tests · test
- Uses
- LiDAR Earthworks Pair (sys.path import), inspect, json, math, os, pathlib, sys, tempfile, traceback
- Used by
- none found
- Produces
- plane, close, one, test_flat_straight, test_sloped_along_and_across, test_bent_flat_and_pappus, test_platform_on_plane, test_sweep_receipt, test_bounded_by_seconds
- Defines here
- plane, close, one, test_flat_straight, test_sloped_along_and_across, test_bent_flat_and_pappus, test_platform_on_plane, test_sweep_receipt, test_bounded_by_seconds
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 tests/test_earthworks.py:1-111 · blob 9b6cd3f15b7e1630da7f2bf2cab8abdbaad8ed04 · 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
"""Tests for src/earthworks_pair.py on synthetic planes with known volumes.
On a plane the floor (centreline ground less d) makes cut = d + c t across the trench, so a
straight trench holds exactly L w d, and a bend of curvature kappa holds, by Pappus,
L (w d - kappa c w^3 / 12). Both channels must hit the known volume and each other.
E:/swarm/gpu-bench/venv/Scripts/python.exe lidar/tests/test_earthworks.py
"""
import inspect, json, math, os, pathlib, sys, tempfile, traceback
import numpy as np
try:
import pytest
except ImportError: # no pytest in the GPU venv: run this file directly, see the bottom
pytest = None
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
import earthworks_pair as ew # noqa: E402
XPS = [np] + ([ew.cp] if ew.cp is not None else [])
OE, ON = 400000.0, 200000.0
def plane(xp, a=100.0, gx=0.0, gy=0.0, n=301):
x, y = np.meshgrid(np.arange(n, dtype=float), np.arange(n, dtype=float))
return ew.Ground(a + gx * x + gy * y, OE, ON, 1.0, xp)
def close(v, want, rel=2e-3):
assert abs(v - want) <= rel * want, (v, want)
def one(G, *a):
e, p, d, _ = ew.trench_pair(ew.routes(*a, oe=OE, on=ON), G)
return e[0], p[0], d[0]
def test_flat_straight():
for xp in XPS:
e, p, d = one(plane(xp), OE + 50.3, ON + 60.7, 0.61, 57.0, 0, 0, 0, 0.6, 1.5)
close(e, 57 * 0.6 * 1.5); close(p, 57 * 0.6 * 1.5, 1e-9); assert d < ew.TOL
def test_sloped_along_and_across():
for xp in XPS:
G = plane(xp, gx=0.08, gy=-0.05) # 8 % east, 5 % south: along and across any heading
for h in (0.0, 0.4, 1.9, 4.0):
e, p, d = one(G, OE + 150, ON + 150, h, 70.0, 0, 0, 0, 0.9, 1.2)
close(e, 70 * 0.9 * 1.2); close(p, 70 * 0.9 * 1.2, 1e-9); assert d < ew.TOL
def test_bent_flat_and_pappus():
for xp in XPS:
for th in (math.radians(90), -math.radians(60)):
L = 30 + 20 * abs(th) + 25
e, p, d = one(plane(xp), OE + 120, ON + 100, 0.3, 30, th, 20, 25, 1.2, 1.0)
close(e, L * 1.2); close(p, L * 1.2, 1e-9); assert d < ew.TOL
# ground rising north (c = +0.3 on the left of an eastward trench); the bend is left, radius 8
G = plane(xp, gy=0.3); w, dd, R, th = 1.2, 1.0, 8.0, math.pi / 2
P = ew.routes(OE + 100, ON + 100, 0.0, 0.0, th, R, 0.0, w, dd, oe=OE, on=ON)
e, p, d, _ = ew.trench_pair(P, G)
# c varies round the bend: c(phi) = 0.3 cos(phi) on the left normal, integrate exactly
want = R * th * w * dd - (1 / R) * 0.3 * w ** 3 / 12 * R * math.sin(th)
close(p[0], want, 1e-5); close(e[0], want); assert d[0] < ew.TOL
def test_platform_on_plane():
for xp in XPS:
G = plane(xp, gx=0.1) # z = 100 + 0.1 x
poly = [(OE + 100, ON + 100), (OE + 120, ON + 100), (OE + 120, ON + 130), (OE + 100, ON + 130)]
(ec, ef), (pc, pf) = ew.platform_pair(poly, 111.0, G) # level crosses at x = 110
want = 0.5 * 10 * 1.0 * 30 # triangle wedge 10 m x 1 m x 30 m either side
close(ec, want); close(ef, want); close(pc, want, 1e-6); close(pf, want, 1e-6)
rot = [(OE + 150 + 20 * math.cos(a), ON + 150 + 20 * math.sin(a)) for a in np.linspace(0, 2 * np.pi, 7)[:-1] + 0.2]
(ec, ef), (pc, pf) = ew.platform_pair(rot, 115.0, G) # a hexagon: the channels must agree
close(pc, ec, ew.TOL); close(pf, ef, ew.TOL)
def test_sweep_receipt(tmp_path):
rng = np.random.default_rng(3)
x, y = np.meshgrid(np.arange(401.0), np.arange(401.0))
z = 120 + 0.03 * x + 4 * np.sin(x / 37) * np.cos(y / 23) + rng.normal(0, 0.05, x.shape)
np.save(tmp_path / "source.npy", z)
json.dump({"origin_e_m": OE, "origin_n_m": ON, "spacing_m": 1}, open(tmp_path / "source.json", "w"))
for gpu in [False] + ([True] if ew.cp is not None else []):
r = ew.sweep(str(tmp_path), trenches=60, seconds=30, batch=25, use_gpu=gpu)
assert r["counts"]["trenches"] == 60 and r["counts"]["bent"] > 0 and r["counts"]["straight"] > 0
assert r["witness"]["photons"] == 0 and r["platform"]["photons"] == 0
assert r["disagreement"]["max_rel"] < ew.TOL, r["disagreement"]["worst"][:2]
assert len(r["script_sha256"]) == 64 and r["seed"] == ew.SEED
def test_bounded_by_seconds(tmp_path):
np.save(tmp_path / "source.npy", np.full((201, 201), 50.0))
json.dump({"origin_e_m": OE, "origin_n_m": ON, "spacing_m": 1}, open(tmp_path / "source.json", "w"))
r = ew.sweep(str(tmp_path), trenches=10 ** 6, seconds=0.0, batch=5, use_gpu=False)
assert r["counts"]["stopped_by"] == "seconds" and r["counts"]["trenches"] == 5
if __name__ == "__main__":
fails = 0
for name, fn in sorted((n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)):
with tempfile.TemporaryDirectory() as d:
try:
fn(*([pathlib.Path(d)] if inspect.signature(fn).parameters else []))
print("ok ", name)
except Exception:
fails += 1
print("FAIL", name); traceback.print_exc()
print(f"{fails} failed")
sys.exit(1 if fails else 0)Test Pair
A test in the tests folder of LiDAR that checks LiDAR Pair GPU, using SHA-256. It makes tiles (`make_tiles`) and checks clean (`check_clean`).
testlidar / tests/test_pair.py · lines 1–167 of 167 · Entry point · pattern test_header_layout (shared by 2 files)
- What it does
- It tests its inputs. Defines 16 functions or classes, including make_tiles, run, poke, test_header_layout, test_clean_tiles_annihilate. Uses libraries hashlib, inspect, json, os, pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (repository name word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- In: JSON file tiles.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `src/pair_gpu.py` against a synthetic hilly grid.
- Why it matters
- Guards the behaviour of LiDAR Pair GPU.
- Application
- lidar · tests · test
- Uses
- LiDAR Pair GPU (sys.path import), hashlib, inspect, json, os, pathlib, struct, sys, tempfile
- Used by
- none found
- Produces
- make_tiles, run, poke, test_header_layout, test_clean_tiles_annihilate, check_clean, test_gpu_and_cpu_agree, test_seeded_repeatable, test_check_points_retest, test_bad_sample_is_a_photon, test_edge_mismatch_is_a_photon, test_header_lie_is_a_photon
- Defines here
- make_tiles, run, poke, test_header_layout, test_clean_tiles_annihilate, check_clean, test_gpu_and_cpu_agree, test_seeded_repeatable, test_check_points_retest, test_bad_sample_is_a_photon, test_edge_mismatch_is_a_photon, test_header_lie_is_a_photon, test_nodata_counted_not_hidden, test_receipt_and_tiles_json, test_bounded_by_seconds, test_main_synth
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 tests/test_pair.py:1-167 · blob caa25690b6c33998d8932073e6e377029bf64e28 · 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
"""Tests for src/pair_gpu.py against a synthetic hilly grid.
A clean set of tiles must annihilate (zero photons); each kind of damage must show up as
photons in the right channel and never be suppressed.
E:/swarm/gpu-bench/venv/Scripts/python.exe -m pytest lidar/tests/test_pair.py -q
"""
import hashlib, inspect, json, os, pathlib, struct, sys, tempfile, traceback
import numpy as np
try:
import pytest
except ImportError: # no pytest in the GPU venv: run this file directly, see the bottom
pytest = None
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
import pair_gpu as pg # noqa: E402
GPU = [False] + ([True] if pg.cp is not None else [])
PTS = 200_000
def make_tiles(tmp_path):
pg.synth(str(tmp_path), tiles_e=2, tiles_n=2)
return str(tmp_path)
if pytest:
tiles = pytest.fixture(make_tiles, name="tiles")
def run(d, gpu=False, **kw):
return pg.run(d, os.path.join(d, "source.npy"), points=kw.pop("points", PTS), batch=1 << 16, use_gpu=gpu, **kw)
def poke(path, row, col, delta_q=0, header=None):
raw = bytearray(open(path, "rb").read())
off = len(raw) - pg.N * pg.N * 2 + 2 * (row * pg.N + col)
q, = struct.unpack_from("<H", raw, off)
struct.pack_into("<H", raw, off, q + delta_q)
if header:
struct.pack_into("<I", raw, 28, header)
open(path, "wb").write(bytes(raw))
def test_header_layout(tiles):
t = pg.read_ght(os.path.join(tiles, "t_400000_300000.ght"))
assert (t["samples"], t["spacing_mm"], t["oe"], t["on"], t["header_bytes"]) == (257, 1000, 400000, 300000, 32)
assert t["q"].shape == (257, 257) and t["nodata"] == 0
def test_clean_tiles_annihilate(tiles):
for gpu in GPU:
check_clean(run(tiles, gpu))
def check_clean(r):
assert r["photons_total"] == 0
assert r["electron"]["samples"] == 4 * 257 * 257
assert r["electron"]["max_err_m"] <= pg.TOL_Q + pg.SLACK
assert r["positron"]["points"] == PTS and r["positron"]["pair_max_m"] < 1e-9
assert r["positron"]["src_max_m"] <= pg.TOL_Q + pg.SLACK
assert r["edges"]["pairs"] == 4 and r["edges"]["photons"] == 0
assert r["witness"]["points"] == pg.WITNESS and r["witness"]["photons"] == 0
assert len(r["check_points"]) == 16
def test_gpu_and_cpu_agree(tiles):
if pg.cp is None:
return # no CuPy device: nothing to compare
a, b = run(tiles, False), run(tiles, True)
for k in ("pair_photons", "src_photons", "nodata_cells"):
assert a["positron"][k] == b["positron"][k]
assert abs(a["positron"]["src_max_m"] - b["positron"]["src_max_m"]) < 1e-12
assert a["check_points"] == b["check_points"]
def test_seeded_repeatable(tiles):
a, b, c = run(tiles), run(tiles), run(tiles, seed=7)
assert a["check_points"] == b["check_points"] and a["positron"] == b["positron"]
assert a["check_points"] != c["check_points"]
def test_check_points_retest(tiles):
"""What the browser does: find the tile, two lerps, compare."""
r = run(tiles)
for p in r["check_points"]:
t = pg.read_ght(os.path.join(tiles, p["tile"]))
h = (t["base"] + t["q"].astype(np.int64)) / 100.0
u, v = (p["x"] - t["oe"]) / (t["spacing_mm"] / 1000), (p["y"] - t["on"]) / (t["spacing_mm"] / 1000)
j, i = min(int(u), 255), min(int(v), 255)
fx, fy = u - j, v - i
a = h[i, j] + (h[i, j + 1] - h[i, j]) * fx
b = h[i + 1, j] + (h[i + 1, j + 1] - h[i + 1, j]) * fx
assert abs(a + (b - a) * fy - p["h"]) < 1e-6
def test_bad_sample_is_a_photon(tiles):
poke(os.path.join(tiles, "t_400000_300000.ght"), 100, 100, delta_q=2)
r = run(tiles)
assert r["electron"]["photons"] == 1
w = r["electron"]["worst"][0]
assert (w["x"], w["y"]) == (400100.0, 300100.0) and w["err_m"] > 0.01
assert r["positron"]["src_photons"] > 0 # interpolated near it, never suppressed
assert r["positron"]["pair_photons"] == 0 # the two formulas still agree with each other
assert r["photons_total"] > 0
def test_edge_mismatch_is_a_photon(tiles):
poke(os.path.join(tiles, "t_400000_300000.ght"), 50, 256, delta_q=1) # east column
r = run(tiles)
assert r["edges"]["photons"] == 1
c = r["edges"]["cases"][0]
assert c["side"] == "east" and c["sample"] == 50 and c["a_cm"] - c["b_cm"] == 1
def test_header_lie_is_a_photon(tiles):
poke(os.path.join(tiles, "t_400256_300256.ght"), 0, 0, header=5)
r = run(tiles)
assert r["header"]["photons"] == 1 and r["header"]["cases"][0]["header"][2] == 5
def test_nodata_counted_not_hidden(tiles):
p = os.path.join(tiles, "t_400000_300000.ght")
raw = bytearray(open(p, "rb").read())
struct.pack_into("<H", raw, len(raw) - pg.N * pg.N * 2 + 2 * (10 * pg.N + 10), pg.NODATA)
struct.pack_into("<I", raw, 28, 1)
open(p, "wb").write(bytes(raw))
r = run(tiles)
assert r["electron"]["nodata_mismatch"] == 1 and r["electron"]["photons"] == 1
assert r["positron"]["nodata_cells"] > 0
def test_receipt_and_tiles_json(tiles):
r = run(tiles)
path, sha = pg.write_receipt(tiles, r)
assert os.path.dirname(path) == tiles
assert hashlib.sha256(open(path, "rb").read()).hexdigest() == sha
assert json.load(open(os.path.join(tiles, "tiles.json")))["receipt"] == sha
rec = json.load(open(path))
assert rec["seed"] == pg.SEED and len(rec["script_sha256"]) == 64 and rec["device"]
assert all(set(p) >= {"x", "y", "h"} for p in rec["check_points"])
def test_bounded_by_seconds(tiles):
r = run(tiles, points=1 << 30, seconds=0.0)
assert r["positron"]["stopped_by"] == "seconds"
def test_main_synth(tmp_path):
assert pg.main(["--tiles", str(tmp_path), "--synth", "--points", "65536", "--cpu"]) == 0
assert os.path.exists(tmp_path / pg.RECEIPT)
if __name__ == "__main__":
fails = 0
for name, fn in sorted((n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)):
with tempfile.TemporaryDirectory() as d:
arg = make_tiles(pathlib.Path(d)) if "tiles" in inspect.signature(fn).parameters else pathlib.Path(d)
try:
fn(arg)
print("ok ", name)
except Exception:
fails += 1
print("FAIL", name); traceback.print_exc()
print(f"{fails} failed")
sys.exit(1 if fails else 0)Test Roundtrip
A test in the tests folder of LiDAR that checks LiDAR Cut Tiles and LiDAR Geotiff Read, using EPSG:27700. It is built from the synthetic step (`synthetic`).
testlidar / tests/test_roundtrip.py · lines 1–104 of 104 · Entry point · pattern test_header_layout (shared by 2 files)
- What it does
- It tests its inputs. Defines synthetic, test_header_layout, test_row_order_south_to_north, test_roundtrip_within_5mm, test_shared_edges_match. Uses libraries json, os, struct, sys, tempfile. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage site_feasibility (repository name word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- In: JSON file tiles.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Synthetic grid -> .ght tiles -> decode -> heights within 5 mm.
- Why it matters
- Guards the behaviour of LiDAR Cut Tiles and LiDAR Geotiff Read.
- Application
- lidar · tests · test
- Uses
- LiDAR Cut Tiles (sys.path import), LiDAR Geotiff Read (sys.path import), json, os, struct, sys, tempfile, numpy
- Used by
- none found
- Produces
- synthetic, test_header_layout, test_row_order_south_to_north, test_roundtrip_within_5mm, test_shared_edges_match
- Defines here
- synthetic, test_header_layout, test_row_order_south_to_north, test_roundtrip_within_5mm, test_shared_edges_match
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 tests/test_roundtrip.py:1-104 · blob e0a8ff0b3f2ca9da44ffa556a5f6f3aa750b3bb3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unknown
"""Synthetic grid -> .ght tiles -> decode -> heights within 5 mm.
Run: python tests/test_roundtrip.py (or pytest tests/)
"""
import json
import os
import struct
import sys
import tempfile
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "src"))
from cut_tiles import (cut_grid, decode_tile, encode_tile, load_tiles, # noqa
HEADER_BYTES, SAMPLES, NODATA_Q)
from geotiff_read import mask_nodata # noqa: E402
TOL_M = 0.005 + 1e-9 # 1 cm quantisation: worst case is exactly 5 mm
def synthetic(size=512, seed=7):
"""Rolling hills with a valley, fine noise and a few nodata holes."""
rng = np.random.default_rng(seed)
y, x = np.mgrid[0:size + 1, 0:size + 1].astype(np.float64)
z = (120.0 + 25.0 * np.sin(x / 90.0) * np.cos(y / 70.0)
- 18.0 * np.exp(-((x - size / 2) ** 2) / (2 * 40.0 ** 2))
+ 0.004 * x + rng.normal(0, 0.03, x.shape))
z[10:14, 300:305] = np.nan
z[400, 0:50] = -3.4028234663852886e38 # EA float32 nodata
z[200, 200] = np.inf
return mask_nodata(z, -3.4028234663852886e38)
def test_header_layout():
h = np.full((SAMPLES, SAMPLES), 42.0)
h[0, 0] = np.nan
blob, info = encode_tile(h, 400000, 210000)
assert HEADER_BYTES == 32
assert len(blob) == 32 + SAMPLES * SAMPLES * 2
assert blob[:4] == b"GGH1"
ver, n, sp, fl = struct.unpack_from("<HHHH", blob, 4)
assert (ver, n, sp, fl) == (1, 257, 1000, 0)
oe, on, base = struct.unpack_from("<iii", blob, 12)
assert (oe, on, base) == (400000, 210000, 4200)
mn, mx, nd = struct.unpack_from("<HHI", blob, 24)
assert (mn, mx, nd) == (0, 0, 1) and info["nodata"] == 1
# first body sample is SW corner and is nodata
assert struct.unpack_from("<H", blob, 32)[0] == NODATA_Q
def test_row_order_south_to_north():
h = np.zeros((SAMPLES, SAMPLES))
h[0, :] = 1.0 # south row
h[:, -1] = 2.0 # east column
blob, _ = encode_tile(h, 0, 0)
q = np.frombuffer(blob, "<u2", offset=32).reshape(SAMPLES, SAMPLES)
assert q[0, 0] == 100 and q[1, 0] == 0 and q[5, -1] == 200
def test_roundtrip_within_5mm():
grid = synthetic(512)
with tempfile.TemporaryDirectory() as d:
man = cut_grid(grid, 400000, 210000, d, "synthetic", source="test")
assert len(man["tiles"]) == 4
with open(os.path.join(d, "tiles.json"), encoding="utf-8") as f:
disk = json.load(f)
assert disk["format"] == "ght1" and disk["crs"] == "EPSG:27700"
assert disk["tile_m"] == 256 and disk["spacing_m"] == 1
for t in disk["tiles"]:
assert os.path.getsize(os.path.join(d, t["file"])) == t["bytes"]
with open(os.path.join(d, t["file"]), "rb") as f:
head, h = decode_tile(f.read())
assert (head["origin_e_m"], head["origin_n_m"]) == (t["e0"],
t["n0"])
_, back = load_tiles(d)
ok = np.isfinite(grid)
assert np.array_equal(ok, np.isfinite(back)), "nodata mask changed"
err = np.abs(back[ok] - grid[ok])
assert err.max() <= TOL_M, f"max error {err.max() * 1000:.3f} mm"
return err.max(), int((~ok).sum()), len(man["tiles"])
def test_shared_edges_match():
grid = synthetic(512, seed=3)
with tempfile.TemporaryDirectory() as d:
man = cut_grid(grid, 0, 0, d, "edges")
tiles = {}
for t in man["tiles"]:
with open(os.path.join(d, t["file"]), "rb") as f:
tiles[t["key"]] = decode_tile(f.read())[1]
a, b = tiles["0_0"], tiles["1_0"]
assert np.allclose(a[:, -1], b[:, 0], equal_nan=True, atol=TOL_M)
a, b = tiles["0_0"], tiles["0_1"]
assert np.allclose(a[-1, :], b[0, :], equal_nan=True, atol=TOL_M)
if __name__ == "__main__":
test_header_layout()
test_row_order_south_to_north()
test_shared_edges_match()
mx, holes, n = test_roundtrip_within_5mm()
print(f"PASS: {n} tiles, max error {mx * 1000:.3f} mm, "
f"{holes} nodata samples preserved")