In this section
- Questions render · galaxies-wafers / iterations/01-route-alpha/questions.mjs lines 1–122
- Build Tiles storage · galaxies-wafers / iterations/22-fast-zoom/build_tiles.py lines 1–80
- Atlas Join transform · galaxies-wafers / iterations/32-spider-and-galaxy/atlas-join.mjs lines 1–109
- GlobalGrid2050 — Atlas V9 Page render · globalgrid2050 / 202608300453-atlas-v9/index.html lines 1–32
- Navigation Browser render · globalgrid2050 / automation/mobile_map_ui/20261118-v942/navigation.browser.mjs lines 1–43
- Navigation interaction · globalgrid2050 / automation/mobile_map_ui/20261118-v942/navigation.mjs lines 1–54
- GridAtlas Resolve automation · globalgrid2050 / automation/pipeline_release/gridatlas_resolve.py lines 1–114
- Bake storage · globalgrid2050 / energy-transition-simulator/202609280014/mod/lidar-onsite/bake.py lines 1–47
Questions
A JavaScript module in the iterations folder of Galaxies Wafers that works with layer tags (`layerTags`) and single-line diagram (SLD) sentence (`sldSentence`), covering 400kV. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.
rendergalaxies-wafers / iterations/01-route-alpha/questions.mjs · lines 1–122 of 122 · Entry point · pattern sldSentence (shared by 8 files)
- What it does
- It draws 400kV. Defines 11 functions or classes, including $, fmt, answer, fill, readJSON. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'route'): 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: 400kV.
- Inputs & outputs
- Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Iterations — 01 Route Alpha Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.
- What it achieves
- It reads JSON (`readJSON`) and is built from the fmt step (`fmt`) and the answer step (`answer`). Iteration 01, Route Alpha: the owner's three questions and the machine detail line. Its code works with 400 kV. It reads `../../layers/manifest.json`. It responds to resize and toggle events.
- Why it matters
- Loaded by the 01 Route Alpha page at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.
- Application
- galaxies-wafers · iterations/01-route-alpha · JavaScript module
- Uses
- none found
- Used by
- loaded by Iterations — 01 Route Alpha Page (script src)
- Produces
- $, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint
- Defines here
- $, fmt, answer, fill, readJSON, layerTags, sldSentence, text, mount, fit, paint
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/01-route-alpha/questions.mjs:1-122 · blob f7cbf36b2a3858658371d6bf72cab8fa5b03b06e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
/* questions.mjs — iteration 01, Route Alpha: the owner's three questions and the
* machine detail line. Counts are read at run time (layers/manifest.json, the
* layers panel's own rows, the page's own count and provenance lines); every
* function is cited to its file and line in this directory. Where an answer is
* not established it says so and why.
*/
const $ = id => document.getElementById(id);
const fmt = n => Number(n).toLocaleString('en-GB');
const DATA_PIN = 'https://globalgrid2050.com/testcode/202609142202/data/';
const SEARCH = 'repository search at ee082ea'; /* the commit the "who else" searches were run on */
/* One question and its answer. Parts are strings or [text, href] links; text only, never HTML. */
function answer(dl, q, parts) {
const dt = document.createElement('dt'); dt.textContent = q;
const dd = document.createElement('dd');
const fill = ps => {
dd.replaceChildren();
for (const p of [].concat(ps)) {
if (Array.isArray(p)) { const a = document.createElement('a'); a.textContent = p[0]; a.href = p[1]; dd.append(a); }
else dd.append(String(p));
}
};
fill(parts);
dl.append(dt, dd);
return fill;
}
/* One fetch, 15 s timeout, only when the reader opens the panel. */
async function readJSON(url) {
const c = new AbortController();
const t = setTimeout(() => c.abort(), 15000);
try {
const r = await fetch(url, { cache: 'default', signal: c.signal });
if (!r.ok) throw new Error(url + ' returned HTTP ' + r.status);
return await r.json();
} finally { clearTimeout(t); }
}
/* The layer rows' tags as the layers panel shows them now, counted from its own DOM. */
function layerTags() {
const c = new Map();
for (const t of document.querySelectorAll('#layersList .ltag')) {
const s = (t.textContent.match(/[A-Z]+/) || ['?'])[0];
c.set(s, (c.get(s) || 0) + 1);
}
return c.size ? [...c].map(([s, n]) => `${fmt(n)} ${s}`).join(', ') : 'layer rows not built yet';
}
/* Layers whose id names an SLD, read from a manifest at run time (name-match inference). */
function sldSentence(m, file) {
const hits = m.layers.filter(l => /sld/i.test(l.id));
if (!hits.length) return `None of the ${fmt(m.layers.length)} layers in ${file} carries "sld" in its id.`;
return `Of ${fmt(m.layers.length)} layers in ${file}, ${hits.length} carry "sld" in their id (name-match inference): ` +
hits.map(l => `${l.id} (${fmt(l.features)} features, draws ${l.draws})`).join(', ') + '.';
}
const text = id => ($(id)?.textContent || '').trim();
/* Collapsed by default. Nothing is read or fetched until the reader opens it; the
machine line repaints every 500 ms only while it is open. */
function mount(build, machine) {
const box = $('questions'), dl = $('qlist'), out = $('machine');
if (!box || !dl || !out) return;
let built = false, timer = 0;
/* Opened, the panel stops above whatever is drawn at the bottom (line panel, clock, strip, beam form), never over it. */
const fit = () => {
const top = box.getBoundingClientRect().top;
let floor = innerHeight;
for (const id of ['panel', 'clock', 'ptable', 'beam']) {
const el = $(id);
const r = el && !el.hidden ? el.getBoundingClientRect() : null;
if (r && r.height > 0 && r.top > top) floor = Math.min(floor, r.top);
}
box.style.maxHeight = Math.max(96, Math.min(innerHeight * 0.45, floor - top - 8)) + 'px';
};
const paint = () => {
fit();
try { out.textContent = 'Machine detail · ' + machine(); }
catch (e) { out.textContent = 'Machine detail · not established: ' + e.message; }
};
/* A bottom element that grows while the panel is open refits it at once, not at the next repaint. */
if ('ResizeObserver' in window) {
const ro = new ResizeObserver(() => { if (box.open) fit(); });
for (const id of ['panel', 'clock', 'ptable', 'beam']) if ($(id)) ro.observe($(id));
}
addEventListener('resize', () => { if (box.open) fit(); });
box.addEventListener('toggle', () => {
clearInterval(timer);
if (!box.open) return;
if (!built) { built = true; build(dl); }
paint();
timer = setInterval(paint, 500);
});
}
const COMMIT = '29c0fb4'; /* the commit that made this page; the Questions panel is added later */
mount(dl => {
const q1 = answer(dl, '1 · How does this help draw a system or a single-line diagram?', 'reading layers/manifest.json…');
answer(dl, '2 · What is this code used for?',
'Stroking layer routes over the numbered wafer so dense modules go translucent. layers-panel.mjs (copied from the root, changes listed at its line 28): ' +
'routeAlpha(n) = min(1, ?alpha ÷ √n) at line 42, ROUTE_WIDTH 0.6 px at line 35, densityLegend() at 114, toggle() at 198 loads a ticked layer, drawOverlay() at 296 strokes it (alpha applied at 309), pickAt() at 349 and inspect() at 379 answer a tap. ' +
'app.mjs is the root page copied with only its import path changed: tier1() at 86 and tier2() at 104 load the numbered database, render() at 256 draws the points, flyTo() at 295, connect() at 378. ' +
`Both import lib.mjs (place, placeAll, parseKey, indexOfKey, ownersOf, fanoutCount, connectAnswer, esc, fmt, SPACING), which 42 files in this repository import (${SEARCH}, import statements). ` +
`Nothing outside this directory imports or names routeAlpha() (${SEARCH}).`);
answer(dl, '3 · Where does it lead next?', [
`Not established: no later page carries the √features rule (${SEARCH}); the root layers-panel.mjs strokes routes with its own casing and opacity (lines 715–716 at ee082ea). ` +
'The same module routes are restyled as transmission-line voltages in ', ['iteration 04, 400kV Engine Mode', '../04-400kv-engine/'],
' (04-400kv-engine/layers-panel.mjs line 63 at ee082ea): a sibling restyle, not a derivation of this rule.']);
readJSON('../../layers/manifest.json').then(m => {
q1('It draws no electrical element; it maps code. It changes only how a layer’s LineString routes are stroked (drawOverlay() lines 309–312), so a sparse layer stays bright beside dense modules; Point marks keep their alpha. ' +
sldSentence(m, 'layers/manifest.json') + ' The draws field is the manifest’s declaration, not a count of feature types.');
}).catch(e => q1(`Not established: layers/manifest.json could not be read (${e.message}), so no SLD layer can be named. The page draws no electrical element.`));
}, () => {
const u = new URL(location.href).searchParams;
return `inputs: ?line= and ?to= (permanent line keys, positive integers, read by readURL() app.mjs line 496), ?layers= (layer ids from layers/manifest.json, layers-panel.mjs line 270), ?alpha= (route alpha scale, clamped to 0.05–1, default 1, line 37; in the URL now: ${u.get('alpha') ?? 'absent'}); ` +
`data: all-lines.meta.json, all-lines.bin, all-lines.len.bin, all-lines.family.bin, families.json and lines.bin from ${DATA_PIN} (app.mjs line 48), ${text('prov') || 'provenance not loaded yet'} · ` +
`outputs: ${text('count') || 'count not loaded yet'}; layer rows now ${layerTags()}; route alpha per layer in the LAYERS density legend · ` +
'refusals: refuse() app.mjs line 514 names why a linked or typed number cannot be used, a number never issued or a line no family carries; a layer reads FAIL with its reason or EMPTY with its reason; unknown ?layers= ids are dropped without a warning and the URL rewritten (lines 272–274) · ' +
`source: page commit ${COMMIT}; lib.mjs and layers/ from this repository`;
});Build Tiles
A Python command-line tool in the iterations folder of Galaxies Wafers that uses SHA-256. It is built from the anchor step (`anchor`) and the tile step (`tile`).
storagegalaxies-wafers / iterations/22-fast-zoom/build_tiles.py · lines 1–80 of 80 · Entry point · pattern anchor (shared by 16 files)
- What it does
- It loads data. Defines anchor, tile, main. Uses libraries __future__, hashlib, json, math, sys. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- In: JSON file index.json. Out: JSON file index.json.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/22-fast-zoom/.
- What it achieves
- Iteration 22: tile every large layer by radius band, into this directory.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/22-fast-zoom · Python CLI
- Uses
- __future__, hashlib, json, math, sys, pathlib
- Used by
- none found
- Produces
- anchor, tile, main
- Defines here
- anchor, tile, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/22-fast-zoom/build_tiles.py:1-80 · blob 52b0ee6229741732a93a248f74e360d2cd940cb7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
"""Iteration 22: tile every large layer by radius band, into this directory.
The same law as build/tile_layer.py, which this reads and does not change:
r = sqrt(key), so the ring [b*S, (b+1)*S) is exactly the key range
[(b*S)^2, ((b+1)*S)^2); a key's band is isqrt(key) // S. A Point is banded by
its key and a LineString by its first key, so each feature is in exactly one
tile. Only layers with more than TILE_OVER features are tiled; the rest stay
whole files, because a small file is one cheap fetch.
Writes iterations/22-fast-zoom/tiles/<id>/<band>.json and index.json, and
tiles/index.json naming every tiled layer. Run from the repository root:
python iterations/22-fast-zoom/build_tiles.py
"""
from __future__ import annotations
import hashlib, json, math, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
REPO = HERE.parents[1]
LAYERS = REPO / "layers"
OUT = HERE / "tiles"
S = 25
TILE_OVER = 5000
def anchor(f):
g = f["geometry"]
return g["key"] if g["type"] == "Point" else g["keys"][0]
def tile(entry):
lid = entry["id"]
src = REPO / entry["file"]
raw = src.read_bytes()
doc = json.loads(raw)
max_key = max(anchor(f) for f in doc["features"])
bands_n = math.isqrt(max_key) // S + 1
buckets = [[] for _ in range(bands_n)]
for f in doc["features"]:
buckets[math.isqrt(anchor(f)) // S].append(f)
out = OUT / lid
out.mkdir(parents=True, exist_ok=True)
for old in out.glob("*.json"):
old.unlink()
bands = []
for b, feats in enumerate(buckets):
kmin, kmax = (b * S) ** 2, ((b + 1) * S) ** 2
assert all(kmin <= anchor(f) < kmax for f in feats)
t = {"type": "CodeFeatureCollection", "substrate": doc.get("substrate"), "layer": doc["layer"],
"provenance": doc["provenance"], "tile": {"band": b, "key_min": kmin, "key_max": kmax}, "features": feats}
data = json.dumps(t, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
(out / f"{b}.json").write_bytes(data)
bands.append({"band": b, "key_min": kmin, "key_max": kmax, "file": f"tiles/{lid}/{b}.json",
"features": len(feats), "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})
total = sum(x["features"] for x in bands)
assert total == len(doc["features"]), "tiles lost or duplicated features"
index = {"type": "CodeTileIndex", "layer_id": lid, "stats": doc.get("stats"),
"source": {"file": entry["file"], "features": total, "sha256": hashlib.sha256(raw).hexdigest()},
"scheme": {"law": "band = isqrt(key) // S; keys [(b*S)^2, ((b+1)*S)^2)", "S": S, "bands": bands_n},
"bands": bands}
(out / "index.json").write_text(json.dumps(index, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{lid}: {total} features in {bands_n} bands, largest band {max(x['features'] for x in bands)}")
return lid
def main():
m = json.loads((LAYERS / "manifest.json").read_text(encoding="utf-8"))
tiled = {}
for l in m["layers"]:
if (l.get("features") or 0) > TILE_OVER and l.get("file"):
tiled[tile(l)] = f"tiles/{l['id']}/index.json"
(OUT / "index.json").write_text(json.dumps({"type": "CodeTileSet", "S": S, "tile_over": TILE_OVER,
"manifest_built_utc": m.get("built_utc"), "layers": tiled}, indent=1) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
sys.exit(main())Atlas Join
A JavaScript module in the iterations folder of Galaxies Wafers that works with atlas urls (`atlasUrls`) and atlas file (`atlasFile`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/.
transformgalaxies-wafers / iterations/32-spider-and-galaxy/atlas-join.mjs · lines 1–109 of 109
- What it does
- It calculates its inputs. Defines 8 functions or classes, including nodeUrls, atlasUrls, atlasFile, declaredLayerIds, add.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 1 file: Iterations — 32 Spider and Galaxy (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/). Reached from 90 other entry points, including Iterations — 32 Spider and Galaxy Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html).
- What it achieves
- It is built from the node urls helper (`nodeUrls`), the atlas urls helper (`atlasUrls`) and the atlas file helper (`atlasFile`). The shared keys between a spider node and Grid Atlas, read from evidence only.
- Why it matters
- Imported by Iterations — 32 Spider and Galaxy.
- Application
- galaxies-wafers · iterations/32-spider-and-galaxy · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 32 Spider and Galaxy (import)
- Produces
- ATLAS_URL, nodeUrls, atlasUrls, atlasFile, declaredLayerIds, configLayerIds, receiverLink, bucketsForLayer
- Defines here
- nodeUrls, atlasUrls, atlasFile, declaredLayerIds, add, configLayerIds, receiverLink, bucketsForLayer
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/32-spider-and-galaxy/atlas-join.mjs:1-109 · blob 52abe04acb137945b6327a33fc9f1ef9f07eb752 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
/* atlas-join.mjs — the shared keys between a spider node and Grid Atlas,
* read from evidence only. No DOM and no fetch, so the page and the tests
* import the same code.
*
* THE JOIN. A spider node joins Grid Atlas when one of its links names a Grid
* Atlas cartridge, cartridge part, composition manifest or config file, and
* that file, read as served, declares a layer id that the Grid Atlas v9
* release config also declares. Declared means one of these written forms,
* and nothing else:
* config entry { id: "<id>", label: "...", type or url: ... } on one
* line: the ukConfig / GROUPS shape
* layer constant a constant whose name carries LAYER_ID, LAYER_IDS or
* LAYERS, assigned string literals (for an object, its values)
* control attr data-layer-id="<id>"
* engine name an 'l-<id>' string literal: the engine names every config
* layer `l-${id}` (repd_grid_atlasv8/ventus-corev8engine.js,
* the visibility toggle), so 'l-subs' declares layer subs
* A GitHub link carrying #La-Lb is read over those lines only. Comment lines
* (starting with //, /* or *) are not read.
*/
export const ATLAS_URL = /gridatlas|grid_atlas|repd_grid_atlas|\/atlas\//i;
/* Every URL a node carries: its gh and ext links and any URL in its reason. */
export function nodeUrls(n) {
const raw = [n.gh, n.ext, ...(String(n.reason || '').match(/https?:\/\/[^\s"'<>)]+/g) || [])];
return [...new Set(raw.filter(Boolean).map(u => String(u).replace(/[.,;]+$/, '')))];
}
export const atlasUrls = n => nodeUrls(n).filter(u => ATLAS_URL.test(u));
/* What kind of Grid Atlas file a URL names, and where its bytes are served.
null when it names no cartridge, part, manifest or config file. */
export function atlasFile(url) {
let u;
try { u = new URL(url); } catch { return null; }
if (!ATLAS_URL.test(url)) return null;
let repo = null, ref = null, path = null, raw = null;
const gh = u.hostname === 'github.com' ? /^\/(Ventusltd\/[^/]+)\/blob\/([^/]+)\/(.+)$/.exec(u.pathname) : null;
if (gh) { [, repo, ref, path] = gh; path = decodeURIComponent(path); raw = `https://raw.githubusercontent.com/${repo}/${ref}/${path}`; }
else if (u.hostname === 'ventusltd.github.io') { path = decodeURIComponent(u.pathname.replace(/^\//, '')); raw = u.origin + u.pathname; }
else return null;
let kind = null;
if (/\/cartridges\/[^/]+\.m?js$/.test(path)) kind = 'cartridge';
else if (/(^|\/)atlas\/parts\/[^/]+\.m?js$/.test(path)) kind = 'cartridge part';
else if (/(^|\/)manifests\/[^/]+\.json$/.test(path)) kind = 'composition manifest';
else if (/(^|\/)[^/]*config[^/]*\.(json|m?js)$/i.test(path) || /(^|\/)(atlas\/(releases\/[^/]+\/)?|repd_grid_atlasv\d+\/)(index\.html)?$/.test(path)) kind = 'config';
if (!kind) return null;
const L = /^#L(\d+)(?:-L(\d+))?$/.exec(u.hash);
const lines = L ? [Number(L[1]), Number(L[2] || L[1])] : null;
const pinned = ref ? /^[0-9a-f]{40}$/.test(ref) : false;
return { kind, raw, repo, ref, path, lines, pinned };
}
const LIT = /(['"`])([^'"`\\\n]{1,80})\1/g;
/* id -> Set of declaration forms, from a file's text (optionally a line range). */
export function declaredLayerIds(text, lines) {
let t = String(text);
let rows = t.split('\n');
if (lines) rows = rows.slice(lines[0] - 1, lines[1]);
/* comment lines declare nothing: they are blanked before reading */
t = rows.map(r => (/^\s*(\/\/|\/\*|\*)/.test(r) ? '' : r)).join('\n');
const out = new Map();
const add = (id, form) => {
id = String(id).trim();
if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,60}$/.test(id)) return;
if (!out.has(id)) out.set(id, new Set());
out.get(id).add(form);
};
for (const m of t.matchAll(/\{\s*id:\s*["']([^"']+)["']\s*,\s*label:\s*(?:"[^"\n]*"|'[^'\n]*')\s*,[^\n}]*\b(?:type|url)\s*:/g)) add(m[1], 'config entry');
for (const m of t.matchAll(/\b([A-Z][A-Z0-9_]*(?:LAYER_IDS?|LAYERS)[A-Z0-9_]*)\s*=\s*([^;]{1,600})/g)) {
const init = m[2];
const head = init.trimStart();
/* only literal initialisers declare: a string, an array, a Set or an object of literals */
if (!/^(['"`]|\[|new Set\(\s*\[|Object\.freeze\(\s*[\[{]|\{)/.test(head)) continue;
const obj = /^(?:Object\.freeze\(\s*)?\{([\s\S]*?)\}/.exec(head);
const vals = obj ? [...obj[1].matchAll(/:\s*(['"`])([^'"`\\\n]{1,80})\1/g)].map(x => x[2])
: /^['"`]/.test(head) ? [head.match(/^(['"`])([^'"`\\\n]{1,80})\1/)?.[2]].filter(Boolean)
: [...(head.match(/^[^\]]*\]/)?.[0] || '').matchAll(LIT)].map(x => x[2]);
for (const v of vals) add(/^l-/.test(v) ? v.slice(2) : v, 'layer constant ' + m[1]);
}
for (const m of t.matchAll(/data-layer-id\s*=\s*\\?["']([A-Za-z0-9_.-]+)\\?["']/g)) add(m[1], 'control attribute data-layer-id');
for (const m of t.matchAll(/(['"])l-([A-Za-z0-9_]+)\1/g)) add(m[2], "engine layer name 'l-<id>'");
return out;
}
/* The Grid Atlas v9 release config: its ukConfig entries' ids, in order. */
export function configLayerIds(html) {
return [...declaredLayerIds(html)].filter(([, f]) => f.has('config entry')).map(([id]) => id);
}
/* The canonical receiver link a node's MAP button may open, built only from
parameters the deep-link contract accepts. */
export function receiverLink(contract, receivers) {
const route = receivers?.canonical?.route || contract.CANONICAL_RECEIVER;
const params = Object.keys(contract.PARAMS);
const layerParam = params.find(p => /layer/i.test(p)) || null;
return {
href: route, params, layerParam, identity: contract.IDENTITY_PARAM,
agrees: route === contract.CANONICAL_RECEIVER,
why: layerParam ? `the contract accepts ${layerParam}`
: `the deep-link contract accepts ${params.join(', ')}; none is a layer id (technology is "${contract.PARAMS.technology?.note || 'a bucket'}"), and ${contract.IDENTITY_PARAM} is required, which no spider node carries, so the link opens the receiver with no parameters and the layer is ticked there by hand`
};
}
/* For a layer id the contract knows, the buckets that resolve to it. */
export function bucketsForLayer(contract, id) {
return contract.BUCKETS.filter(b => contract.layerIdForBucket(b) === id);
}GlobalGrid2050 — Atlas V9 Page
A web page using data from the GridAtlas repository. Published at https://globalgrid2050.com/202608300453-atlas-v9/.
renderglobalgrid2050 / 202608300453-atlas-v9/index.html · lines 1–32 of 32 · version 2026-08-30 04:53 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): 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
- Out: web page.
- Downstream impact
- It is itself an entry point, published at https://globalgrid2050.com/202608300453-atlas-v9/.
- What it achieves
- Grid Atlas V9 — canonical application.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · 202608300453-atlas-v9 · page
- Uses
- GridAtlas — Index Page (link)
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 202608300453-atlas-v9/index.html:1-32 · blob 9ff831aee0c4fac41734c9a19f440a5bf03ed45c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex">
<title>Grid Atlas V9 — canonical application</title>
<link rel="canonical" href="https://ventusltd.github.io/gridatlas/">
<meta http-equiv="refresh" content="0; url=https://ventusltd.github.io/gridatlas/">
<script>
(() => {
const target = new URL('https://ventusltd.github.io/gridatlas/');
target.search = window.location.search;
target.hash = window.location.hash;
window.location.replace(target.href);
})();
</script>
</head>
<body>
<main>
<h1>Grid Atlas V9 has moved</h1>
<p>This GlobalGrid2050 mirror is retired. <a id="canonical" href="https://ventusltd.github.io/gridatlas/">Open the canonical Grid Atlas V9 application.</a></p>
</main>
<script>
const link = document.getElementById('canonical');
const target = new URL(link.href);
target.search = window.location.search;
target.hash = window.location.hash;
link.href = target.href;
</script>
</body>
</html>Navigation Browser
A JavaScript module in the mobile map ui folder of GlobalGrid2050 that reads inputs for county and sort projects.
renderglobalgrid2050 / automation/mobile_map_ui/20261118-v942/navigation.browser.mjs · lines 1–43 of 43 · version 2026-11-18 · Entry point
- What it does
- It loads data. Uses libraries node:assert/strict, node:http, node:fs, node:module, node:path. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'navigation'): 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.
- Inputs & outputs
- In: form fields (user input).
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/mobile_map_ui/20261118-v942 · JavaScript module
- Uses
- Navigation (new URL import.meta.url), node:assert/strict, node:http, node:fs, node:module, node:path
- Used by
- run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/mobile_map_ui/20261118-v942/navigation.browser.mjs:1-43 · blob 0feb4ba56c20b5984938582248edaeaffcf6e530 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync,existsSync,writeFileSync} from 'node:fs';
import {createRequire} from 'node:module';
import {resolve} from 'node:path';
const moduleRoot=process.env.PLAYWRIGHT_MODULE_ROOT||'D:/githubfiles/.qa-tools/node';
const {chromium}=createRequire(resolve(moduleRoot,'package.json'))('playwright');
const source=readFileSync(new URL('./navigation.mjs',import.meta.url));
const fixture=`<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>a{display:inline-block;min-width:44px;min-height:44px}</style>
<div id="tech"><button aria-pressed="true" data-technology="all">All</button></div>
<div id="status"><button aria-pressed="true" data-official-status="All">All</button></div>
<input id="search" value="2470"><select id="county"><option>All</option></select><select id="sortProjects"><option>capacity_desc</option></select>
<a id="mapAtlasNav" href="/destination">MAP ATLAS</a>
<div class="tablewrap"><table><tbody id="tbody" data-total="7775"><tr><td><a class="atlaslink" target="_blank" rel="noopener" href="/destination?repd_ref=2470">MAP</a></td></tr></tbody></table></div>
<nav id="projectPager" data-page="1" data-pages="1"></nav><script type="module" src="/navigation.mjs"></script>`;
const server=createServer((req,res)=>{const u=new URL(req.url,'http://local');
if(u.pathname==='/navigation.mjs'){res.setHeader('content-type','text/javascript');res.end(source)}
else{res.setHeader('content-type','text/html');res.end(u.pathname==='/destination'?'<h1>Destination</h1>':fixture)}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
const browser=await chromium.launch();const results=[];
try{
for(const mobile of [true,false]){
const context=await browser.newContext({viewport:{width:mobile?393:1440,height:852},isMobile:mobile,hasTouch:mobile});
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base+'/source');const a=page.locator('a.atlaslink');
await page.waitForFunction(()=>document.querySelector('a.atlaslink')?.dataset.mapNavigation);
assert.equal(await a.getAttribute('target'),mobile?'_self':'_blank');
assert.equal(await page.locator('#mapAtlasNav').getAttribute('target'),mobile?'_self':null);
if(mobile){
await a.tap();await page.waitForURL('**/destination?repd_ref=2470');assert.equal(context.pages().length,1);
await page.goBack();await page.waitForFunction(()=>document.querySelector('a.atlaslink')?.dataset.mapNavigation==='current-tab');
assert.equal(new URL(page.url()).searchParams.get('q'),'2470');
// Search rerenders get the same target before a native keyboard activation.
await page.evaluate(()=>{const a=document.querySelector('a.atlaslink');a.replaceWith(a.cloneNode(true))});
await page.locator('a.atlaslink').focus();await page.keyboard.press('Enter');await page.waitForURL('**/destination?repd_ref=2470');
}else{
const opened=context.waitForEvent('page');await a.click();const popup=await opened;await popup.waitForLoadState();assert.equal(new URL(popup.url()).searchParams.get('repd_ref'),'2470');assert.equal(new URL(page.url()).pathname,'/source');await popup.close();
}
assert.deepEqual(errors,[]);results.push({mobile,pass:true});await context.close();
}
}finally{await browser.close();await new Promise(r=>server.close(r))}
if(process.env.MOBILE_MAP_REPORT)writeFileSync(process.env.MOBILE_MAP_REPORT,JSON.stringify({scope:'sender mechanics on local real HTTP pages; not live receiver acceptance',results},null,2)+'\n');
console.log(JSON.stringify(results));Navigation
A JavaScript module in the mobile map ui folder of GlobalGrid2050. It is built from the decorate step (`decorate`), the remember step (`remember`) and the restore step (`restore`).
interactionglobalgrid2050 / automation/mobile_map_ui/20261118-v942/navigation.mjs · lines 1–54 of 54 · version 2026-11-18 · Entry point · pattern decorate (shared by 2 files)
- What it does
- Defines decorate, remember, restore. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'navigation'): 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.
- Downstream impact
- Used directly by 2 files: Navigation Browser (globalgrid2050); GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 5 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents).
- What it achieves
- Native touch navigation: do not open a background tab or wait on a fetch. It responds to click and change events.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/. Also imported by Navigation Browser.
- Application
- globalgrid2050 · automation/mobile_map_ui/20261118-v942 · JavaScript module
- Uses
- none found
- Used by
- referenced by Navigation Browser (new URL import.meta.url), loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src)
- Produces
- decorate, remember, restore
- Defines here
- decorate, remember, restore
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/mobile_map_ui/20261118-v942/navigation.mjs:1-54 · blob bfa8e8f5fda44c22738a719d6fa517b0a2fd5993 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
/* Native touch navigation: do not open a background tab or wait on a fetch. */
const touch=matchMedia('(pointer: coarse)');
const selector='a.atlaslink,#mapAtlasNav';
const key='pipelineMapReturn';
const originalTargets=new WeakMap();
function decorate(){
for(const a of document.querySelectorAll(selector)){
if(!originalTargets.has(a))originalTargets.set(a,a.getAttribute('target'));
const target=touch.matches?'_self':originalTargets.get(a);
if(target===null)a.removeAttribute('target');else a.target=target;
a.dataset.mapNavigation=target==='_blank'?'new-tab':'current-tab';
a.setAttribute('aria-description',target==='_blank'?'Opens the grid map in a new tab.':'Opens the grid map in this tab. Use Back to return to these results.');
}
}
function remember(){
const url=new URL(location.href),value=id=>document.getElementById(id)?.value;
const fields={technology:document.querySelector('#tech [aria-pressed="true"]')?.dataset.technology,
status:document.querySelector('#status [aria-pressed="true"]')?.dataset.officialStatus,
county:value('county'),q:value('search'),sort:value('sortProjects')};
for(const [param,id] of [['submitted_year','submittedYear'],['updated_year','updatedYear'],['operational_year','operationalYear']])
fields[param]=document.querySelector('[data-year-filter="'+id+'"]')?.value;
for(const [param,v]of Object.entries(fields))if(v!==undefined)url.searchParams.set(param,v);
const wrapper=document.querySelector('#tbody')?.closest('.tablewrap');
try{history.replaceState({...history.state,[key]:{path:location.pathname,page:Number(document.getElementById('projectPager')?.dataset.page)||1,x:scrollX,y:scrollY,left:wrapper?.scrollLeft||0}},'',url)}catch{/* Navigation stays native if history is unavailable. */}
}
document.addEventListener('click',event=>{
const link=event.target.closest?.(selector);
if(!link)return;
decorate();
if(touch.matches&&!event.metaKey&&!event.ctrlKey&&!event.shiftKey&&!event.altKey)remember();
},true);
touch.addEventListener('change',decorate);
new MutationObserver(decorate).observe(document.getElementById('tbody'),{childList:true,subtree:true});
decorate();
// BFCache preserves the actual DOM. A full Back reload uses the URL filters and
// the saved page/scroll instead; no filters or data are synthesized here.
const saved=history.state?.[key];
if(saved?.path===location.pathname){
let attempts=0;
const restore=()=>{
const body=document.getElementById('tbody'),pager=document.getElementById('projectPager');
if(Number(body?.dataset.total)>0&&pager){
const target=Math.min(Math.max(1,saved.page),Number(pager.dataset.pages)||1);
while(Number(pager.dataset.page)<target){
const next=pager.querySelector('[data-page-step="1"]');
if(!next||next.disabled)break;
next.click();
}
const wrapper=body.closest('.tablewrap');if(wrapper)wrapper.scrollLeft=saved.left;
scrollTo(saved.x,saved.y);
}else if(++attempts<300)setTimeout(restore,100);
};
restore();
}GridAtlas Resolve
A Python command-line tool in the pipeline release folder of GlobalGrid2050 that fetches the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/gridatlas_resolve.py · lines 1–114 of 114 · Entry point
- What it does
- It fetches the REPD register. Defines main. Uses libraries hashlib, json, sys, urllib.request, collections. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): 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: the REPD register.
- Inputs & outputs
- In: JSON file build_manifest.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Verify (globalgrid2050); GlobalGrid2050 Verify Pipeline Versions Workflow (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050).
- What it achieves
- Which Pipeline News MAP links does a GridAtlas register resolve by REPD Ref ID?
- Why it matters
- Run by Verify and GlobalGrid2050 Verify Pipeline Versions Workflow.
- Application
- globalgrid2050 · automation/pipeline_release · Python CLI
- Uses
- hashlib, json, sys, urllib.request, collections, datetime, pathlib
- Used by
- run by Verify (script call), run by GlobalGrid2050 Verify Pipeline Versions Workflow (workflow run)
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/gridatlas_resolve.py:1-114 · blob 96efc38a4eaeb3cc017689fbf8738ff70ba35eec · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Which Pipeline News MAP links does a GridAtlas register resolve by REPD Ref ID?
gridatlas_resolve.py <version folder> <register> [--composition <current.json>] [--summary] [--write <state.json>] [--require-active]
<register> is a GridAtlas browser registry (data/repd_browser_registry_<generation>.json, schema
gridatlas.browser-registry.v1), as a file path or an https URL. The MAP link itself is not
touched or tested here; this only answers, for every row of the version, whether GridAtlas
holds a record with the same REPD Ref ID, which is what lets it open the project's identity
card on arrival.
GridAtlas keeps the active register only: Operational, Under Construction, Awaiting
Construction and Application Submitted. Rows with any other REPD status are not expected to
resolve; on those the map still opens on the point the link carries. The rows that matter
are the ACTIVE ones GridAtlas does not hold yet: they are listed in full.
--composition names GridAtlas's composition manifest (atlas/current.json, path or https URL);
the generation of its project-search cartridge is recorded so a page can tell whether the
measurement still applies to what GridAtlas serves.
--require-active exits 1 unless every active row either resolves or lies outside the area
GridAtlas compiles (the re-run check once a new GridAtlas register is live). Standard library only.
"""
import hashlib
import json
import sys
import urllib.request
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
# The bounds GridAtlas's compiler keeps a point within (compiler/<generation>-compile-atlas-v9.py):
# -9 < longitude < 2.5 and 49 < latitude < 61. An active row outside them is explained, not a fault.
BOUNDS = {"lon": (-9.0, 2.5), "lat": (49.0, 61.0)}
ACTIVE = {"operational", "under construction", "awaiting construction", "application submitted"}
def main():
args = sys.argv[1:]
folder, source = Path(args[0]), args[1]
read = lambda s: urllib.request.urlopen(s, timeout=60).read() if s.startswith("https://") else Path(s).read_bytes()
raw = read(source)
search = None
if "--composition" in args:
comp = json.loads(read(args[args.index("--composition") + 1]))
cart = next(c for c in comp["cartridges"] if c["id"] == "uk-gazetteer-flyto")
search = {"cartridge": cart["id"], "generation": str(cart["generation"]), "composition_generation": str(comp.get("generation"))}
reg = json.loads(raw)
assert reg.get("schema") == "gridatlas.browser-registry.v1", reg.get("schema")
held = {str(r["repd_ref"]): r for r in reg["records"]}
rows = []
manifest = json.loads((folder / "data/v9.1/build_manifest.json").read_text())
for part in manifest["project_partitions"]:
rows += json.loads((folder / part["path"]).read_text())["projects"]
pending, stale, counts = [], [], Counter()
for row in rows:
ref, active = str(row["repd_ref"]), row["status"].lower() in ACTIVE
rec = held.get(ref)
if rec and active:
counts["active_resolved"] += 1
elif rec:
counts["not_active_but_still_held"] += 1
stale.append({"repd_ref": ref, "name": row["name"], "repd_status": row["status"], "gridatlas_status": rec.get("status")})
elif active:
counts["active_not_resolved"] += 1
lon, lat = row.get("longitude"), row.get("latitude")
outside = row.get("geometry_status") == "valid" and not (BOUNDS["lon"][0] < lon < BOUNDS["lon"][1] and BOUNDS["lat"][0] < lat < BOUNDS["lat"][1])
reason = ("REPD point %.4f N, %.4f E lies outside the area GridAtlas compiles (longitude -9 to 2.5, latitude 49 to 61)" % (lat, lon)) if outside else "not explained by status or position"
counts["active_outside_bounds" if outside else "active_unexplained"] += 1
pending.append({"repd_ref": ref, "name": row["name"], "technology": row["technology"], "repd_status": row["status"],
"capacity_mw": row.get("capacity_mw"), "has_map_point": row.get("geometry_status") == "valid", "reason": reason,
"page_note": "GRIDATLAS: MAP OPENS ON THE PROJECT POINT · NO PROJECT CARD THERE: " + ("POINT IS EAST OF THE AREA GRIDATLAS COMPILES" if outside and lon >= BOUNDS["lon"][1] else "POINT IS OUTSIDE THE AREA GRIDATLAS COMPILES" if outside else "RECORD NOT YET IN GRIDATLAS")})
else:
counts["not_active_not_expected"] += 1
out = {
"schema": "globalgrid2050.pipeline-news.gridatlas-map-link-state.v1",
"measured_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"pipeline_news_version": folder.name,
"gridatlas_register": {"generation": reg.get("generation"), "dataset": (reg.get("source") or {}).get("dataset"),
"records": len(reg["records"]), "sha256": hashlib.sha256(raw).hexdigest(),
"file": "data/repd_browser_registry_%s.json" % reg.get("generation")},
"gridatlas_project_search": search,
"method": "Exact REPD Ref ID match between every Pipeline News row and the GridAtlas browser registry. Offline, from the files; the live site was not opened.",
"rows": len(rows),
"active_rows": counts["active_resolved"] + counts["active_not_resolved"],
"active_resolved": counts["active_resolved"],
"active_not_resolved": counts["active_not_resolved"],
"active_not_resolved_outside_gridatlas_area": counts["active_outside_bounds"],
"active_not_resolved_unexplained": counts["active_unexplained"],
"rows_resolved_total": counts["active_resolved"] + counts["not_active_but_still_held"],
"rows_without_map_point": sum(1 for r in rows if r.get("geometry_status") != "valid"),
"not_active_not_expected": counts["not_active_not_expected"],
"not_active_but_still_held": counts["not_active_but_still_held"],
"meaning": {
"active_not_resolved": "REPD status is Operational, Under Construction, Awaiting Construction or Application Submitted, and GridAtlas holds no record with this REPD Ref ID. The MAP link still opens the map on the project's point and measures from it; the project's identity card does not open. Each row carries its reason.",
"not_active_not_expected": "REPD status is outside the four active statuses. GridAtlas keeps the active register only, so no identity card is expected; the map still opens on the link's point.",
"not_active_but_still_held": "GridAtlas still holds an earlier record for a project whose REPD status is no longer active; its card shows the earlier status.",
},
"pass": counts["active_unexplained"] == 0,
"active_not_resolved_refs": sorted(pending, key=lambda r: int(r["repd_ref"])),
"not_active_but_still_held_refs": sorted(stale, key=lambda r: int(r["repd_ref"])),
}
if "--write" in args:
Path(args[args.index("--write") + 1]).write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n")
if "--summary" in args:
out = {k: v for k, v in out.items() if not k.endswith("_refs") and k != "meaning"}
print(json.dumps(out, indent=1, ensure_ascii=False))
if "--require-active" in args and not out["pass"]:
sys.exit(1)
if __name__ == "__main__":
main()Bake
A Python module in the LiDAR onsite folder of GlobalGrid2050 that reads LiDAR terrain.
storageglobalgrid2050 / energy-transition-simulator/202609280014/mod/lidar-onsite/bake.py · lines 1–47 of 47 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review)
- What it does
- It loads LiDAR terrain. Uses libraries sys, json, base64, os, numpy. Side effects: 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: JSON file index.json; command-line arguments. Out: JSON file.
- What it achieves
- Bake cached EA LiDAR 1 m DTM around a point into a small file the LiDAR-onsite module draws.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/lidar-onsite · Python module
- Uses
- sys, json, base64, os, numpy, mirror_store
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/lidar-onsite/bake.py:1-47 · blob 7fd7b876e7ec28f3474bf628919fe10d68ec3607 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
"""Bake cached EA LiDAR 1 m DTM around a point into a small file the lidar-onsite module draws.
Reads ONLY the local mirror E:/lidar-mirror (built from the local caches E:/lidar-cache, E:/world-cache and the
bulk zips; no network, never the EA WCS). Writes mod/lidar-onsite/<name>.json: every 1 km tile within `search`
metres that holds data, cropped to its data, sampled every `step` metres as int16 centimetres (-32768 = no data).
Usage: python bake.py <name> <E> <N> [search_m=3000] [step_m=5]
"""
import sys, json, base64, os
import numpy as np
sys.path.insert(0, '(local path)')
import mirror_store as ms
ROOT = 'E:/lidar-mirror'
name, E, N = sys.argv[1], float(sys.argv[2]), float(sys.argv[3])
search = float(sys.argv[4]) if len(sys.argv) > 4 else 3000.0
step = int(sys.argv[5]) if len(sys.argv) > 5 else 5
patches = []
for te in range(int((E - search) // 1000) * 1000, int(E + search) + 1, 1000):
for tn in range(int((N - search) // 1000) * 1000, int(N + search) + 1, 1000):
tid = ms.tile_id(te, tn)
meta, h = ms.read_tile(ROOT, tid, 'dtm')
if meta is None:
continue
h = np.asarray(h) # rows south->north, cell SW corner (e0+c, n0+r)
ok = np.isfinite(h)
if not ok.any():
continue
rows, cols = np.where(ok)
r0, r1 = rows.min() // step * step, rows.max() // step * step
c0, c1 = cols.min() // step * step, cols.max() // step * step
sub = h[r0:r1 + 1:step, c0:c1 + 1:step] # sample the cell at every step-th SW corner
q = np.where(np.isfinite(sub), np.round(sub * 100), -32768).astype('<i2')
patches.append(dict(tile=tid, e0=int(meta['e0'] + c0), n0=int(meta['n0'] + r0), step=step,
w=int(sub.shape[1]), h=int(sub.shape[0]), valid=int(ok.sum()),
min=float(np.nanmin(sub)), max=float(np.nanmax(sub)),
source=meta['source'].split(':')[0], survey_year=meta.get('survey_year'),
cm=base64.b64encode(q.tobytes()).decode()))
out = dict(name=name, E=E, N=N, search=search, step=step, product='dtm',
credit='Contains Environment Agency LiDAR 1 m DTM, OGL v3 (local cache)', patches=patches)
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, name + '.json'), 'w') as f:
json.dump(out, f)
idx = os.path.join(here, 'index.json')
lst = json.load(open(idx)) if os.path.exists(idx) else []
lst = [a for a in lst if a['name'] != name] + [dict(name=name, E=E, N=N, search=search)]
json.dump(lst, open(idx, 'w'))
print(name, len(patches), 'patches', [(p['tile'], p['w'], p['h'], p['valid']) for p in patches])