In this section
- Addresses Check test · energy-transition-simulator / tests/addresses-check.cjs lines 1–116
- Coords Reference test · energy-transition-simulator / tests/coords-reference.mjs lines 1–60
- Engine Lock test · energy-transition-simulator / tests/engine-lock.cjs lines 1–139
- Farm Assess test · energy-transition-simulator / tests/farm-assess.cjs lines 1–244
- Grid Assets test · energy-transition-simulator / tests/grid-assets.cjs lines 1–123
Addresses Check
A JavaScript module in the tests folder of Energy Transition Simulator that tests postcodes, OSTN15 and solar, using Helmert and SHA-256, and uses data from postcodes.io.
testenergy-transition-simulator / tests/addresses-check.cjs · lines 1–116 of 116 · Not reached from any entry point (candidate for review) · pattern metres (shared by 10 files)
- What it does
- It tests postcodes, ostn15 and solar. Defines metres, goAndLand, readBack, hold. Uses libraries http, fs, path, crypto, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, solar.
- Inputs & outputs
- In: data source: postcodes.io; JSON file postcodes-20.json; JSON file ostn15.json; JSON file index.json. Out: JSON file results.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), ETRS89 / EPSG:4258.
- What it achieves
- It reads back (`readBack`) and is built from the metres step (`metres`) and the go and land helper (`goAndLand`). Typed postcodes and grid references land on the right spot, in the real overlay, in Chrome.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- ./world/bng.mjs, http, fs, path, ./fixtures/postcodes-20.json, crypto, playwright
- Used by
- none found
- Produces
- metres, goAndLand, readBack, hold
- Defines here
- metres, goAndLand, readBack, hold
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/addresses-check.cjs:1-116 · blob a21e71ba410e437dac91f2cb5e5acdc45478a72b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Addresses check: typed postcodes and grid references land on the right spot, in the real overlay, in Chrome.
// 20 postcodes: land within 50 m of the centroid postcodes.io publishes (tests/fixtures/postcodes-20.json, fetched
// once; the page's calls to postcodes.io are answered from that file, so the test never touches the service).
// 10 grid references: 10-figure refs cut from the Ordnance Survey's published OSTN15 test points TP03 to TP12
// (OSTN15_TestInput_ETRStoOSGB / TestOutput, ETRS89 lat/lon with National Grid E/N to the mm). The ref names a
// 1 m square and we land at its centre, so the landing must sit exactly the square-centre offset away from the
// OS point (to 2 cm), and the landed centre read back through the overlay's own OSTN15 must give the same ref.
// Serves prototype/ locally, adds the addresses module to the module list for this run only (index.json unchanged).
// Screenshots and results.json go to test-output/addresses/ (or ADDR_SHOTS). Browser: playwright's Chrome, or the
// module named by CHROME_LAUNCHER (exports launch()).
const http = require('http'), fs = require('fs'), path = require('path');
const ROOT = path.join(__dirname, '..', 'prototype');
const OUT = process.env.ADDR_SHOTS || path.join(__dirname, '..', 'test-output', 'addresses');
const FIX = require('./fixtures/postcodes-20.json');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
// OS OSTN15 test points (ETRS89 lat, lon; National Grid E, N as the OS publishes them).
const TP = [['TP03', 50.43885825610, -4.10864563561, 250359.811, 62016.569], ['TP04', 50.57563665000, -1.29782277240, 449816.371, 75335.861],
['TP05', 50.93127937910, -1.45051433700, 438710.920, 114792.250], ['TP06', 51.40078220140, -3.55128349240, 292184.870, 168003.465],
['TP07', 51.37447025550, 1.44454730409, 639821.835, 169565.858], ['TP08', 51.42754743020, -2.54407618349, 362269.991, 169978.690],
['TP09', 51.48936564950, -0.11992557180, 530624.974, 178388.464], ['TP10', 51.85890896400, -4.30852476960, 241124.584, 220332.641],
['TP11', 51.89436637350, 0.89724327012, 599445.590, 225722.826], ['TP12', 52.25529381630, -2.15458614387, 389544.190, 261912.153]];
fs.mkdirSync(OUT, { recursive: true });
const metres = (a, b) => { const k = Math.cos((a.lat + b.lat) * Math.PI / 360); return Math.hypot((a.lat - b.lat) * 111320, (a.lon - b.lon) * 111320 * k); };
const server = http.createServer((q, s) => {
const f = path.join(ROOT, decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html');
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, evidence) => results.push({ name, ok: !!ok, evidence: String(evidence).slice(0, 300) });
(async () => {
// 0. The OSTN15 index must be byte-identical to what ostn15.mjs expects. A Windows checkout with core.autocrlf=true
// rewrites it with CRLF; the hash then fails and the page quietly falls back to Helmert (1-3 m off). Say so first.
{ const want = (fs.readFileSync(path.join(ROOT, 'world', 'ostn15.mjs'), 'utf8').match(/INDEX_SHA256 = '([0-9a-f]{64})'/) || [])[1];
const buf = fs.readFileSync(path.join(ROOT, 'world', 'data', 'ostn15', 'ostn15.json'));
const got = require('crypto').createHash('sha256').update(buf).digest('hex'), crlf = buf.includes(Buffer.from([13, 10]));
check('OSTN15 index file is intact (hash matches, so the page uses OSTN15, not Helmert)', want && got === want,
got === want ? `sha256 ${got.slice(0, 12)}... matches` : `sha256 ${got.slice(0, 12)}... expected ${String(want).slice(0, 12)}...${crlf ? '; the file has CRLF line ends (git core.autocrlf): add "prototype/world/data/** -text" to .gitattributes or clone with -c core.autocrlf=false' : ''}`); }
const launch = process.env.CHROME_LAUNCHER ? require(process.env.CHROME_LAUNCHER).launch
: () => require('playwright').chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : [] });
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
const b = await launch(); const p = await b.newPage({ viewport: { width: 1280, height: 800 } });
const errs = [], pcCalls = []; p.on('pageerror', e => errs.push(e.message));
await p.route('**/mod/index.json', async r => { const list = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'index.json'), 'utf8'));
r.fulfill({ contentType: 'application/json', body: JSON.stringify(list.includes('addresses') ? list : [...list, 'addresses']) }); });
await p.route('https://api.postcodes.io/**', r => { const key = decodeURIComponent(r.request().url().split('/').pop()).replace(/\s/g, '').toUpperCase(); pcCalls.push(key);
const row = FIX.rows.find(x => x.postcode.replace(/\s/g, '') === key);
r.fulfill(row ? { status: 200, contentType: 'application/json', body: JSON.stringify({ status: 200, result: row }) } : { status: 404, contentType: 'application/json', body: '{"status":404}' }); });
await p.goto(`${base}?lat=51.5&lon=-0.12`, { waitUntil: 'load' });
await p.waitForFunction(() => window.SIM && window.SIM.addresses, null, { timeout: 30000 });
await p.evaluate(() => { try { localStorage.clear(); } catch (e) {} });
const goAndLand = async text => {
const msg = await p.evaluate(t => window.SIM.addresses.go(t), text);
await p.waitForFunction(() => !window.SIM.map.isMoving(), null, { timeout: 30000 });
return p.evaluate(m => { const c = window.SIM.map.getCenter(), l = window.SIM.addresses.last(); return { msg: m, lat: c.lat, lon: c.lng, target: l, info: document.getElementById('info').textContent }; }, msg);
};
// Readback through the overlay's own converter (window.__pf.PF, its own OSTN15 blocks, loaded on moveend).
const readBack = async () => { await p.waitForFunction(() => { const c = window.SIM.map.getCenter(); return window.__pf.PF.toBng(c.lat, c.lng).engine === 'OSTN15'; }, null, { timeout: 15000 }).catch(() => {});
return p.evaluate(() => { const c = window.SIM.map.getCenter(); return window.__pf.PF.toBng(c.lat, c.lng); }); };
// 1. Postcodes.
let worstPc = 0; const shotsAt = { 'SW1A 1AA': '1-postcode-SW1A1AA', 'EH1 1YZ': '2-postcode-EH11YZ-helmert', 'CF10 1EP': '3-postcode-CF101EP' };
for (const row of FIX.rows) {
const L = await goAndLand('go ' + row.postcode);
const d = metres(L, { lat: row.latitude, lon: row.longitude }), flown = L.target ? metres(L, L.target) : NaN;
worstPc = Math.max(worstPc, d);
const engine = L.target && / by OSTN15/.test(L.target.text) ? 'OSTN15' : 'Helmert';
check(`postcode ${row.postcode} within 50 m of published centroid`, L.msg === '' && d <= 50 && flown < 0.5,
`${d.toFixed(2)} m from published ${row.latitude}, ${row.longitude}; landed ${L.lat.toFixed(6)}, ${L.lon.toFixed(6)} by ${engine}; flight end ${flown.toFixed(3)} m from target`);
if (shotsAt[row.postcode]) { await p.waitForTimeout(2500); await p.screenshot({ path: path.join(OUT, shotsAt[row.postcode] + '.png') }); }
}
check('postcodes.io asked once per postcode (cache)', pcCalls.length === FIX.rows.length, `${pcCalls.length} calls for ${FIX.rows.length} postcodes`);
const again = await goAndLand('go SW1A 1AA');
check('a repeat postcode uses the cache', pcCalls.length === FIX.rows.length && again.msg === '', `${pcCalls.length} calls after repeat`);
// 2. Grid references cut from the OS test points.
const gr = await p.evaluate(tp => import('./world/bng.mjs').then(B => tp.map(([id, lat, lon, E, N]) => [id, lat, lon, E, N, B.gridRef(E, N, 10)])), TP);
let worstGr = 0;
for (const [id, lat, lon, E, N, ref] of gr) {
const L = await goAndLand('go ' + ref);
const want = Math.hypot(Math.floor(E) + 0.5 - E, Math.floor(N) + 0.5 - N), got = metres(L, { lat, lon }), err = Math.abs(got - want);
const back = await readBack(), backRef = await p.evaluate(([e, n]) => import('./world/bng.mjs').then(B => B.gridRef(e, n, 10)), [back.e, back.n]);
const cen = Math.hypot(back.e - (Math.floor(E) + 0.5), back.n - (Math.floor(N) + 0.5));
worstGr = Math.max(worstGr, err, cen);
check(`grid ref ${ref} (OS ${id}) lands exactly`, L.msg === '' && err <= 0.02 && cen <= 0.02 && backRef === ref && back.engine === 'OSTN15',
`${got.toFixed(3)} m from OS ${id} (square centre is ${want.toFixed(3)} m away); readback ${backRef} by ${back.engine}, ${cen.toFixed(4)} m from square centre`);
if (id === 'TP09') { await p.waitForTimeout(2500); await p.screenshot({ path: path.join(OUT, '4-gridref-TP09.png') }); }
}
// 3. Not an address: find-go keeps it.
check('non-address text is left to find-go', await p.evaluate(() => window.SIM.addresses.classify('solar 50').then(x => x === null)), 'classify("solar 50") === null');
// 4. Typed through the real box, as a player would.
await p.click('#fg-in'); await p.fill('#fg-in', 'TQ 30624 78388'); await p.keyboard.press('Enter');
await p.waitForTimeout(500); await p.waitForFunction(() => !window.SIM.map.isMoving(), null, { timeout: 30000 }); await p.waitForTimeout(2500);
const typed = await p.evaluate(() => ({ info: document.getElementById('info').textContent, msg: document.getElementById('fg-msg').textContent }));
check('typing a grid ref in the find box lands there', /TQ 30624 78388/.test(typed.info) && typed.msg === '', typed.info);
await p.screenshot({ path: path.join(OUT, '5-typed-box.png') });
// 5. Walk and fly where we landed: the landing must hold while the camera changes mode.
const hold = async (key, shot) => { const t = await p.evaluate(() => window.SIM.addresses.last());
await p.evaluate(() => document.activeElement && document.activeElement.blur()); await p.keyboard.press(key); await p.waitForTimeout(1200); await p.waitForFunction(() => !window.SIM.map.isMoving(), null, { timeout: 30000 }); await p.waitForTimeout(2000);
const v = await p.evaluate(() => { const c = window.SIM.map.getCenter(); return { lat: c.lat, lon: c.lng, pitch: window.SIM.map.getPitch(), zoom: window.SIM.map.getZoom() }; });
await p.screenshot({ path: path.join(OUT, shot + '.png') }); return { v, off: t ? metres(v, t) : NaN }; };
const w = await hold('1', '7-walk-at-gridref'), f = await hold('2', '8-drone-at-gridref');
check('walk (1) and drone (2) keep the landed spot', w.v.pitch > 30 && f.v.pitch > 20 && w.off < 0.5 && f.off < 0.5,
`walk pitch ${w.v.pitch.toFixed(0)} zoom ${w.v.zoom.toFixed(1)} off ${w.off.toFixed(3)} m; drone pitch ${f.v.pitch.toFixed(0)} zoom ${f.v.zoom.toFixed(1)} off ${f.off.toFixed(3)} m`);
await p.setViewportSize({ width: 390, height: 844 }); await p.waitForTimeout(1500); await p.screenshot({ path: path.join(OUT, '6-phone.png') });
check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
await b.close(); server.close();
fs.writeFileSync(path.join(OUT, 'results.json'), JSON.stringify({ worstPostcodeMetres: worstPc, worstGridRefMetres: worstGr, results }, null, 1));
for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} -- ${r.evidence}`);
const failed = results.filter(r => !r.ok).length;
console.log(`\nworst postcode ${worstPc.toFixed(2)} m, worst grid ref ${worstGr.toFixed(4)} m\n${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
})().catch(e => { console.error(e); server.close(); process.exit(2); });Coords Reference
A JavaScript module in the tests folder of Energy Transition Simulator that tests OSTN15, using Helmert and SHA-256.
testenergy-transition-simulator / tests/coords-reference.mjs · lines 1–60 of 60 · Not reached from any entry point (candidate for review)
- What it does
- It tests ostn15. Defines check, get. Uses libraries node:fs, node:crypto, node:url, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file ostn15.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), ETRS89 / EPSG:4258.
- What it achieves
- It is built from the check step (`check`) and the get step (`get`). Coords reference check: the ONE conversion (`place-frame.mjs` with the world's OSTN15) against the Ordnance Survey's own published answers.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- Place Frame (import), Bng (import), OSTN15 (import), node:fs, node:crypto, node:url, node:path
- Used by
- none found
- Produces
- check, get
- Defines here
- check, get
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/coords-reference.mjs:1-60 · blob 2d93917b013339a834957e9a911cf4bcccda667b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Coords reference check: the ONE conversion (place-frame.mjs with the world's OSTN15) against the Ordnance Survey's
// own published answers. No network, no browser: reads the committed OSTN15 blocks from disk through the same
// hash-checked loader the page uses, so a checkout that alters the data (CRLF line endings on ostn15.json) FAILS here
// instead of silently dropping the page to Helmert (about 2 m off).
//
// References (external truth): OS OSTN15 test points TP01 to TP12 from OSTN15_TestInput_ETRStoOSGB / TestOutput
// (ETRS89 lat/lon and National Grid E/N as the OS publishes them, to the mm). These are the OS test points inside the
// committed England blocks. Tolerance 0.1 m, the owner's lane target.
// Run: node tests/coords-reference.mjs (exit 1 on any FAIL)
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import * as PF from '../prototype/place-frame.mjs';
import * as BNG from '../prototype/world/bng.mjs';
import { createOstn15, etrsToBng, bngToEtrs, INDEX_SHA256 } from '../prototype/world/ostn15.mjs';
const WORLD = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'prototype', 'world');
const results = [];
const check = (name, ok, evidence) => { results.push({ name, ok: !!ok }); console.log(`${ok ? 'PASS' : 'FAIL'} ${name} | ${evidence}`); };
// Same contract as ostn15.mjs getChecked: refuse any file whose SHA-256 is not the pinned one.
const get = async (rel, sha) => {
const buf = readFileSync(path.join(WORLD, rel)), got = createHash('sha256').update(buf).digest('hex');
if (got !== sha) throw Error(`${rel}: hash ${got.slice(0, 12)} is not the pinned ${sha.slice(0, 12)}`);
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
};
const idx = readFileSync(path.join(WORLD, 'data', 'ostn15', 'ostn15.json'));
const idxSha = createHash('sha256').update(idx).digest('hex');
check('OSTN15 index hash is the pinned one (fails on a CRLF checkout)', idxSha === INDEX_SHA256,
`file ${idxSha.slice(0, 12)} pinned ${INDEX_SHA256.slice(0, 12)}${idx.includes(13) ? ', file has CR bytes' : ''}`);
const OSTN = createOstn15({ get });
PF.useWorld(BNG, { blocks: OSTN.blocks, etrsToBng, bngToEtrs });
const TP = [['TP01', 49.92226393730, -6.29977752014, 91492.146, 11318.804], ['TP02', 49.96006137820, -5.20304609998, 170370.718, 11572.405],
['TP03', 50.43885825610, -4.10864563561, 250359.811, 62016.569], ['TP04', 50.57563665000, -1.29782277240, 449816.371, 75335.861],
['TP05', 50.93127937910, -1.45051433700, 438710.920, 114792.250], ['TP06', 51.40078220140, -3.55128349240, 292184.870, 168003.465],
['TP07', 51.37447025550, 1.44454730409, 639821.835, 169565.858], ['TP08', 51.42754743020, -2.54407618349, 362269.991, 169978.690],
['TP09', 51.48936564950, -0.11992557180, 530624.974, 178388.464], ['TP10', 51.85890896400, -4.30852476960, 241124.584, 220332.641],
['TP11', 51.89436637350, 0.89724327012, 599445.590, 225722.826], ['TP12', 52.25529381630, -2.15458614387, 389544.190, 261912.153]];
let worstF = 0, worstI = 0, worstRT = 0, worstH = 0;
for (const [id, lat, lon, E, N] of TP) {
const ok = await OSTN.need(lat, lon);
const f = PF.toBng(lat, lon), dF = Math.hypot(f.e - E, f.n - N);
const b = PF.fromBng(E, N), a = PF.placeKey(lat, lon), q = PF.toLocal(a, lat, lon, 0), r = PF.toLocal(a, b.lat, b.lon, 0);
const dI = Math.hypot(q.x - r.x, q.y - r.y); // inverse error in ground metres, measured in the one local frame
const back = PF.fromLocal(a, q.x, q.y, 0), rt = PF.toLocal(a, back.lat, back.lon, 0), dRT = Math.hypot(rt.x - q.x, rt.y - q.y);
worstF = Math.max(worstF, dF); worstI = Math.max(worstI, dI); worstRT = Math.max(worstRT, dRT); worstH = Math.max(worstH, f.helmert ? Math.hypot(f.helmert.e - E, f.helmert.n - N) : 0);
check(`${id} ETRS89 -> National Grid within 0.1 m by OSTN15`, ok && f.engine === 'OSTN15' && dF <= 0.1, `${f.engine} ${dF.toFixed(4)} m (Helmert would be ${f.helmert ? Math.hypot(f.helmert.e - E, f.helmert.n - N).toFixed(2) : '?'} m)`);
check(`${id} National Grid -> ETRS89 within 0.1 m by OSTN15`, b.engine === 'OSTN15' && dI <= 0.1, `${b.engine} ${dI.toFixed(4)} m`);
check(`${id} toLocal/fromLocal round trip within 1 mm`, dRT <= 0.001, `${(dRT * 1000).toFixed(6)} mm at ${a.key}`);
}
console.log(`worst: forward ${worstF.toFixed(4)} m, inverse ${worstI.toFixed(4)} m, local round trip ${(worstRT * 1000).toFixed(6)} mm; Helmert alone worst ${worstH.toFixed(2)} m`);
console.log(`references: ${TP.length} OS test points (external truth); the lane target is 20, so ${20 - TP.length} are still missing`);
const fail = results.filter(r => !r.ok).length;
console.log(`${results.length - fail}/${results.length} PASS`);
process.exit(fail ? 1 : 0);Engine Lock
A JavaScript module in the tests folder of Energy Transition Simulator that tests cables and LiDAR terrain, using OSTN15. It is built from the mod list helper (`modList`).
testenergy-transition-simulator / tests/engine-lock.cjs · lines 1–139 of 139 · Not reached from any entry point (candidate for review) · pattern modList (shared by 3 files)
- What it does
- It tests cables and LiDAR terrain. Defines DTM, modList. Uses libraries http, fs, path, url, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: cables, LiDAR terrain, 400kV.
- Inputs & outputs
- In: JSON file index.json; command-line arguments. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 400kV.
- What it achieves
- Check for `mod/engine-lock.js`: the site-world block imported BY URL from its release, locked to real coordinates (BNG through the overlay's own OSTN15 path, measured ground from the R5 stream), then built in sequence and pulsed. Its code works with 400 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- http, fs, path, url, playwright
- Used by
- none found
- Produces
- DTM, modList
- Defines here
- DTM, modList
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/engine-lock.cjs:1-139 · blob 4bda434378e065fb08f5ed123e37786357ce6ebf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Check for mod/engine-lock.js: the site-world block imported BY URL from its release, locked to real coordinates
// (BNG through the overlay's own OSTN15 path, measured ground from the R5 stream), then built in sequence and pulsed.
// The EA is NEVER called: the stream is answered by a synthetic fixture (as tests/lidar-stream.cjs). The engine itself
// is fetched from the site-world release (network needed; a failed import is a FAIL that says so).
// Serves prototype/ on a local port with engine-lock added before menu-bar in a scratch module list (index.json untouched).
// node tests/engine-lock.cjs [outDir]
// Every check prints PASS or FAIL with evidence; exit code 1 on any FAIL.
const http = require('http'), fs = require('fs'), path = require('path'), { pathToFileURL } = require('url');
const ROOT = path.join(__dirname, '..', 'prototype');
const OUT = process.argv[2] || path.join(__dirname, '..', 'test-output', 'engine-lock');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
const LINE = { lat: 52.2441634, lon: -1.0453368 }; // on a mapped 400 kV line (the UI check's default): open land
const DTM = (e, n) => 100 + 0.01 * (e % 2048) + 5 * Math.sin((n % 2048) / 150);
fs.mkdirSync(OUT, { recursive: true });
const results = []; const check = (name, ok, evidence) => { results.push({ name, ok: !!ok }); console.log(`${ok ? 'PASS' : 'FAIL'} ${name} :: ${String(evidence).slice(0, 400)}`); };
function modList() {
const l = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'index.json'), 'utf8')).filter(n => n !== 'engine-lock');
if (!l.includes('lidar-stream')) l.push('lidar-stream');
const i = l.indexOf('menu-bar'); if (i >= 0) l.splice(i, 0, 'engine-lock'); else l.push('engine-lock');
return l;
}
(async () => {
const R5 = await import(pathToFileURL(path.join(ROOT, 'mod', 'lidar-stream', 'r5.mjs')).href);
const server = http.createServer((q, s) => {
const u = decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html';
if (u === 'mod/index.json') { s.writeHead(200, { 'Content-Type': 'application/json' }); return s.end(JSON.stringify(modList())); }
const f = path.join(ROOT, u);
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
const { chromium } = require('playwright');
const b = await chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
const p = await b.newPage({ viewport: { width: 1280, height: 800 } });
const errs = [], ea = []; let delayMs = 0; p.on('pageerror', e => errs.push(e.message));
await p.route(/environment\.data\.gov\.uk/, async route => {
const u = decodeURIComponent(route.request().url()); ea.push(u);
if (delayMs) await new Promise(r => setTimeout(r, delayMs)); // the "clicked before the ground lands" fixture
const E = u.match(/subset=E\((\d+),(\d+)\)/), N = u.match(/subset=N\((\d+),(\d+)\)/);
if (!E || !N) return route.fulfill({ status: 400, body: 'fixture: bad request' });
const e0 = +E[1], e1 = +E[2], n0 = +N[1], n1 = +N[2];
const body = R5.synthTiff(e0, n1, e1 - e0, n1 - n0, (i, j) => DTM(e0 + i + 0.5, n1 - j - 0.5));
route.fulfill({ status: 200, headers: { 'content-type': 'image/tiff', 'access-control-allow-origin': '*' }, body: Buffer.from(body) });
});
await p.goto(`${base}?lat=${LINE.lat}&lon=${LINE.lon}`, { waitUntil: 'load' });
await p.waitForFunction(() => window.SIM && window.SIM.engineLock && window.__lidarStream, null, { timeout: 40000 });
// 1. Menu items, in File and View (not Scope > More).
const items = await p.evaluate(() => ({ file: [...document.querySelectorAll('.gm-panel[data-menu="File"] button')].map(x => x.textContent.trim()), view: [...document.querySelectorAll('.gm-panel[data-menu="View"] button')].map(x => x.textContent.trim()) }));
check('File > Build here (animated)', items.file.includes('Build here (animated)'), items.file.join(' | '));
check('View > Walk a cable', items.view.includes('Walk a cable'), items.view.join(' | '));
// 2. The engine imports by URL from the site-world release (never copied into this repo).
const src = await p.evaluate(async () => { try { await window.SIM.engineLock.load(); } catch (e) { return 'ERR ' + e.message; } return window.SIM.engineLock.state().source; });
check('engine imported by URL from the site-world release', /^https:\/\/globalgrid2050\.com\/solar-design-studio\/2026092\d{5}-site-world\/world\/block-build\.mjs$/.test(src), src);
check('no engine file copied by this lane (mod/block-build.mjs, engine-lock.js)', !fs.existsSync(path.join(ROOT, 'mod', 'block-build.mjs')) && !/buildBlock\s*=|function buildBlock/.test(fs.readFileSync(path.join(ROOT, 'mod', 'engine-lock.js'), 'utf8')), 'mod/ has no block-build.mjs and engine-lock.js defines no buildBlock (the base carries its own v12 copy under mod/engine/, used by plant.js; no … [line shortened here: 418 characters; full line on GitHub]
// 3. Measured ground streams (fixture), then the build at the view centre uses it: every sample measured, ground contact solid.
await p.evaluate(() => window.__lidarStream.useFixture(null, 1500));
await p.evaluate(() => document.getElementById('drone').click());
await p.waitForFunction(() => window.__lidarStream.blocks().some(b => b.kind === 'ground'), null, { timeout: 30000 });
const centre = await p.evaluate(() => { const P = window.SIM.PF || window.__pf.PF, c = window.SIM.map.getCenter(), g = P.toBng(c.lat, c.lng); return { e: g.e, n: g.n, lat: c.lat, lon: c.lng }; });
// keep the block inside the streamed tile: anchor 300 m inside its south-west corner
const tile = R5.tileOf(centre.e, centre.n), E0 = tile.e0 + 300, N0 = tile.n0 + 300;
const st = await p.evaluate(async ([e, n]) => { const s = await window.SIM.engineLock.build({ e, n, bearingDeg: 0, animate: false }); return s; }, [E0, N0]);
check('block built: 23 tables, 1,344 DC and 84 AC cables, 28 inverters', st.built && st.routes.dc === 1344 && st.routes.ac === 84 && st.counts.inverters === 364 && st.counts.tables > 5000, JSON.stringify({ routes: st.routes, counts: st.counts }));
check('every ground sample measured from the stream (none estimated)', st.unmeasured === 0 && st.used.measured > 20000, JSON.stringify(st.used));
check('provenance styles: ground contact solid, equipment ghost, cables dashed', st.styles.outline === 'solid' && st.styles.tables === 'ghost' && st.styles.dc === 'dashed' && st.styles.ac === 'dashed', JSON.stringify(st.styles));
check('own layer on the map, static buffers', st.layer, 'engine-lock-wire');
// 4. LOCK: the pad centre lands where asked (BNG in, OSTN15 out, BNG back), and its level is the fixture's own DTM.
const fp = await p.evaluate(() => window.SIM.engineLock.footprints());
const back = await p.evaluate(([lat, lon]) => { const P = window.SIM.PF || window.__pf.PF; return P.toBng(lat, lon); }, [fp.pad.lat, fp.pad.lon]);
check('pad centre round trip BNG -> OSTN15 lon/lat -> BNG within 0.01 m', Math.hypot(back.e - fp.pad.e, back.n - fp.pad.n) < 0.01, `${(Math.hypot(back.e - fp.pad.e, back.n - fp.pad.n) * 1000).toFixed(2)} mm (${back.engine || 'engine?'})`);
const truth = DTM(Math.floor(fp.pad.e) + 0.5, Math.floor(fp.pad.n) + 0.5);
check('pad level = measured DTM at the pad within 0.5 m (the fixture formula is the truth)', fp.pad.measured != null && Math.abs(fp.pad.levelEngine - truth) < 0.5 && Math.abs(fp.pad.measured - truth) < 0.01, `engine ${fp.pad.levelEngine.toFixed(3)} m, stream ${fp.pad.measured && fp.pad.measured.toFixed(3)} m, formula ${truth.toFixed(3)} m, receipt ${fp.pad.receipt}`);
const st2 = await p.evaluate(async ([e, n]) => window.SIM.engineLock.build({ e, n, bearingDeg: 30, at: 'pad', animate: false }), [E0 + 200, N0 + 200]);
const fp2 = await p.evaluate(() => window.SIM.engineLock.footprints());
check('at: pad places the pad centre on the asked point; bearing turns the tables', Math.hypot(fp2.pad.e - (E0 + 200), fp2.pad.n - (N0 + 200)) < 0.01 && Math.abs(fp2.bearingDeg - 30) < 1e-9 && Math.abs(Math.atan2(fp2.tables[0].corners[3].e - fp2.tables[0].corners[0].e, fp2.tables[0].corners[3].n - fp2.tables[0].corners[0].n) * 180 / Math.PI - 30) < 0.01, `pad d ${Math.hypot(fp2.pad.e - (E0 + 200 … [line shortened here: 616 characters; full line on GitHub]
// 4b. LOCK BEFORE ANIMATING: Build here clicked before the ground lands (the fixture answers 4 s late). The block is built
// at once on estimated ground, the caption says it is waiting, and within 10 s of the tile arriving the block is
// re-grounded at the same E, N, bearing: estimated 0, outline solid, MEASURED caption, the sequence not replayed.
await p.evaluate(() => window.SIM.engineLock.stop());
const far = R5.tileOf(centre.e + 3 * 2048, centre.n + 2 * 2048); // a tile nothing has streamed yet
const farLL = await p.evaluate(([e, n]) => { const P = window.SIM.PF || window.__pf.PF; return P.fromBng(e, n); }, [far.e0 + 1024, far.n0 + 1024]);
await p.evaluate(([lon, lat]) => window.SIM.map.jumpTo({ center: [lon, lat], zoom: 16.8, pitch: 60 }), [farLL.lon, farLL.lat]);
await p.waitForTimeout(500); delayMs = 4000; const eaBefore = ea.length;
await p.evaluate(() => { window.SIM.menu.open('File'); [...document.querySelectorAll('.gm-panel[data-menu="File"] button')].find(x => x.textContent.trim() === 'Build here (animated)').click(); window.SIM.menu.close(); });
await p.waitForFunction(() => window.SIM.engineLock.state().built, null, { timeout: 15000 });
const early = await p.evaluate(() => ({ s: window.SIM.engineLock.state(), cap: document.getElementById('engine-lock-caption').textContent }));
check('delayed fixture: built at once on estimated ground, caption says waiting (R5 gap), outline ghost', early.s.unmeasured > 0 && early.s.styles.outline === 'ghost' && early.s.regrounding && /waiting for measured ground \(R5 gap\)|estimated/.test(early.cap) && !/no measured LiDAR here yet/.test(early.cap), `estimated ${early.s.used.estimated} of ${early.s.used.estimated + early.s.used.measured … [line shortened here: 474 characters; full line on GitHub]
await p.waitForFunction(k => { const t = window.__lidarStream.tiles.get(k); return t && t.dtm && !t.dtm.pending && !t.dtm.none; }, far.key, { timeout: 30000 });
const tArrived = Date.now();
await p.waitForFunction(() => { const s = window.SIM.engineLock.state(); return s.built && s.unmeasured === 0; }, null, { timeout: 10000 }).catch(() => null);
const late = await p.evaluate(() => ({ s: window.SIM.engineLock.state(), cap: document.getElementById('engine-lock-caption').textContent }));
const regroundMs = Date.now() - tArrived;
check('delayed fixture: re-grounded within 10 s of the tile arriving: estimated 0, outline solid, MEASURED caption, sequence kept its place', late.s.unmeasured === 0 && late.s.styles.outline === 'solid' && late.s.rebuilt >= 1 && regroundMs < 10000 && late.s.seq && late.s.seq.t > 0.05 && Math.abs(late.s.E - early.s.E) < 1e-6 && Math.abs(late.s.N - early.s.N) < 1e-6 && (late.s.seq.done ? /MEASURED … [line shortened here: 656 characters; full line on GitHub]
delayMs = 0;
await p.waitForFunction(() => { const s = window.SIM.engineLock.state(); return s.seq && s.seq.done; }, null, { timeout: 30000 });
const capDone = await p.evaluate(() => document.getElementById('engine-lock-caption').textContent);
check('delayed fixture: at the end of the sequence the caption says MEASURED and re-grounded', /MEASURED/.test(capDone) && /re-grounded/.test(capDone) && !/no measured LiDAR here yet/.test(capDone), capDone.slice(0, 200));
await p.screenshot({ path: path.join(OUT, '0-regrounded.png') });
// 4c. A block straddling a tile edge: both tiles fetched (the neighbour by a stepped arrival), estimated 0.
await p.evaluate(() => window.SIM.engineLock.stop());
const eaStraddle = ea.length;
const st3 = await p.evaluate(async ([e, n]) => window.SIM.engineLock.build({ e, n, bearingDeg: 0, animate: false }), [far.e0 - 100, far.n0 + 300]);
check('straddle: the block touches two R5 tiles and the far one is estimated at first', st3.tiles.length === 2 && st3.unmeasured > 0 && st3.regrounding, `tiles ${JSON.stringify(st3.tiles)}, estimated ${st3.used.estimated} of ${st3.used.estimated + st3.used.measured}`);
await p.waitForFunction(() => { const s = window.SIM.engineLock.state(); return s.built && s.unmeasured === 0; }, null, { timeout: 40000 }).catch(() => null);
const st4 = await p.evaluate(() => ({ s: window.SIM.engineLock.state(), cap: document.getElementById('engine-lock-caption').textContent, centre: window.SIM.map.getCenter() }));
const west = R5.tileOf(far.e0 - 100, far.n0 + 300);
const fetched = ea.slice(eaStraddle).map(u => (u.match(/subset=E\((\d+),/) || [])[1]);
check('straddle: both tiles fetched, estimated 0, both tiles measured, the view never moved', st4.s.unmeasured === 0 && st4.s.tiles.every(t => t.state === 'measured') && fetched.includes(String(west.e0)) && Math.abs(st4.centre.lng - farLL.lon) < 1e-9 && Math.abs(st4.centre.lat - farLL.lat) < 1e-9, `tiles ${JSON.stringify(st4.s.tiles)}, fetched E ${fetched.join(',')}, estimated ${st4.s.used.estim … [line shortened here: 436 characters; full line on GitHub]
await p.evaluate(() => window.SIM.engineLock.stop());
await p.evaluate(([lon, lat]) => window.SIM.map.jumpTo({ center: [lon, lat] }), [centre.lon, centre.lat]);
await p.waitForTimeout(300);
// 5. The animated build: File > Build here (animated) plays the sequence (marks prefixes) and then pulses.
await p.evaluate(() => { window.SIM.map.jumpTo({ pitch: 60, zoom: 16.8 }); window.SIM.menu.open('File'); [...document.querySelectorAll('.gm-panel[data-menu="File"] button')].find(x => x.textContent.trim() === 'Build here (animated)').click(); window.SIM.menu.close(); });
await p.waitForFunction(() => { const s = window.SIM.engineLock.state(); return s.built && s.seq && s.seq.t > 0.05; }, null, { timeout: 15000 });
const mid = await p.evaluate(() => window.SIM.engineLock.state()); const midCap = await p.evaluate(() => document.getElementById('engine-lock-caption').textContent);
check('sequence running from the menu, caption names the item being built', mid.seq && mid.seq.t > 0 && mid.seq.t < 1 && /building: \w+ \d+ of \d+/.test(midCap), `t ${mid.seq && mid.seq.t.toFixed(2)}: "${midCap}"`);
await p.screenshot({ path: path.join(OUT, '1-building.png') });
await p.waitForFunction(() => { const s = window.SIM.engineLock.state(); return s.seq && s.seq.done; }, null, { timeout: 30000 });
await p.waitForTimeout(800);
const done = await p.evaluate(() => window.SIM.engineLock.state());
check('sequence complete in about 20 s, then the cable-flow pulses (one dash per route)', done.seq.done && done.pulse === 1344 + 84 + done.routes.mv, `pulse ${done.pulse}, routes ${JSON.stringify(done.routes)}`);
await p.screenshot({ path: path.join(OUT, '2-pulses.png') });
// 6. Walk a cable: View item rides an AC cable at eye height; the walker moves along it.
await p.evaluate(() => { window.SIM.menu.open('View'); [...document.querySelectorAll('.gm-panel[data-menu="View"] button')].find(x => x.textContent.trim() === 'Walk a cable').click(); window.SIM.menu.close(); });
await p.waitForTimeout(1500); const r1 = await p.evaluate(() => window.SIM.engineLock.state().ride);
await p.waitForTimeout(2000); const r2 = await p.evaluate(() => window.SIM.engineLock.state().ride);
const walkOn = await p.evaluate(() => !!(window.walkFps && window.walkFps.state().on));
check('walk a cable: an AC cable selected, the rider moves along it, first person on', r1 && r2 && /^ST-INV/.test(r1.id) && r2.d - r1.d > 3 && walkOn, `${r1 && r1.id}: ${r1 && r1.d.toFixed(1)} -> ${r2 && r2.d.toFixed(1)} m, walk-fps ${walkOn}`);
await p.screenshot({ path: path.join(OUT, '3-walk-cable.png') });
await p.evaluate(() => window.SIM.engineLock.stop());
// 7. Hygiene: the EA was never called; no page errors; nothing edited outside the two files.
check('EA never called (fixture answered every request)', ea.every(u => /environment\.data\.gov\.uk/.test(u)) && ea.length >= 1, `${ea.length} routed`);
check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
await b.close(); server.close();
const failed = results.filter(r => !r.ok).length;
console.log(`${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
})().catch(e => { console.error('FAIL harness', e); process.exit(1); });Farm Assess
A JavaScript module in the tests folder of Energy Transition Simulator that tests substations and LiDAR terrain, using EPSG:27700.
testenergy-transition-simulator / tests/farm-assess.cjs · lines 1–244 of 244 · Not reached from any entry point (candidate for review) · pattern empty (shared by 10 files)
- What it does
- It tests substations and LiDAR terrain. Defines 14 functions or classes, including ok, near, sq, get, T. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'farm'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: substations, LiDAR terrain, 33kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 33kV.
- What it achieves
- It is built from the near step (`near`), the get step (`get`) and the empty5 step (`empty5`). Smoke check for `prototype/mod/farm-assess.js`: the pure core only, on a small synthetic fixture. Its code works with 33 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- Farm Assess (require)
- Used by
- none found
- Produces
- ok, near, sq, get, T, empty5, fakeInfo, lift, dtmTile, tan, z, ditch
- Defines here
- ok, near, sq, get, T, empty5, fakeInfo, lift, dtmTile, tan, z, ditch, inR, mk
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/farm-assess.cjs:1-244 · blob 9fd7d491632ab1b1306bbbc0dbffdb0b9066583e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// Smoke check for prototype/mod/farm-assess.js: the pure core only, on a small synthetic fixture. No network.
// Run: node tests/farm-assess.cjs
const A = require('../prototype/mod/farm-assess.js');
let pass = 0, fail = 0;
const ok = (name, c, ev) => { (c ? pass++ : fail++); console.log(`${c ? 'PASS' : 'FAIL'} ${name} -- ${ev}`); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
// 1. The site box is the R5 tile: 2,048 m on the National Grid lattice.
const b = A.tileBox(412345, 290001);
ok('tile box on 2,048 m lattice', b.e0 === 411648 && b.n0 === 288768 && b.e1 - b.e0 === 2048 && b.key === '411648_288768', JSON.stringify(b));
// 2. Synthetic fixture (Esri rings, outer clockwise, hole counter-clockwise), all in the box above.
const e0 = b.e0, n0 = b.n0, W = 2048;
const sq = (x0, y0, x1, y1, cw = true) => cw ? [[x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0]] : [[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]];
const fixture = [
{ grade: 'Grade 2', rings: [sq(e0 - 500, n0 - 500, e0 + 1024, n0 + W + 500)] }, // west half, overhangs 3 sides
{ grade: 'Grade 3', rings: [sq(e0 + 1024, n0, e0 + W, n0 + 1024), sq(e0 + 1200, n0 + 200, e0 + 1400, n0 + 400, false)] }, // SE quarter minus 200x200 hole
{ grade: 'Grade 4', rings: [sq(e0 + 5000, n0 + 5000, e0 + 6000, n0 + 6000)] } // wholly outside: ignored
];
const r = A.assessBox(fixture, b);
const get = g => (r.rows.find(x => x.grade === g) || {}).share || 0;
ok('box area 419.43 ha', near(r.boxHa, 419.4304, 1e-3), r.boxHa);
ok('grade 2 share = 50% (clipped to box)', near(get('Grade 2'), 0.5, 1e-9), get('Grade 2'));
ok('grade 3 share = 25% minus hole', near(get('Grade 3'), (1024 * 1024 - 40000) / (W * W), 1e-9), get('Grade 3'));
ok('outside polygon ignored', !r.rows.some(x => x.grade === 'Grade 4'), r.rows.map(x => x.grade).join(','));
const none = r.rows.find(x => /no ALC/.test(x.grade));
ok('uncovered area reported, not filled', none && near(none.share, 0.25 + 40000 / (W * W), 1e-9), none && none.share);
ok('shares sum to 100%', near(r.rows.reduce((s, x) => s + x.share, 0), 1, 1e-9), r.rows.reduce((s, x) => s + x.share, 0));
ok('BMV 1+2 share = grade 2 share', near(r.bmv12Share, 0.5, 1e-9), r.bmv12Share);
ok('clipped vertices all inside box', r.clipped.every(f => f.rings.every(g => g.every(p => p[0] >= b.e0 - 1e-6 && p[0] <= b.e1 + 1e-6 && p[1] >= b.n0 - 1e-6 && p[1] <= b.n1 + 1e-6))), r.clipped.length + ' polygons');
// 3. Negative control: an empty answer gives 100% "no ALC polygon", never a grade.
const e = A.assessBox([], b);
ok('empty answer -> 100% uncovered (negative control)', e.rows.length === 1 && near(e.rows[0].share, 1, 1e-12) && e.bmv12Share === 0, JSON.stringify(e.rows));
// 4. Nearest substation: 1 degree of latitude on the mean sphere is 111,195 m.
const s = A.nearest([{ lat: 53, lon: -1, kv: [132] }, { lat: 52.5, lon: -1, kv: [400] }], 52, -1);
ok('nearest substation picked and distance', s.kv[0] === 400 && near(s.m, 55597.5, 1), `${s.m.toFixed(1)} m ${s.kv}`);
ok('voltage parse "132000;33000" -> [132,33]', JSON.stringify(A.kvList('132000;33000')) === '[132,33]', A.kvList('132000;33000'));
// 5. The query is one bounding-box request in EPSG:27700 to the Natural England service, with the licence stated.
const u = A.queryUrl(b);
ok('query is one bbox in 27700', /geometry=411648%2C288768%2C413696%2C290816/.test(u) && /inSR=27700/.test(u) && /esriGeometryEnvelope/.test(u), u.slice(0, 120));
ok('licence OGL v3 and attribution present', /Open Government Licence v3\.0/.test(A.SRC.licence) && /Natural England/.test(A.SRC.attribution), A.SRC.licence);
const cc = A.centroid([[0, 0], [0, 10], [10, 10], [10, 0], [9, 0], [8, 0], [7, 0]]);
ok('label at area centroid, not vertex average', near(cc[0], 5, 1e-9) && near(cc[1], 5, 1e-9), cc);
// 6. Honest GRID line (round 2): source, licence and provenance words on screen; voltage reported; never an offer.
const sub = { m: 3130, kv: [33], op: 'UK Power Networks' };
const gd = A.gridText(sub, false), gp = A.gridText(sub, true);
ok('grid line names OSM source and ODbL', gd.includes('GridAtlas substations from OpenStreetMap (© OpenStreetMap contributors, ODbL)'), gd.slice(-90));
ok('voltage marked [reported, as tagged]', gd.includes('33 kV [reported, as tagged]'), gd.slice(0, 120));
ok('distance marked [derived, straight line from map centre]', gd.includes('3.13 km [derived, straight line from map centre]'), gd.slice(0, 80));
ok('warning: private/generator, not a connection point, capacity not assessed', gd.includes('may be a private or generator substation; not a connection point or offer; capacity not assessed'), '');
ok('network operator shown', gd.includes('operator UK Power Networks [reported, as tagged]'), '');
ok('phone line keeps meaning: derived, reported, not an offer, ODbL', /\[derived\]/.test(gp) && /\[reported\]/.test(gp) && /not a connection offer/.test(gp) && /capacity not assessed/.test(gp) && /ODbL/.test(gp) && gp.length < 170, gp.length + ' chars');
const nv = A.gridText({ m: 900, kv: [] }, false), nvp = A.gridText({ m: 900, kv: [] }, true);
ok('no voltage tag -> "voltage not tagged", no kV claimed', nv.includes('voltage not tagged') && nvp.includes('voltage not tagged') && !/kV/.test(nv + nvp), nv.slice(0, 100));
ok('no substations loaded -> says so, no distance', !/km/.test(A.gridText(null, false)) && /not loaded/.test(A.gridText(null, true)), A.gridText(null, false));
ok('operator kept only for network operators', ['UK Power Networks', 'NIE Networks', 'SSEN Transmission', 'Northern Powergrid', 'NPG'].every(o => A.netOperator(o) === o)
&& ['Network Rail', 'RWE Renewables', 'Scottish Power Renewables', 'Humber Gateway OFTO', 'Michelin Tyre PLC', 'Lightsource Renewable Energy', 'Some Farm', ''].every(o => A.netOperator(o) === ''), '');
ok('no operator -> says so, never an OSM name', A.gridText({ m: 900, kv: [33], op: '', name: 'Hill Farm' }, false).includes('no network operator recognised in its tags') && !/Hill Farm/.test(A.gridText({ m: 900, kv: [33], name: 'Hill Farm' }, false)), '');
// 7. Grade 3 wording: none present -> "Grade 3: 0%", never "may include BMV 3a".
const g0 = A.grade3Text({ grade3Share: 0, bmv12Share: 1 }, false), g0p = A.grade3Text({ grade3Share: 0, bmv12Share: 1 }, true);
ok('no grade 3 -> "Grade 3: 0%", no "may include"', g0.includes('Grade 3: 0%') && g0p.includes('Grade 3: 0%') && !/may include|not split/.test(g0 + g0p), g0);
const g3 = A.grade3Text({ grade3Share: 0.25, bmv12Share: 0.5 }, false);
ok('grade 3 present -> 3a/3b caveat kept', g3.includes('25.0% may include BMV 3a') && /Field survey needed/.test(g3), g3);
// 8. Round 3: the box is centred on arrival, edges on the 256 m BNG lattice, 2,048 m square.
const T = (name, f) => { let c = false, ev = ''; try { [c, ev] = f(); } catch (x) { ev = 'threw: ' + x.message; } ok(name, c, ev); };
let seed = 7; const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
const pts = Array.from({ length: 2000 }, () => [100000 + rnd() * 500000, 100000 + rnd() * 800000]);
T('(a) centre >= 896 m from every box edge (2,000 random points, and cell corners)', () => {
let worst = Infinity; for (const [e, n] of pts.concat([[412416 + 128, 290048 - 128], [412416 - 127.999, 290048 + 127.999]])) worst = Math.min(worst, A.edgeMargin(A.centredBox(e, n), e, n));
return [worst >= 896, 'worst margin ' + worst.toFixed(3) + ' m']; });
T('(a) centre 30 m above a tile south edge: fixed tile margin < 896 m, centred box margin >= 896 m', () => {
const e = 520300, n = 335872 + 30, t = A.tileBox(e, n), c = A.centredBox(e, n); // synthetic; 335872 = 164 x 2048
return [A.edgeMargin(t, e, n) < 896 && A.edgeMargin(c, e, n) >= 896, `tile ${A.edgeMargin(t, e, n).toFixed(0)} m, centred ${A.edgeMargin(c, e, n).toFixed(0)} m`]; });
T('(b) moves under 256 m inside one 256 m cell reuse the same cache key', () => {
let same = 0, k = 0; for (const [e, nn] of pts.slice(0, 500)) { const ce = Math.round(e / 256) * 256, cn = Math.round(nn / 256) * 256;
const k0 = A.centredBox(ce - 127, cn - 127).key; for (const [de, dn] of [[0, 0], [254, 0], [0, 254], [254, 254], [100, 37]]) { k++; if (A.centredBox(ce - 127 + de, cn - 127 + dn).key === k0) same++; } }
return [same === k, `${same}/${k} same key`]; });
T('(b) any move under 256 m shifts each edge by at most one 256 m step (neighbour key, never a jump)', () => {
let bad = 0; for (const [e, n] of pts) { const a = A.centredBox(e, n), b2 = A.centredBox(e + 255 * (rnd() * 2 - 1), n + 255 * (rnd() * 2 - 1));
if (Math.abs(a.e0 - b2.e0) > 256 || Math.abs(a.n0 - b2.n0) > 256) bad++; } return [bad === 0, bad + ' jumps']; });
T('(b) edges lie on the 256 m BNG lattice', () => [pts.every(([e, n]) => { const b2 = A.centredBox(e, n); return [b2.e0, b2.n0, b2.e1, b2.n1].every(v => v % 256 === 0); }), 'all edges % 256 == 0']);
T('(c) centred box area stays 419.43 ha; one envelope query for it', () => {
const cb = A.centredBox(412345, 290001), rr = A.assessBox([], cb);
return [near(rr.boxHa, 419.4304, 1e-6) && cb.e1 - cb.e0 === 2048 && cb.n1 - cb.n0 === 2048 && /geometry=411392%2C289024%2C413440%2C291072/.test(A.queryUrl(cb)), `${rr.boxHa} ha, ${JSON.stringify(cb)}`]; });
// 9. Round 4: EA Flood Map for Planning, Flood Zones 3 and 2, clipped to the same centred box (made-up geometry).
T('(fz) one service-level envelope query for both zone layers, EPSG:27700, the centred box', () => {
const cb = A.centredBox(412345, 290001), u = A.floodQueryUrl(cb);
return [/Flood_Map_for_Planning\/FeatureServer\/query\?/.test(u) && u.includes(encodeURIComponent('{"1":"1=1","2":"1=1"}')) && /geometry=411392%2C289024%2C413440%2C291072/.test(u) && /inSR=27700/.test(u) && /esriGeometryEnvelope/.test(u), u.slice(0, 140)]; });
T('(fz) licence OGL v3.0, EA attribution, data date, 40 s EA pace', () => [A.FZ.licence === 'Open Government Licence v3.0' && /Environment Agency copyright/.test(A.FZ.attribution) && /Nov 2023/.test(A.FZ.date) && A.EA_GAP_MS >= 40000, A.FZ.date]);
T('(fz) clip and area: FZ3 strip 512 m wide overhanging the box, FZ2 = west half with a 100x100 hole', () => {
const cb = A.centredBox(412345, 290001), x0 = cb.e0, y0 = cb.n0;
const ans = { layers: [
{ id: 1, features: [{ geometry: { rings: [sq(x0 - 300, y0 - 300, x0 + 512, y0 + 2048 + 300)] } }] },
{ id: 2, features: [{ geometry: { rings: [sq(x0 - 300, y0 - 300, x0 + 1024, y0 + 2048 + 300), sq(x0 + 700, y0 + 700, x0 + 800, y0 + 800, false)] } },
{ geometry: { rings: [sq(x0 + 9000, y0, x0 + 9500, y0 + 500)] } }] } ] };
const r = A.floodShares(A.parseFlood(ans), cb), t = A.floodText(r, false), tp = A.floodText(r, true);
const ok3 = near(r.fz3.share, 0.25, 1e-12) && near(r.fz3.ha, 104.8576, 1e-6);
const ok2 = near(r.fz2.share, (1024 * 2048 - 10000) / (2048 * 2048), 1e-12) && near(r.fz2.ha, (1024 * 2048 - 10000) / 1e4, 1e-6);
const txt = t.includes('Flood Zone 3 25.0% (105 ha) [derived]') && t.includes('Flood Zone 2 49.8% (209 ha) [derived]') && t.includes('planning flood zones, not a site flood risk assessment') && /do not add/.test(t);
const inside = r.clipped.fz3.concat(r.clipped.fz2).every(f => f.rings.every(g => g.every(p => p[0] >= cb.e0 - 1e-6 && p[0] <= cb.e1 + 1e-6 && p[1] >= cb.n0 - 1e-6 && p[1] <= cb.n1 + 1e-6)));
return [ok3 && ok2 && txt && inside && r.clipped.fz2.length === 1 && /\[derived\]/.test(tp) && /not a site flood risk assessment/.test(tp), `fz3 ${r.fz3.share} ${r.fz3.ha} ha; fz2 ${r.fz2.share.toFixed(6)}; ${t.slice(0, 110)}`]; });
T('(fz) negative: an empty answer gives 0% in both zones, with the caveat', () => {
const cb = A.centredBox(412345, 290001), r = A.floodShares(A.parseFlood({ layers: [{ id: 1, features: [] }, { id: 2, features: [] }] }), cb), t = A.floodText(r, false);
return [r.fz3.share === 0 && r.fz2.share === 0 && t.includes('Flood Zone 3 0.0% (0 ha) [derived]') && t.includes('Flood Zone 2 0.0% (0 ha) [derived]') && t.includes('planning flood zones, not a site flood risk assessment'), t.slice(0, 160)]; });
T('(fz) no answer (service error) -> says so, shows no value', () => {
let threw = false; try { A.parseFlood({ error: { message: 'Service unavailable' } }); } catch (x) { threw = true; }
const t = A.floodText(null, false, 'HTTP 503'), tp = A.floodText(null, true);
return [threw && /did not answer/.test(t) && /no value shown/.test(t) && !/%/.test(t + tp) && /no value shown/.test(tp), t]; });
// 10. Round 5: honest flood wording (undefended zones; phone overlap note; phone transfer-limit warning).
const empty5 = () => A.floodShares(A.parseFlood({ layers: [{ id: 1, features: [] }, { id: 2, features: [] }] }), A.centredBox(412345, 290001));
T('(fz5) desktop and phone say the zones are undefended and ignore flood defences', () => {
const t = A.floodText(empty5(), false), tp = A.floodText(empty5(), true), w = /undefended: they ignore flood defences \[reported, EA\], so a defended area can still show as Zone 3/;
return [w.test(t) && w.test(tp), tp]; });
T('(fz5) phone line says Zone 2 includes Zone 3; do not add', () => {
const tp = A.floodText(empty5(), true); return [tp.includes('Zone 2 includes Zone 3; do not add'), tp.slice(0, 120)]; });
T('(fz5) phone line warns when the service transfer limit is hit, and not otherwise', () => {
const hit = A.floodShares(A.parseFlood({ layers: [{ id: 1, features: [], exceededTransferLimit: true }, { id: 2, features: [] }] }), A.centredBox(412345, 290001));
const tp = A.floodText(hit, true);
return [hit.exceeded && /WARNING: service transfer limit hit; shares incomplete/.test(tp) && !/WARNING/.test(A.floodText(empty5(), true)), tp.slice(-70)]; });
// 11. Round 6: the result panel sits above the bottom band (honesty-ux offsets) and scrolls inside a capped height.
T('(panel6) offsets: phone (<=480 px) bottom 124 px, desktop bottom 44 px', () => {
const p = A.panelLayout(390, 844, 382, [], 0), p480 = A.panelLayout(480, 844, 472, [], 0), d = A.panelLayout(1280, 800, 728, [], 0);
return [A.PANEL.phone === 124 && A.PANEL.desktop === 44 && p.bottom === 124 && p.phone && p480.bottom === 124 && d.bottom === 44 && !d.phone, `phone ${p.bottom}, 480 ${p480.bottom}, desktop ${d.bottom}`]; });
T('(panel6) phone 390: lifted above joystick and find box, never below 124, max-height capped under the button bar', () => {
const joy = { left: 246, right: 366, top: 684, bottom: 804 }, fg = { left: 150, right: 382, top: 634, bottom: 668 };
const p = A.panelLayout(390, 844, 382, [joy, fg], 350);
return [p.bottom === 214 && p.bottom >= 124 && p.maxHeight === 844 - 214 - 350 - 4 && 844 - p.bottom <= fg.top, JSON.stringify(p)]; });
T('(panel6) negative: obstacles beside or above the panel do not lift it; height never below the floor', () => {
const p = A.panelLayout(1280, 800, 728, [{ left: 1136, right: 1256, top: 640, bottom: 760 }, { left: 0, right: 700, top: 8, bottom: 60 }], 790);
return [p.bottom === 44 && p.maxHeight === A.PANEL.minH, JSON.stringify(p)]; });
// 12. Round 7: #info is shared; the farmer lift is undone exactly when another module writes #info.
const fakeInfo = (style, cls) => { const c = new Set(cls || []); return { textContent: '', style: Object.assign({}, style),
classList: { contains: k => c.has(k), add: k => c.add(k), remove: k => c.delete(k) } }; };
const ORIG = { whiteSpace: '', bottom: '', maxHeight: '', overflowY: '', maxWidth: '', boxSizing: '', zIndex: '', background: 'rgba(1, 2, 3, 0.5)' };
const lift = (el, text) => { el.textContent = text; Object.assign(el.style, { whiteSpace: 'pre-wrap', bottom: '214px', maxHeight: '276px', overflowY: 'auto', maxWidth: '374px', boxSizing: 'border-box', zIndex: '5', background: 'rgba(0,10,20,.88)' }); el.classList.add('fa-lift'); };
const FARM = A.FARM_HEAD + ' 519.936,332.8 km (centred on arrival, 419 ha). ALC provisional 1:250k:';
T('(info7) records all 8 inline styles and the class; a foreign SIM.info write restores them exactly and drops fa-lift', () => {
const el = fakeInfo(ORIG), prev = A.snapInfo(el); lift(el, FARM);
const kept = A.infoChanged(prev, el); el.textContent = '52.88900, -0.20000 (typed coordinates, WGS84).'; const done = A.infoChanged(prev, el);
return [A.INFO_KEYS.length === 8 && !kept && done && JSON.stringify(el.style) === JSON.stringify(ORIG) && !el.classList.contains('fa-lift'), JSON.stringify(el.style)]; });
T('(info7) a second farmer result after a restore re-applies the lift (fresh snapshot is the original)', () => {
const el = fakeInfo(ORIG); let prev = A.snapInfo(el); lift(el, FARM); el.textContent = 'Pylons: 12 at GridAtlas line vertices.'; A.infoChanged(prev, el);
prev = A.snapInfo(el); lift(el, FARM);
return [el.classList.contains('fa-lift') && el.style.bottom === '214px' && JSON.stringify(prev.style) === JSON.stringify(ORIG) && !prev.lift, JSON.stringify(prev)]; });
T('(info7) negative: a farmer re-render (text still starts with the LAND line) does NOT clear the lift', () => {
const el = fakeInfo(ORIG), prev = A.snapInfo(el); lift(el, FARM); el.textContent = FARM + '\n Grade 1 83.4%';
const r = A.infoChanged(prev, el), r0 = A.infoChanged(null, el);
return [!r && !r0 && el.classList.contains('fa-lift') && el.style.zIndex === '5' && el.style.background === 'rgba(0,10,20,.88)' && !A.isFarmText(' ' + FARM), JSON.stringify(el.style)]; });
// 13. Round 8: the LAND line names the box by its OS grid reference (box centre), not the internal key.
// Known points: OS published references (Ben Nevis summit trig NN 16667 71278; TF, TQ, SU and NT 100 km squares).
T('(gref8) TF: box centre 520960,333824 gives TF 2096 3382 (8-figure, truncated)', () => { const g = A.gridRef(520960, 333824); return [g === 'TF 2096 3382', g]; });
T('(gref8) TQ: Trafalgar Square about 530000,180400 gives TQ 3000 8040; SU 441234,112345 gives SU 4123 1234', () => {
const a = A.gridRef(530000, 180400), c = A.gridRef(441234, 112345); return [a === 'TQ 3000 8040' && c === 'SU 4123 1234', a + ' | ' + c]; });
T('(gref8) NT and 10-figure: Edinburgh 325000,673000 gives NT 2500 7300; Ben Nevis 216667,771278 gives NN 16667 71278', () => {
const a = A.gridRef(325000, 673000), c = A.gridRef(216667, 771278, 10); return [a === 'NT 2500 7300' && c === 'NN 16667 71278', a + ' | ' + c]; });
T('(gref8) corners and the skipped I: 0,0 is SV; 699999,1299999 is JM; HP (Shetland) 460000,1210000; no square uses I', () => {
const a = A.gridRef(0, 0), c = A.gridRef(699999, 1299999), d = A.gridRef(460000, 1210000);
let noI = true; for (let e = 50000; e < 700000; e += 100000) for (let n = 50000; n < 1300000; n += 100000) if (/I/.test(A.gridRef(e, n).slice(0, 2))) noI = false;
return [a === 'SV 0000 0000' && c === 'JM 9999 9999' && d === 'HP 6000 1000' && noI, [a, c, d, noI].join(' | ')]; });
T('(gref8) negative: outside the grid or not a number gives null, never a wrong square', () => {
const bad = [[-1, 300000], [300000, -0.5], [700000, 300000], [300000, 1300000], [NaN, 1], [1, Infinity], ['520960', 333824], [520960, 333824, 7], [520960, 333824, 12]];
const out = bad.map(x => A.gridRef(x[0], x[1], x[2])); return [out.every(v => v === null), JSON.stringify(out)]; });
T('(gref8) LAND line head: grid ref of the centred box, tagged [derived]; still starts with FARM_HEAD; cache key unchanged', () => {
const bx = A.centredBox(520900, 333800), h = A.landHead(bx);
return [bx.key === 'c520960_333824' && h === 'LAND: site box TF 2096 3382 [derived, box centre, OS grid ref]' && A.isFarmText(h + ' (centred on arrival, 419 ha)') && !/519\.936/.test(h), bx.key + ' | ' + h]; });
T('(gref8) negative: a box outside the lettered grid falls back to km and says so, never a letter pair', () => {
const h = A.landHead({ e0: -2048, n0: 300000, e1: 0, n1: 302048 }); return [A.isFarmText(h) && /km BNG \[derived, box centre; outside the lettered OS grid\]/.test(h) && !/[A-Z]{2} \d/.test(h), h]; });
// 14. Round 9: SLOPE of the site box from an already-streamed R5 DTM tile (lidar-stream's decoded form). No network.
// geo in the decoder's form: rows north to south, west/north = the tile's NW corner, res = cell size (m).
const dtmTile = (e0, n0, size, res, fn, holes) => { const w = size / res, h = w, data = new Float32Array(w * h), mask = new Uint8Array(w * h);
for (let r = 0; r < h; r++) for (let c = 0; c < w; c++) { const e = e0 + (c + 0.5) * res, n = n0 + size - (r + 0.5) * res; data[r * w + c] = fn(e, n); mask[r * w + c] = holes && holes(e, n) ? 0 : 1; }
return { geo: { data, width: w, height: h, west: e0, north: n0 + size, res }, mask, src: { product: 'LIDAR Composite DTM 1 m' }, sha: 'abcdef0123456789' }; };
const bx9 = A.centredBox(520900, 333800); // c520960_333824: E 519936-521984, N 332800-334848
const tan = d => Math.tan(d * Math.PI / 180);
T('(slope9) synthetic plane of 7.0 deg rising to the NE gives 100% in the 5-10 deg band; 3.0 deg gives 100% under 5; 14.0 deg gives 100% over 10', () => {
const out = [7, 3, 14].map(deg => { const g = tan(deg) / Math.SQRT2; // equal E and N components; magnitude tan(deg)
const t = dtmTile(519000, 332000, 4096, 4, (e, n) => 10 + g * (e - 519000) + g * (n - 332000));
const sl = A.slopeBands([t], bx9); return sl.bands.map(x => x.share); });
return [near(out[0][1], 1, 1e-12) && near(out[1][0], 1, 1e-12) && near(out[2][2], 1, 1e-12), JSON.stringify(out)]; });
T('(slope9/r10) a flat tile gives 100% under 5 deg over the whole 419 ha box, tagged [derived, 5 m blocks from DTM 1 m: Environment Agency LIDAR Composite, OGL v3.0], licence and attribution named', () => {
const sl = A.slopeBands([dtmTile(519000, 332000, 4096, 1, () => 4.2)], bx9), d = A.slopeText(sl, false), ph = A.slopeText(sl, true), cr = A.slopeCredit(sl);
return [near(sl.bands[0].share, 1, 1e-12) && near(sl.assessedHa, 419.4304, 1e-6) && sl.bands[1].ha === 0 && sl.bands[2].ha === 0
&& /under 5° 100\.0% \(419 ha\)/.test(d) && d.indexOf('[derived, 5 m blocks from DTM 1 m: Environment Agency LIDAR Composite, OGL v3.0]') > 0 && d.indexOf('5 m blocks from DTM 1 m (mean of measured cells, blocks at least 80% measured)') > 0 && ph.indexOf('5 m blocks from DTM 1 m') > 0 && /^SLOPE: <5° 100\.0%/.test(ph)
&& /Open Government Licence v3\.0\. Contains Environment Agency information © Environment Agency and database right\./.test(cr) && /receipt abcdef012345/.test(cr), d + ' || ' + ph + ' || ' + cr]; });
T('(slope9) a missing tile gives "slope not assessed (no DTM tile loaded)" and no value, on desktop and phone', () => {
const a = A.slopeBands([], bx9), c = A.slopeBands(undefined, bx9), d = A.slopeBands([{ none: 'outside the service envelope' }], bx9);
const t = A.slopeText(a, false), tp = A.slopeText(null, true);
return [a === null && c === null && d === null && t === 'SLOPE: slope not assessed (no DTM tile loaded).' && tp === t && A.slopeCredit(null) === '' && !/\d/.test(t), t]; });
T('(slope9, 1 m path) bands split by area: W part flat, middle 8 deg, E part 15 deg; only cells in the box count; shares are of the assessed part', () => {
// Tile E 520960-523008, N 333824-335872 overlaps the box in E 520960-521984, N 333824-334848. Its W column and S row are
// tile edges (no west/south neighbour), so 1023 x 1023 cells are assessable. The kinks at x1, x2 move at most one column.
const s8 = tan(8), s15 = tan(15), x1 = 521300, x2 = 521700;
const z = e => e < x1 ? 0 : e < x2 ? (e - x1) * s8 : (x2 - x1) * s8 + (e - x2) * s15;
const sl = A.slopeBands([dtmTile(520960, 333824, 2048, 1, e => z(e))], bx9, { block: 1 }), H = sl.bands.map(x => x.ha * 1e4);
const rows = 1023, flat = (x1 - 520961) * rows, mid = (x2 - x1) * rows, steep = (521984 - x2) * rows;
return [near(sl.assessedHa, 1023 * 1023 / 1e4, 1e-9) && Math.abs(H[0] - flat) <= rows && Math.abs(H[1] - mid) <= rows && Math.abs(H[2] - steep) <= rows
&& near(sl.bands.reduce((s, x) => s + x.share, 0), 1, 1e-12) && near(sl.cover, 1023 * 1023 / (2048 * 2048), 1e-12), JSON.stringify(H) + ' vs ' + [flat, mid, steep]]; });
T('(slope9, 1 m path) holes: unmeasured cells and their 4 neighbours are not assessed (never 0 m)', () => {
const t = dtmTile(519000, 332000, 4096, 1, () => 0, (e, n) => e > 521000 && e < 521100 && n > 333000 && n < 333100);
const sl = A.slopeBands([t], bx9, { block: 1 });
return [near(sl.assessedHa * 1e4, 2048 * 2048 - 100 * 100 - 4 * 100, 1e-6) && sl.bands[0].share === 1, sl.assessedHa]; });
T('(gref9) gridRef digits=0 gives null (was 8 figures via digits||8); omitted still gives 8; 6 gives 6', () => {
const z = A.gridRef(520960, 333824, 0), u = A.gridRef(520960, 333824), n6 = A.gridRef(520960, 333824, 6);
return [z === null && u === 'TF 2096 3382' && n6 === 'TF 209 338', [z, u, n6].join(' | ')]; });
// 15. Round 10: SCALE. 5 m blocks (mean of measured 1 m cells, blocks at least 80% measured) so ditch banks are not "steep".
T('(slope10) a narrow 2 m ditch, 1.5 m deep with vertical banks, cut into flat ground: over 10 deg at 1 m, but 100% under 5 deg at 5 m blocks', () => {
const ditch = (e, n) => (e >= 521001 && e < 521003) || (n >= 333401 && n < 333403) ? -1.5 : 0; // one N-S and one E-W ditch
const t = dtmTile(519000, 332000, 4096, 1, ditch), s1 = A.slopeBands([t], bx9, { block: 1 }), s5 = A.slopeBands([t], bx9);
return [s1.bands[2].ha > 0.8 && s5.block === 5 && s5.bands[0].share === 1 && s5.bands[2].ha === 0 && s5.bands[1].ha === 0,
'1 m over 10: ' + s1.bands[2].ha.toFixed(3) + ' ha; 5 m: ' + s5.bands.map(x => x.share).join(',')]; });
T('(slope10) 5 m blocks keep a real 7 deg field in the 5-10 band and a 14 deg bank over 10 (averaging does not flatten true slope)', () => {
const out = [7, 14].map(deg => { const g = tan(deg); return A.slopeBands([dtmTile(519000, 332000, 4096, 1, (e, n) => g * (n - 332000))], bx9).bands.map(x => x.share); });
return [near(out[0][1], 1, 1e-9) && near(out[1][2], 1, 1e-9), JSON.stringify(out)]; });
T('(slope10) the 80% rule: blocks with 5 of 25 cells unmeasured are used (their junk heights ignored); 6 of 25 are not, nor their 4 neighbours', () => {
const inR = (e, n) => e > 521000 && e < 521100 && n > 333000 && n < 333100, k5 = [0, 1, 2, 3, 4], k6 = [0, 1, 2, 3, 4, 5];
const mk = K => { const t = dtmTile(519000, 332000, 4096, 1, () => 0, (e, n) => inR(e, n) && K.includes((Math.floor(e) % 5) * 5 + (Math.floor(n) % 5)));
for (let i = 0; i < t.mask.length; i++) if (!t.mask[i]) t.geo.data[i] = 1000; return A.slopeBands([t], bx9); };
const a = mk(k5), b6 = mk(k6), box = 2048 * 2048;
return [near(a.assessedHa * 1e4, box, 1e-6) && a.bands[0].share === 1 && near(b6.assessedHa * 1e4, box - (400 + 80) * 25, 1e-6) && b6.bands[0].share === 1,
a.assessedHa + ' / ' + b6.assessedHa]; });
T('(slope10) the over-10 deg outline: none on flat ground; on a 14 deg plane every segment is one 5 m block side on the 5 m BNG lattice', () => {
const f0 = A.slopeBands([dtmTile(519000, 332000, 4096, 1, () => 0)], bx9, { edges: true });
const s = A.slopeBands([dtmTile(519000, 332000, 4096, 1, (e, n) => tan(14) * (n - 332000))], bx9, { edges: true });
const okSeg = s.edges.every(q => q.every(v => v % 5 === 0) && Math.hypot(q[2] - q[0], q[3] - q[1]) === 5);
return [f0.edges.length === 0 && s.edges.length > 0 && okSeg && !s.edgesCut, f0.edges.length + ' / ' + s.edges.length]; });
T('(slope10) the scale is said: 5 m blocks from DTM 1 m by default; block 1 on a 1 m tile says DTM 1 m and 1 cell central differences', () => {
const t = dtmTile(519000, 332000, 4096, 1, () => 0), a = A.slopeBands([t], bx9), c = A.slopeBands([t], bx9, { block: 1 });
return [A.SLOPE_BLOCK_M === 5 && A.slopeScale(a) === '5 m blocks from DTM 1 m' && A.slopeScale(c) === 'DTM 1 m' && /1 cell central differences/.test(A.slopeText(c, false)), A.slopeScale(a) + ' | ' + A.slopeScale(c)]; });
console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);Grid Assets
A JavaScript module in the tests folder of Energy Transition Simulator that tests substations footprints odbl, grid 400kV and grid substations, and uses data from the GridAtlas repository.
testenergy-transition-simulator / tests/grid-assets.cjs · lines 1–123 of 123 · Not reached from any entry point (candidate for review) · pattern inRing (shared by 3 files)
- What it does
- It tests substations footprints odbl, grid 400kV and grid substations. Defines wait, inRing, inSub. Uses libraries http, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
- Inputs & outputs
- In: data source: gridatlas data; JSON file substations-footprints.odbl.json; GeoJSON file grid_400kv.geojson; GeoJSON file grid_substations.geojson. Out: JSON file results.json. Voltage levels named: 400kV.
- What it achieves
- It is built from the wait step (`wait`), the in ring helper (`inRing`) and the in sub helper (`inSub`). Grid assets check: pylons and substations are MAPPED POSITIONS, drawn through the ONE wire layer, labelled honestly. Its code works with 400 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- http, fs, path, playwright
- Used by
- none found
- Produces
- wait, inRing, inSub
- Defines here
- wait, inRing, inSub
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/grid-assets.cjs:1-123 · blob 17da3c223eb6e88eb0274a18aace95c7e8562c77 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Grid assets check: pylons and substations are MAPPED POSITIONS, drawn through the ONE wire layer, labelled honestly.
// Serves prototype/ locally, opens overlay.html in Chrome, and checks against the raw GridAtlas files (fetched here in
// Node, once, independently of the page):
// 1. every tower not flagged "estimated" equals a vertex of the GridAtlas line files EXACTLY (===, no tolerance);
// 2. every substation compound sits EXACTLY on its GridAtlas point;
// 3. the towers are blocks in SIM.blocks (the one wire layer) and the old 'pylons-real' custom layer is gone;
// 4. place-frame round trip: each tower's local base point maps back to its lat/lon within 1 mm (consistency only);
// 5. no drawn tower falls inside a substation footprint (footprints read in Node, own point-in-polygon);
// 6. estimated infill towers lie on the straight segment between two line vertices (a place with a long span);
// 7. the labels on screen say "assumed at mapped line vertices", name GridAtlas and OpenStreetMap, and say what is estimated.
// Screenshots go to $OUT (default test-output/grid-assets). Exit 1 on any FAIL.
const http = require('http'), fs = require('fs'), path = require('path');
const { chromium } = require('playwright');
const ROOT = path.join(__dirname, '..', 'prototype');
const OUT = process.env.OUT || path.join(__dirname, '..', 'test-output', 'grid-assets');
const GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data';
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
fs.mkdirSync(OUT, { recursive: true });
const server = http.createServer((q, s) => {
const f = path.join(ROOT, decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html');
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, evidence) => results.push({ name, ok: !!ok, evidence: String(evidence).slice(0, 300) });
const wait = ms => new Promise(r => setTimeout(r, ms));
// A 400 kV line in the English Midlands (a GridAtlas vertex; no site is named).
const START = { lat: 52.2441634, lon: -1.0453368 };
(async () => {
// Reference: the raw GridAtlas line files, one polite request per second.
const V = new Set();
for (const kv of ['400', '275', '132']) {
const j = await (await fetch(`${GA}/grid_${kv}kv.geojson`)).json();
for (const f of j.features) { const g = f.geometry; if (!g) continue;
for (const c of g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : []) for (const p of c) V.add(kv + '|' + p[0] + '|' + p[1]); }
await wait(1000);
}
const FPS = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'substations-footprints.odbl.json'), 'utf8')).f.map(r => r[2]);
const inRing = (x, y, R) => { let c = false; for (let i = 0, j = R.length - 1; i < R.length; j = i++) { const [xi, yi] = R[i], [xj, yj] = R[j];
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c; } return c; };
const inSub = (lon, lat) => FPS.some(R => inRing(lon, lat, R));
// A place with a long 400 kV span (> 1.6 x the 360 m typical span), so the estimated path is drawn.
let LONG = null;
{ const j = await (await fetch(`${GA}/grid_400kv.geojson`)).json(), kx = l => 111320 * Math.cos(l * Math.PI / 180);
outer: for (const f of j.features) { const g = f.geometry; if (!g) continue;
for (const c of g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : []) for (let i = 1; i < c.length; i++) {
const a = c[i - 1], b = c[i], d = Math.hypot((b[0] - a[0]) * kx(a[1]), (b[1] - a[1]) * 111320);
if (d > 1.6 * 360 && d < 2000 && a[1] > 51.5 && a[1] < 53.5) { LONG = { lon: (a[0] + b[0]) / 2, lat: (a[1] + b[1]) / 2, d }; break outer; } } } }
const S = (await (await fetch(`${GA}/grid_substations.geojson`)).json()).features.map(f => f.geometry.coordinates);
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
const b = await chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
const p = await b.newPage({ viewport: { width: 1280, height: 800 } });
const errs = []; p.on('pageerror', e => errs.push(e.message));
await p.goto(`${base}?lat=${START.lat}&lon=${START.lon}`, { waitUntil: 'load' });
await p.waitForFunction(() => window.__pylonsReal && window.__pylonsReal.count() > 0, null, { timeout: 30000 }).catch(() => {});
await p.waitForTimeout(4000); // terrain tiles and the re-grade
// 1-4: pylons.
const P = await p.evaluate(() => {
const R = window.__pylonsReal, PF = window.__pf.PF, bl = SIM.blocks.filter(b => b.pylonsReal);
let worst = 0;
for (const b of bl) { const o = PF.toLocal(b.anchor, b.lat, b.lon, 0), g = PF.fromLocal(b.anchor, o.x, o.y, 0);
const d = Math.hypot((g.lon - b.lon) * 111320 * Math.cos(b.lat * Math.PI / 180), (g.lat - b.lat) * 111320); if (d > worst) worst = d; }
return { towers: bl.map(b => ({ id: b.id, kv: b.kv, lon: b.lon, lat: b.lat, est: b.est, prov: b.prov })), live: R.count(),
layer: !!SIM.map.getLayer('pylons-real'), wire: !!SIM.map.getLayer('wire'), worst, self: R.check(),
btn: [...document.querySelectorAll('#bar button')].map(x => x.textContent), info: document.getElementById('info').textContent };
});
const inside = P.towers.filter(t => inSub(t.lon, t.lat));
check('no tower inside a substation footprint (start)', inside.length === 0 && P.self.inSub.length === 0, `${inside.length} inside of ${P.towers.length}; module dropped ${P.self.dropped} so far`);
const mapped = P.towers.filter(t => !t.est), miss = mapped.filter(t => !V.has(t.kv + '|' + t.lon + '|' + t.lat));
check('towers drawn at the start (zoom 15)', P.towers.length > 0, `${P.towers.length} tower blocks, ${mapped.length} mapped, ${P.towers.length - mapped.length} estimated`);
check('every mapped tower === a GridAtlas vertex (raw file, fetched in Node)', mapped.length > 0 && miss.length === 0, miss.length ? 'miss: ' + miss.slice(0, 5).map(t => t.id).join(' ') : `${mapped.length}/${mapped.length} exact`);
check('module self-check agrees', P.self.bad.length === 0 && P.self.exact === mapped.length, JSON.stringify({ exact: P.self.exact, est: P.self.est, bad: P.self.bad.length }));
check('every tower carries provenance', P.towers.every(t => /^(assumed: tower at a mapped line vertex|estimated)/.test(t.prov || '')), 'prov tag on each block');
check('towers are blocks of the ONE wire layer', P.wire && !P.layer && P.live === P.towers.length, `wire layer ${P.wire}, own layer ${P.layer}, live ${P.live} = blocks ${P.towers.length}`);
check('place-frame round trip < 1 mm (consistency, not truth)', P.worst < 0.001, `worst ${(P.worst * 1000).toFixed(4)} mm`);
check('pylon label: assumed at mapped line vertices, GridAtlas, OpenStreetMap, estimates', /assumed at mapped line vertices/.test(P.info) && /GridAtlas/.test(P.info) && /OpenStreetMap/.test(P.info) && /estimat/.test(P.info), P.info);
check('button "Pylons (mapped)"', P.btn.includes('Pylons (mapped)'), P.btn.join(' | '));
await p.screenshot({ path: path.join(OUT, '1-map-towers.png') });
// Walk to a mapped tower: stand 120 m south of it, look north.
const t0 = mapped[0];
await p.evaluate(t => SIM.map.jumpTo({ center: [t.lon, t.lat - 120 / 111320], zoom: 18, pitch: 78, bearing: 0 }), t0);
await p.waitForTimeout(5000); await p.screenshot({ path: path.join(OUT, '2-walk-at-tower.png') });
await p.evaluate(t => SIM.map.jumpTo({ center: [t.lon, t.lat], zoom: 16.5, pitch: 60, bearing: 30 }), t0);
await p.waitForTimeout(5000); await p.screenshot({ path: path.join(OUT, '3-drone-line.png') });
const P2 = await p.evaluate(() => { const bl = SIM.blocks.filter(b => b.pylonsReal); return bl.filter(b => !b.est).map(b => b.kv + '|' + b.lon + '|' + b.lat); });
const miss2 = P2.filter(k => !V.has(k));
check('after moving: every mapped tower still === a vertex', P2.length > 0 && miss2.length === 0, `${P2.length - miss2.length}/${P2.length} exact`);
// 6: estimated infill towers, at a long span.
if (LONG) {
await p.evaluate(t => SIM.map.jumpTo({ center: [t.lon, t.lat], zoom: 16, pitch: 65, bearing: 20 }), LONG);
await p.waitForTimeout(6000);
const E = await p.evaluate(() => window.__pylonsReal.check());
check('estimated towers drawn and each on a straight segment between two line vertices', E.est > 0 && E.estBad.length === 0 && E.bad.length === 0,
`span ${LONG.d.toFixed(0)} m; ${E.est} estimated, ${E.estBad.length} off-segment; ${E.exact} assumed-at-vertex`);
await p.screenshot({ path: path.join(OUT, '6-estimated-span.png') });
} else check('estimated towers drawn and each on a straight segment between two line vertices', false, 'no long span found');
// 2 and 5: substations. Fly to the nearest 400 kV compound.
const go = await p.evaluate(() => window.SUBS.go(400));
await p.waitForTimeout(9000);
const Q = await p.evaluate(() => ({ c: window.SUBS.check(), blocks: SIM.blocks.filter(b => b.substation !== undefined).map(b => ({ i: b.substation, lon: b.lon, lat: b.lat })), info: document.getElementById('info').textContent }));
const T4 = await p.evaluate(() => ({ t: SIM.blocks.filter(b => b.pylonsReal).map(b => [b.lon, b.lat]), c: window.__pylonsReal.check() }));
const in4 = T4.t.filter(q => inSub(q[0], q[1]));
check('no tower inside a substation footprint (at the 400 kV compound)', T4.t.length > 0 && in4.length === 0 && T4.c.inSub.length === 0, `${in4.length} inside of ${T4.t.length}; module dropped ${T4.c.dropped}`);
const sbad = Q.blocks.filter(x => !(S[x.i] && S[x.i][0] === x.lon && S[x.i][1] === x.lat));
check('substation compounds === GridAtlas points (raw file)', Q.blocks.length > 0 && sbad.length === 0, `${Q.blocks.length - sbad.length}/${Q.blocks.length} exact; footprint fences ${Q.c.footprint}, estimated ${Q.c.estimated}`);
const cr = Q.c.credit; check('substation label: mapped positions, GridAtlas, OpenStreetMap, estimates', /mapped positions/.test(cr) && /GridAtlas/.test(cr) && /OpenStreetMap/.test(cr) && /estimate/.test(cr), cr);
await p.screenshot({ path: path.join(OUT, '4-substation-400.png') });
await p.evaluate(() => SIM.map.jumpTo({ zoom: 18, pitch: 75 })); await p.waitForTimeout(5000);
await p.screenshot({ path: path.join(OUT, '5-substation-walk.png') });
check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
await b.close(); server.close();
fs.writeFileSync(path.join(OUT, 'results.json'), JSON.stringify({ go, results }, null, 1));
for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} -- ${r.evidence}`);
const failed = results.filter(r => !r.ok).length; console.log(`\n${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
})().catch(e => { console.error(e); server.close(); process.exit(2); });