In this section
- Test Pilot LiDAR test · cosmic / tools/explore/theme/test_pilot_lidar.py lines 1–457
Test Pilot LiDAR
A test in the theme folder of Cosmic covering LiDAR terrain, using EPSG:27700 and OSTN15.
testcosmic / tools/explore/theme/test_pilot_lidar.py · lines 1–457 of 457 · Not reached from any entry point (candidate for review) · pattern _gdal (shared by 2 files)
- What it does
- It tests LiDAR terrain. Defines 29 functions or classes, including _load, _report, test_os_square_to_easting_northing, test_os_square_rejects_bad_refs, test_sourcecoop_fallback_names_cover_the_four_5km_tiles. Uses libraries __future__, functools, http.server, importlib.util, io. Side effects: changes the web page (DOM); reads or writes files.
- 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: GeoTIFF file syn.tif; JSON file index.json; PMTiles file lidar-tr06.pmtiles. Out: JSON file index.json; JSON file play-index.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It makes fixture (`make_fixture`) and is built from the served step (`served`) and the browser step (`browser`). Tests for the LiDAR proof of concept (TRIGPOINT-62): tools/LiDAR (fetch + tile builder), the workflow `.github/workflows/lidar-tr06.yml`, and the Pilot reader `theme/pilot-lidar.js`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/theme · test
- Uses
- __future__, functools, http.server, importlib.util, io, json, math, os
- Used by
- none found
- Produces
- test_os_square_to_easting_northing, test_os_square_rejects_bad_refs, test_sourcecoop_fallback_names_cover_the_four_5km_tiles, test_terrarium_round_trip_and_nodata, test_tile_grid_matches_web_mercator, test_builder_end_to_end_on_synthetic_bng_dtm, test_workflow_dispatch_only_commits_nothing, test_workflow_sources_are_free_and_named, test_module_shape_and_credit, make_fixture, served, browser
- Defines here
- _load, _report, test_os_square_to_easting_northing, test_os_square_rejects_bad_refs, test_sourcecoop_fallback_names_cover_the_four_5km_tiles, test_terrarium_round_trip_and_nodata, test_tile_grid_matches_web_mercator, _gdal, test_builder_end_to_end_on_synthetic_bng_dtm, _wf, test_workflow_dispatch_only_commits_nothing, test_workflow_sources_are_free_and_named, test_module_shape_and_credit, _chromium, _txy, _plane, make_fixture, ll, served, browser, _open, _wait_ring, _at, test_idle_by_default_and_offline, test_pick_zoom_and_ring_rules, test_streams_ring_samples_bilinear_and_credits, test_feather_edges_and_nodata_fall_back, test_missing_index_is_quiet, test_slow_4g_ring_time_and_bandwidth_estimate
- 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/explore/theme/test_pilot_lidar.py:1-457 · blob 618b2dcb26a2c9d8fe60408e5200e39e276f7897 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
"""Tests for the LiDAR proof of concept (TRIGPOINT-62): tools/lidar (fetch + tile builder), the workflow
.github/workflows/lidar-tr06.yml, and the Pilot reader theme/pilot-lidar.js.
Browser tests drive the published Pilot page (inject.py copy_assets + sync_pilot, as test_pilot_browser.py does) at
390x844 with a small FIXTURE tile set made here at test time: synthetic Terrarium tiles whose heights are a known
plane plus 2 cm noise (not real data). All non-local requests are aborted, so no external host is contacted.
Skips: GDAL tests without osgeo; browser tests without Playwright/Chromium.
Run: python3 -m pytest -q tools/explore/theme/test_pilot_lidar.py (PILOT_LIDAR_REPORT=path writes measurements)
"""
from __future__ import annotations
import functools, http.server, importlib.util, io, json, math, os, re, shutil, socketserver, sys, tempfile, threading, time
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
REPO = HERE.parents[2]
LIDAR = REPO / 'tools' / 'lidar'
WF = REPO / '.github' / 'workflows' / 'lidar-tr06.yml'
JS = HERE / 'pilot-lidar.js'
CREDIT = 'Contains Environment Agency information © Environment Agency and/or database right, OGL v3'
SITE = (51.3330, 0.9130) # Cleve Hill, Faversham (fixture centre)
REPORT = os.environ.get('PILOT_LIDAR_REPORT')
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec); sys.modules[name] = m; spec.loader.exec_module(m); return m
def _report(key, val):
if REPORT:
p = Path(REPORT); d = json.loads(p.read_text()) if p.is_file() else {}
d[key] = val; p.write_text(json.dumps(d, indent=1))
# ---------------------------------------------------------------- tools/lidar: pure parts
fetch = _load('lidar_fetch_dtm', LIDAR / 'fetch_dtm.py')
@pytest.mark.parametrize('ref,en', [('TR06', (600000, 160000)), ('TQ38', (530000, 180000)), ('NT60', (360000, 600000)),
('SU12', (410000, 120000)), ('SV00', (0, 0)), ('tr06', (600000, 160000))])
def test_os_square_to_easting_northing(ref, en):
assert fetch.os_ref_to_en(ref) == en
def test_os_square_rejects_bad_refs():
for bad in ('TR0', 'TR0612', '1R06', ''):
with pytest.raises(ValueError):
fetch.os_ref_to_en(bad)
def test_sourcecoop_fallback_names_cover_the_four_5km_tiles(monkeypatch):
monkeypatch.setattr(fetch, '_get', lambda *a, **k: (_ for _ in ()).throw(OSError('offline')))
hrefs = fetch.sourcecoop_hrefs('TR06')
assert sorted(h.rsplit('/', 1)[1] for h in hrefs) == sorted(f'TR06{q}_DTM_1m.tif' for q in ('ne', 'nw', 'se', 'sw'))
assert all(h.startswith('https://data.source.coop/rebalance-earth/ea-dem/DTM/DEFLATE/') for h in hrefs)
np = pytest.importorskip('numpy')
try:
build = _load('lidar_build_tiles', LIDAR / 'build_tiles.py')
except Exception as e: # Pillow missing
build = None
def test_terrarium_round_trip_and_nodata():
if build is None:
pytest.skip('build_tiles needs Pillow')
h = np.array([[0.0, 1.03125, -4.5, np.nan], [123.456, 7.9, 300.0, 15.0]], np.float32)
for vstep in (0, 0.0625, 0.25):
rgba = build.terrarium_encode(h, vstep)
back = build.terrarium_decode(rgba)
ok = np.isfinite(h)
assert np.all(np.isnan(back[~ok])) and np.all(rgba[~ok][:, 3] == 0)
assert np.max(np.abs(back[ok] - h[ok])) <= max(vstep / 2, 0) + 1 / 256 + 1e-6
rgba = build.terrarium_encode(np.full((256, 256), 10.0, np.float32), 0.0625)
from PIL import Image
im = Image.open(io.BytesIO(build.encode_image(rgba, 'png')))
assert im.mode == 'RGB' and im.size == (256, 256), 'full tiles are written without alpha'
def test_tile_grid_matches_web_mercator():
if build is None:
pytest.skip('build_tiles needs Pillow')
assert abs(build.tile_res(16) - 2.388657133911758) < 1e-9
x, y = build.lonlat_to_tile(SITE[1], SITE[0], 16)
w, s, e, n = build.tile_bounds_3857(int(x), int(y), 16)
assert abs((e - w) - 256 * build.tile_res(16)) < 1e-6 and abs((n - s) - (e - w)) < 1e-6
rng = build.tile_range((0.89, 51.32, 0.93, 51.35), 16)
assert rng[0] <= int(x) <= rng[2] and rng[1] <= int(y) <= rng[3]
tile_m = (e - w) * math.cos(math.radians(SITE[0]))
assert 380 < tile_m < 384, 'z16 block is ~382 m at Faversham (VERDICT section 3)'
def _gdal():
try:
from osgeo import gdal, osr
gdal.UseExceptions(); return gdal, osr
except Exception:
return None, None
def test_builder_end_to_end_on_synthetic_bng_dtm(tmp_path):
"""A synthetic 1 m DTM in EPSG:27700 (a plane in E/N plus a no-data strip) -> tiles; decoded heights must match
the plane at the same ground point, transformed with the same PROJ operation."""
gdal, osr = _gdal()
if gdal is None or build is None:
pytest.skip('needs GDAL Python bindings (apt python3-gdal) and Pillow')
e0, n0, size = 602500, 163500, 1500
yy, xx = np.mgrid[0:size, 0:size].astype(np.float64)
E, N = e0 + xx + 0.5, n0 + size - yy - 0.5
h = (5 + 0.01 * (E - e0) + 0.004 * (N - n0)).astype(np.float32)
h[:200, :] = -9999
src = tmp_path / 'syn.tif'
d = gdal.GetDriverByName('GTiff').Create(str(src), size, size, 1, gdal.GDT_Float32)
d.SetGeoTransform((e0, 1, 0, n0 + size, 0, -1)); sr = osr.SpatialReference(); sr.ImportFromEPSG(27700)
d.SetProjection(sr.ExportToWkt()); b = d.GetRasterBand(1); b.SetNoDataValue(-9999); b.WriteArray(h); d = None
out = tmp_path / 'site' / 'lidar'
rc = build.main(['--src', str(src), '--square', 'TR06', '--bng', '602600', '163600', '603900', '164900',
'--out', str(out), '--zooms', '15', '16', '--vstep', '0'])
assert rc == 0
idx = json.loads((out / 'index.json').read_text())
sq = idx['squares'][0]
assert sq['attribution'] == CREDIT and sq['licence'] == 'OGL-3.0' and sq['encoding'] == 'terrarium'
assert sq['tiles_url'] == 'tr06/{z}/{x}/{y}.png'
for k, n in sq['tiles'].items():
assert (out / 'tr06' / f'{k}.png').stat().st_size == n, k
assert sq['total_bytes'] == sum(sq['tiles'].values())
assert set(sq['stats']) == {'15', '16'} and sq['stats']['16']['count'] == sum(1 for k in sq['tiles'] if k.startswith('16/'))
assert (tmp_path / 'site' / 'lidar-tr06.pmtiles').stat().st_size > 1000 or importlib.util.find_spec('pmtiles') is None
# a ground point well inside the data: BNG -> lon/lat with the same PROJ choice, then sample the z16 tile
sr.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
wgs = osr.SpatialReference(); wgs.ImportFromEPSG(4326); wgs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
tr = osr.CoordinateTransformation(sr, wgs)
from PIL import Image
worst = 0.0
for Ept, Npt in ((603000, 164000), (603400, 164300), (602800, 163800)):
lon, lat = tr.TransformPoint(Ept, Npt)[:2]
x, y = build.lonlat_to_tile(lon, lat, 16)
p = out / 'tr06' / '16' / str(int(x)) / f'{int(y)}.png'
a = np.asarray(Image.open(p).convert('RGBA'))
px, py = int((x - int(x)) * 256), int((y - int(y)) * 256)
got = build.terrarium_decode(a)[py, px]
want = 5 + 0.01 * (Ept - e0) + 0.004 * (Npt - n0)
worst = max(worst, abs(got - want))
# one z16 pixel is ~1.5 m on the ground; the plane rises <= 0.0108 m/m, so nearest-pixel error < 0.03 m
assert worst < 0.05, f'height misplaced by {worst:.3f} m'
# the no-data strip (north) is transparent
alpha0 = 0
for k in sq['tiles']:
if k.startswith('16/'):
im = Image.open(out / 'tr06' / f'{k}.png')
if im.mode == 'RGBA' and (np.asarray(im)[..., 3] == 0).any():
alpha0 += 1
assert alpha0 > 0, 'no-data pixels must be alpha 0'
# ---------------------------------------------------------------- workflow (static)
def _wf():
yaml = pytest.importorskip('yaml')
return yaml.safe_load(WF.read_text()), WF.read_text()
def test_workflow_dispatch_only_commits_nothing():
wf, text = _wf()
on = wf.get('on', wf.get(True))
assert list(on) == ['workflow_dispatch'], f'triggers {list(on)}'
assert set(on['workflow_dispatch']['inputs']) >= {'square', 'source', 'format', 'vstep', 'release'}
assert wf['permissions'] == {'contents': 'write'}
assert not re.search(r'git\s+(push|commit|add)\b', text), 'the workflow must not commit or push'
steps = wf['jobs']['build']['steps']
uses = [s.get('uses', '') for s in steps]
assert any(u.startswith('actions/upload-artifact@') for u in uses)
run = '\n'.join(s.get('run', '') for s in steps)
for need in ('apt-get install', 'gdal-bin', 'python3-gdal', 'projsync', 'OSTN15', 'fetch_dtm.py', 'build_tiles.py',
'gh release upload', 'GITHUB_STEP_SUMMARY', '--max-total-mb'):
assert need in run, need
def test_workflow_sources_are_free_and_named():
src = (LIDAR / 'fetch_dtm.py').read_text()
assert 'https://data.source.coop/rebalance-earth/ea-dem/' in src
assert 'environment.data.gov.uk/spatialdata/lidar-composite-digital-terrain-model-dtm-1m/wcs' in src
assert 'time.sleep(pause)' in src and 'pause: float = 40.0' in src, 'EA WCS polite pace (>= 40 s)'
# ---------------------------------------------------------------- pilot-lidar.js (static)
def test_module_shape_and_credit():
s = JS.read_text()
assert re.search(r"\(function \(\) \{\s*'use strict';\s*if \(!window\.PILOT\) return;", s)
assert "P.module('lidar'" in s
assert CREDIT in s
assert not re.search(r'https?://(?!www\.nationalarchives)', s.split('*/', 1)[1]), 'no hard-coded external host'
assert 'P.offline' in s and "flag === '0'" in s
assert 'navigator.connection' in s and 'createImageBitmap' in s and 'MAX_TILES = 120' in s
# ---------------------------------------------------------------- browser: fixture tiles + Playwright at 390x844
def _chromium():
try:
from playwright.sync_api import sync_playwright # noqa: F401
except Exception:
return None
for c in sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome')):
return str(c)
return ''
CH = _chromium()
def _txy(lat, lon, z):
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 _plane(u, v, U0, V0):
"""Fixture height (metres) at z16 global pixel coordinates (u, v)."""
return 5 + 0.02 * (u - U0) + 0.01 * (v - V0)
def make_fixture(root: Path) -> dict:
"""lidar/index.json + lidar/fx/{z}/{x}/{y}.png: 5x5 z16, 3x3 z15, 2x2 z14 around SITE. Plane + 2 cm noise;
the north-west z16 tile has its top half as no data (alpha 0). FIXTURE ONLY, not real heights."""
from PIL import Image
rng = np.random.default_rng(7)
cx, cy = (int(c) for c in _txy(SITE[0], SITE[1], 16))
U0, V0 = (cx - 2) * 256, (cy - 2) * 256
tiles = {}
for z, half in ((16, 2), (15, 1), (14, 1)):
k = 2 ** (16 - z)
zx, zy = cx // k, cy // k
xs = range(zx - half, zx + half + 1) if z != 14 else range(zx, zx + 2)
ys = range(zy - half, zy + half + 1) if z != 14 else range(zy, zy + 2)
for ty in ys:
for tx in xs:
j, i = np.mgrid[0:256, 0:256].astype(np.float64)
u, v = (tx * 256 + i + 0.5) * k, (ty * 256 + j + 0.5) * k
h = _plane(u, v, U0, V0) + rng.uniform(-0.02, 0.02, (256, 256))
val = h + 32768; fl = np.floor(val)
a = np.stack([fl // 256, fl % 256, np.floor((val - fl) * 256), np.full_like(fl, 255)], -1).astype(np.uint8)
if z == 16 and tx == cx - 2 and ty == cy - 2:
a[:128, :, :] = 0
b = io.BytesIO(); Image.fromarray(a, 'RGBA').save(b, 'PNG', optimize=True)
p = root / 'lidar' / 'fx' / str(z) / str(tx) / f'{ty}.png'
p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(b.getvalue())
tiles[f'{z}/{tx}/{ty}'] = len(b.getvalue())
def ll(x, y, z):
n = 2 ** z; return math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))), x / n * 360 - 180
n_, w_ = ll(cx - 2, cy - 2, 16); s_, e_ = ll(cx + 3, cy + 3, 16)
st = {}
for z in ('14', '15', '16'):
s = [v for k, v in tiles.items() if k.startswith(z + '/')]
st[z] = {'count': len(s), 'bytes_total': sum(s), 'bytes_mean': round(sum(s) / len(s))}
idx = {'schema': 'cosmic.lidar-index.v1', 'generated_utc': 'fixture', 'squares': [{
'id': 'FX', 'bbox': [w_, s_, e_, n_], 'zooms': [14, 15, 16], 'encoding': 'terrarium', 'format': 'png',
'tiles_url': 'fx/{z}/{x}/{y}.png', 'tiles': tiles, 'stats': st, 'total_bytes': sum(tiles.values()),
'licence': 'OGL-3.0', 'attribution': CREDIT, 'source': {'source': 'FIXTURE (synthetic plane, not real data)'}}]}
(root / 'lidar' / 'index.json').write_text(json.dumps(idx))
return {'U0': U0, 'V0': V0, 'cx': cx, 'cy': cy, 'tiles': tiles, 'bbox': [w_, s_, e_, n_]}
@pytest.fixture(scope='module')
def served(tmp_path_factory):
if CH is None:
pytest.skip('Playwright unavailable')
inj = _load('pilot_inject_lidar', HERE / 'inject.py')
tmp = tmp_path_factory.mktemp('lidar-site')
vers = inj.copy_assets(tmp); inj.sync_pilot(tmp, vers)
(tmp / 'index.html').write_text('<!doctype html><title>hub</title>')
(tmp / 'favicon.ico').write_bytes(b'')
(tmp / 'theme' / 'play-index.json').write_text('{}')
fx = make_fixture(tmp) # default index ../../lidar/index.json from /pilot/index.html = /lidar/index.json
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp))
handler.log_message = lambda *a, **k: None
srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler); srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield {'url': f'http://127.0.0.1:{srv.server_address[1]}/pilot/index.html', 'fx': fx, 'root': tmp}
srv.shutdown()
@pytest.fixture(scope='module')
def browser():
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
b = p.chromium.launch(**({'executable_path': CH} if CH else {}))
yield b
b.close()
def _open(browser, url, throttle=None):
ctx = browser.new_context(viewport={'width': 390, 'height': 844}, has_touch=True, is_mobile=True)
ctx.route('**/*', lambda r: r.continue_() if r.request.url.startswith('http://127.0.0.1') else r.abort())
pg = ctx.new_page(); errs, lid = [], []
pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' and 'net::ERR_FAILED' not in m.text else None)
pg.on('pageerror', lambda e: errs.append(str(e)))
pg.on('request', lambda r: lid.append(r.url) if '/lidar/' in r.url else None)
if throttle:
cdp = ctx.new_cdp_session(pg)
cdp.send('Network.enable')
cdp.send('Network.emulateNetworkConditions', {'offline': False, 'latency': throttle[1],
'downloadThroughput': throttle[0], 'uploadThroughput': throttle[0]})
pg.goto(url, wait_until='load')
if 'lidar=1' in url: # hover exactly over the fixture centre at 150 m, still
pg.wait_for_function("!!(window.PILOT && typeof PILOT.flyTo === 'function')", timeout=10000)
pg.evaluate('new Promise(r => PILOT.ready(() => setTimeout(r, 300)))')
pg.evaluate(f'PILOT.stop(); PILOT.flyTo({SITE[0]}, {SITE[1]}, {{instant: true, dist: 0, alt: 150}})')
return ctx, pg, errs, lid
def _wait_ring(pg, timeout=60.0, zoom=16):
t0 = time.time()
while time.time() - t0 < timeout:
st = pg.evaluate('PILOT.lidar && PILOT.lidar.status()')
if st and st['want'] and st['zoom'] == zoom and st['loaded'] >= len(st['want']) and st['queued'] == 0 and st['active'] == 0:
return st, time.time() - t0
pg.wait_for_timeout(200)
return pg.evaluate('PILOT.lidar.status()'), None
def _at(lat=SITE[0], lon=SITE[1], agl=150):
return '?lidar=1' # _open then hovers at SITE, 150 m AGL
def test_idle_by_default_and_offline(served, browser):
"""Without the core hook and without ?lidar=1 nothing is fetched (site unchanged); ?offline=1 never fetches."""
hooked = None
for q in ('', '?offline=1&lidar=1'):
ctx, pg, errs, lid = _open(browser, served['url'] + q)
pg.wait_for_timeout(1500)
assert pg.evaluate("PILOT.modules().some(m => m.name === 'lidar')")
hooked = pg.evaluate("typeof PILOT.groundSource === 'function'")
if q or not hooked:
assert not lid, f'{q or "default"}: must not fetch LiDAR, got {lid[:3]}'
assert not errs, errs
ctx.close()
def test_pick_zoom_and_ring_rules(served, browser):
ctx, pg, errs, _ = _open(browser, served['url'] + '?offline=1')
pg.wait_for_timeout(800)
r = pg.evaluate('''(() => { const L = PILOT.lidar, a = {14: 80000, 15: 80000, 16: 80000}, lat = 51.33;
const pz = o => L.pickZoom(Object.assign({lat, avgBytes: a, bps: 62500, queue: 0, speed: 0, zooms: [14, 15, 16]}, o));
return { hover150: pz({agl: 150}), agl500: pz({agl: 500}), agl1500: pz({agl: 1500}), agl2500: pz({agl: 2500}),
agl3500: pz({agl: 3500}), walk: pz({agl: 150, speed: 1.4}), car30: pz({agl: 150, speed: 30}),
drone100: pz({agl: 150, speed: 100}), jet400: pz({agl: 150, speed: 400}), fast1Mbps100: pz({agl: 150, speed: 100, bps: 125000}),
g2: pz({agl: 150, conn: {effectiveType: '2g'}}), g3: pz({agl: 150, conn: {effectiveType: '3g'}}),
save: pz({agl: 150, conn: {saveData: true}}), behind: pz({agl: 150, queue: 8, speed: 10}), hoverQueued: pz({agl: 150, queue: 8}),
ringE: L.ringFor(51.333, 0.913, 90, 16), ringN: L.ringFor(51.333, 0.913, 0, 16),
t16: L.tileMetres(51.333, 16) }; })()''')
assert (r['hover150'], r['agl500'], r['agl1500'], r['agl2500'], r['agl3500']) == (16, 15, 14, 0, 0)
# keep-up: need = 2 x speed x 3 x 80,000 B / block metres; 0.5 Mbps = 62,500 B/s
assert r['walk'] == 16 and r['car30'] == 16
assert r['drone100'] == 14, '100 m/s: z16 needs 125.6 kB/s, z15 62.8 kB/s (> 62.5), z14 31.4 kB/s'
assert r['fast1Mbps100'] == 15 and r['jet400'] == 0
assert (r['g2'], r['g3'], r['save'], r['behind'], r['hoverQueued']) == (0, 16, 14, 15, 16)
cx, cy = (int(c) for c in _txy(51.333, 0.913, 16))
e = r['ringE']
assert e[0] == f'16/{cx}/{cy}' and e[1] == f'16/{cx + 1}/{cy}' and e[2] == f'16/{cx + 2}/{cy}', e[:3]
assert len(e) == 10 and len(set(e)) == 10, '3x3 ring + 1 extra block 2 ahead'
assert r['ringN'][1] == f'16/{cx}/{cy - 1}' and r['ringN'][2] == f'16/{cx}/{cy - 2}'
assert 380 < r['t16'] < 384
assert not errs, errs
ctx.close()
def test_streams_ring_samples_bilinear_and_credits(served, browser):
fx = served['fx']
ctx, pg, errs, lid = _open(browser, served['url'] + _at())
st, secs = _wait_ring(pg, 30)
assert secs is not None, f'ring did not load: {st}'
assert st['enabled'] and st['squares'] == ['FX'] and st['zoom'] == 16
cam = pg.evaluate('PILOT.camLL()')
cx, cy = (int(c) for c in _txy(cam['lat'], cam['lon'], 16))
assert st['want'][0] == f'16/{cx}/{cy}'
want_bytes = sum(fx['tiles'][k] for k in st['want'] if k in fx['tiles'])
assert st['bytes'] >= want_bytes, (st['bytes'], want_bytes) # plus z14/z15 fetched while descending
assert all('/lidar/fx/' in u or u.endswith('/lidar/index.json') for u in lid)
# bilinear heights on the fixture plane (2 cm noise) at several points inside the inner 3x3
pts = []
for dx, dy in ((0.1, 0.2), (0.5, 0.5), (0.93, 0.07), (0.999, 0.5), (0.0, 0.0)):
x, y = cx + dx, cy + dy
n = 2 ** 16; lat = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))); lon = x / n * 360 - 180
got = pg.evaluate(f'PILOT.lidar.height({lat}, {lon})')
want = _plane(x * 256, y * 256, fx['U0'], fx['V0'])
pts.append((round(got['h'], 3), round(want, 3), got['z'], round(got['w'], 2)))
assert got['z'] == 16 and abs(got['h'] - want) < 0.05, pts[-1]
assert got['w'] == 1, 'inner blocks are past the feather band'
# credit shown, no sideways scroll at 390
assert CREDIT in pg.evaluate("document.getElementById('credit').textContent")
sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
assert sw <= iw
hooked = pg.evaluate("typeof PILOT.groundSource === 'function'")
if hooked:
g = pg.evaluate(f'PILOT.ground({SITE[0]}, {SITE[1]})')
h = pg.evaluate(f'PILOT.lidar.height({SITE[0]}, {SITE[1]}).h')
assert abs(g - h) < 1e-6, 'with the core hook, PILOT.ground returns the LiDAR height'
_report('fixture_ring', {'blocks': len(st['want']), 'ring_bytes': want_bytes, 'session_bytes': st['bytes'], 'seconds_unthrottled': round(secs, 2),
'samples': pts, 'core_hook': hooked})
pg.screenshot(path=str(Path(tempfile.gettempdir()) / 'pilot-lidar-390x844.png'))
assert not errs, errs
ctx.close()
def test_feather_edges_and_nodata_fall_back(served, browser):
fx = served['fx']
ctx, pg, errs, _ = _open(browser, served['url'] + _at())
_wait_ring(pg, 30)
w_, s_, e_, n_ = fx['bbox']
pg.evaluate(f"PILOT.lidar.start()")
# fetch the whole fixture into the cache by hovering over the north-west corner block too
pg.evaluate(f"PILOT.flyTo({n_ - 0.0005}, {w_ + 0.0008}, {{instant: true, dist: 0, alt: 150}})")
pg.wait_for_timeout(2500)
edge = pg.evaluate(f'PILOT.lidar.height({(s_ + n_) / 2}, {w_ + 1e-7})')
mid = pg.evaluate(f'PILOT.lidar.height({(s_ + n_) / 2}, {(w_ + e_) / 2})')
out = pg.evaluate(f'PILOT.lidar.height({n_ + 0.01}, {w_})')
assert out is None, 'outside the square: AWS only'
if edge is not None:
assert edge['w'] < 0.01, f'at the square edge LiDAR weight must fade to 0, got {edge}'
assert mid is None or mid['w'] == 1
# north-west block: top half is no data -> null (AWS), bottom half has data
n = 2 ** 16; X = fx['cx'] - 2 + 0.6
lat_top = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * (fx['cy'] - 2 + 0.2) / n))))
lat_bot = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * (fx['cy'] - 2 + 0.8) / n))))
lon = X / n * 360 - 180
loaded = pg.evaluate(f"PILOT.lidar._cache.has('16/{fx['cx'] - 2}/{fx['cy'] - 2}')")
if loaded:
assert pg.evaluate(f'PILOT.lidar.height({lat_top}, {lon})') is None
assert pg.evaluate(f'PILOT.lidar.height({lat_bot}, {lon})') is not None
b = pg.evaluate(f'PILOT.lidar.blend({(s_ + n_) / 2}, {w_ + 1e-7}, 42)')
assert b is None or abs(b - 42) < 0.5, 'blend at the edge returns the AWS height'
assert not errs, errs
ctx.close()
def test_missing_index_is_quiet(served, browser, tmp_path):
ctx, pg, errs, lid = _open(browser, served['url'] + '?lidar=../nowhere/index.json#at=51.333,0.913,150')
pg.wait_for_timeout(2000)
st = pg.evaluate('PILOT.lidar.status()')
assert st['enabled'] is False and st['loaded'] == 0 and not st['credit']
assert not [e for e in errs if 'nowhere' not in e and '404' not in e], errs
ctx.close()
def test_slow_4g_ring_time_and_bandwidth_estimate(served, browser):
"""0.5 Mbps (62,500 B/s), 300 ms latency: the ring arrives and the measured bandwidth is near the link."""
ctx, pg, errs, _ = _open(browser, served['url'] + _at(), throttle=(62500, 300))
st, secs = _wait_ring(pg, 90)
assert secs is not None, f'ring did not load on 0.5 Mbps: {st}'
assert st['bwSamples'] >= 2 and 15000 < st['bps'] < 90000, st
_report('fixture_ring_0.5Mbps', {'blocks': len(st['want']), 'bytes': st['bytes'], 'seconds': round(secs, 1),
'measured_bps': st['bps']})
assert not errs, errs
ctx.close()