In this section
- Map Navigation V970 test · globalgrid2050 / uk_renewables_pipeline/202611221930/tests/map-navigation-v970.mjs lines 1–86
- Atlas Receiver V9 7 ingest · globalgrid2050 / uk_renewables_pipeline/v9.7/scripts/core/atlas-receiver-v9-7.js lines 1–168
- Build Federation Systems Map storage · globalgrid2050-homepage / scripts/build_federation_systems_map.py lines 1–176
- Release GridAtlas automation · globalgrid2050-homepage / scripts/release_gridatlas.py lines 1–153
- Test Release GridAtlas test · globalgrid2050-homepage / tests/test_release_gridatlas.py lines 1–42
- GridAtlas GPU storage · graphics-engines-open-source / gridatlas_gpu.py lines 1–42
Map Navigation V970
A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register and uses data from the GridAtlas repository.
testglobalgrid2050 / uk_renewables_pipeline/202611221930/tests/map-navigation-v970.mjs · lines 1–86 of 86 · version 2026-11-22 19:30 · Entry point
- What it does
- It tests the REPD register. Uses libraries node:assert/strict, playwright. 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. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 2 files: GlobalGrid2050 Pn V970 Map Parity Workflow (globalgrid2050); GlobalGrid2050 Pn V971 Retire Legacy Maximise Workflow (globalgrid2050).
- What it achieves
- V9.70 regression: prove real normal versus expanded MAP navigation, not click events.
- Why it matters
- Run by GlobalGrid2050 Pn V970 Map Parity Workflow and GlobalGrid2050 Pn V971 Retire Legacy Maximise Workflow.
- Application
- globalgrid2050 · uk_renewables_pipeline/202611221930/tests · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), node:assert/strict, playwright
- Used by
- run by GlobalGrid2050 Pn V970 Map Parity Workflow (workflow run), run by GlobalGrid2050 Pn V971 Retire Legacy Maximise 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 uk_renewables_pipeline/202611221930/tests/map-navigation-v970.mjs:1-86 · blob 1806f8bd658c0774fed200a5e0721b3034af386a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: IPP_developer, EPC_contractor, landowner_planner · canonical: production_core
// V9.70 regression: prove real normal versus expanded MAP navigation, not click events.
import assert from 'node:assert/strict';
import {chromium,webkit} from 'playwright';
const app='http://127.0.0.1:8765/uk_renewables_pipeline/202611221930/';
const atlas='https://ventusltd.github.io/gridatlas/atlas/';
for(const [engineName,engine] of [['Chromium',chromium],['WebKit',webkit]]){
const browser=await engine.launch({headless:true});
try{
for(const cfg of [
{name:'portrait-touch',width:393,height:852,touch:true},
{name:'landscape-touch',width:852,height:393,touch:true},
{name:'desktop',width:1280,height:800,touch:false}
]){
const ctx=await browser.newContext({viewport:{width:cfg.width,height:cfg.height},
isMobile:cfg.touch,hasTouch:cfg.touch,reducedMotion:'reduce'});
const page=await ctx.newPage();
const errors=[];page.on('pageerror',e=>errors.push(e.message));
await ctx.route('https://raw.githubusercontent.com/**',r=>r.abort());
await ctx.route('https://ventusltd.github.io/gridatlas/atlas/**',r=>
r.fulfill({status:200,contentType:'text/html',
body:'<!doctype html><title>GridAtlas test receiver</title><h1>GridAtlas test receiver</h1>'}));
const nativeSelector='#tbody tr[id^="repd-"] td:last-child .pn-journey-action.atlaslink[href]';
const expandedSelector='#pnExpandedHost #tbody tr[id^="repd-"] .pn-expanded-map-cell a.pn-expanded-map-launch';
try{
await page.goto(app,{waitUntil:'domcontentloaded',timeout:90000});
await page.waitForFunction(()=>document.querySelectorAll('#tbody tr[id^="repd-"]').length===50
&&document.querySelector('#tbody .pn-journey-action.atlaslink[href]'),{timeout:90000});
assert.equal(await page.locator('#pnRepdWideToggle, #pnRepdWidePrompt').count(),0,'No legacy control');
assert.equal(await page.locator('#pnLiquidLaunch').count(),1,'Modern launcher remains');
const native=page.locator(nativeSelector).first();
const href=await native.getAttribute('href');
assert.ok(href.startsWith(atlas),'native original must link GridAtlas');
const normalTarget=await native.getAttribute('target');
assert.equal(normalTarget,cfg.touch?'_self':'_blank','native target policy');
if(cfg.touch){
await Promise.all([page.waitForURL(u=>u.href===href,{timeout:15000}),native.click()]);
assert.equal(page.url(),href,'normal MAP must navigate in same tab');
await page.goBack({waitUntil:'domcontentloaded'});
await page.waitForFunction(()=>document.querySelectorAll('#tbody tr[id^="repd-"]').length===50,{timeout:90000});
}else{
const popupPromise=page.waitForEvent('popup',{timeout:15000});
await native.click();
const popup=await popupPromise;
await popup.waitForURL(href,{timeout:15000});
assert.equal(popup.url(),href,'normal desktop MAP opens real destination');
await popup.close();
}
await page.locator('#pnLiquidLaunch').click();
await page.waitForFunction(()=>document.querySelectorAll('#tbody tr[id^="repd-"]').length===100
&&document.querySelector('#tbody .pn-expanded-map-launch'),{timeout:20000});
const expanded=page.locator(expandedSelector).first();
const currentNative=page.locator(nativeSelector).first();
assert.equal(await expanded.getAttribute('href'),await currentNative.getAttribute('href'),
'expanded must inherit live, enriched MAP target');
assert.equal(await expanded.getAttribute('target'),await currentNative.getAttribute('target'),
'expanded and normal target policy must match');
// Simulate an asynchronously updated native URL after expansion. This was
// missed by V9.69's click-only acceptance and permanently stale mirror.
const changed=await page.evaluate(()=>{
const row=document.querySelector('#tbody tr[id^="repd-"]');
const source=row?.querySelector('td:last-child .pn-journey-action.atlaslink[href]');
if(!source)throw Error('Native source missing');
const u=new URL(source.href);u.searchParams.set('v970_parity','source-updated');
source.href=u.href;return u.href;
});
if(cfg.touch){
await Promise.all([page.waitForURL(u=>u.href===changed,{timeout:15000}),expanded.click()]);
assert.equal(page.url(),changed,'expanded touch MAP must navigate to newest native URL');
}else{
const popupPromise=page.waitForEvent('popup',{timeout:15000});
await expanded.click();
const popup=await popupPromise;
await popup.waitForURL(changed,{timeout:15000});
assert.equal(popup.url(),changed,'expanded desktop MAP must open newest native URL');
await popup.close();
// Expanded mode survives actual desktop MAP click.
assert.equal(await page.locator('#pnExpandedHost').isVisible(),true);
await page.locator('#pnExpandedClose').click();
assert.equal(await page.locator('#repdScroll thead th').count(),13);
}
assert.deepEqual(errors,[],'No browser errors');
console.log('PASS V9.70 native MAP parity',engineName,cfg.name);
}finally{await ctx.close()}
}
}finally{await browser.close()}
}Atlas Receiver V9 7
A JavaScript module in the core folder of GlobalGrid2050 that fetches receivers and the Renewable Energy Planning Database (REPD) register from the ventus-grid-engine repository.
ingestglobalgrid2050 / uk_renewables_pipeline/v9.7/scripts/core/atlas-receiver-v9-7.js · lines 1–168 of 168 · Not reached from any entry point (candidate for review) · pattern atlasCentresOnRepdPoint (shared by 3 files)
- What it does
- It fetches receivers and the REPD register. Defines 9 functions or classes, including stripTrailingSlash, isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7. Side effects: makes network requests.
- 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. Domain terms in the code: the REPD register, 132kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; JSON file receivers.json. Voltage levels named: 132kV.
- Downstream impact
- Used directly by 2 files: Projects V9 5 1 (globalgrid2050); Check V9 5 1 (globalgrid2050).
- What it achieves
- It loads atlas receiver v9 (`loadAtlasReceiverV9_7`) and builds atlas deep link v9 (`buildAtlasDeepLinkV9_7`). On the MAP button in this app was measured pointing at the V8 overlay the engine now publishes as retired. Its code works with 132 kV and 500 MW.
- Why it matters
- Imported by Projects V9 5 1. Checked by Check V9 5 1.
- Application
- globalgrid2050 · uk_renewables_pipeline/v9.7/scripts/core · JavaScript module
- Uses
- none found
- Used by
- imported by Projects V9 5 1 (import), run by Check V9 5 1 (script call)
- Produces
- isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7, loadAtlasReceiverV9_7, atlasCentresOnRepdPointV9_7, buildAtlasDeepLinkV9_7, atlasUnavailableReasonV9_7
- Defines here
- stripTrailingSlash, isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7, loadAtlasReceiverV9_7, atlasCentresOnRepdPointV9_7, buildAtlasDeepLinkV9_7, atlasUnavailableReasonV9_7
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/v9.7/scripts/core/atlas-receiver-v9-7.js:1-168 · blob a356ce6c4ddc6be38eb8cc5120f5849f47ca1d00 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* ── WHICH RECEIVER A MAP LINK IS BUILT AGAINST ──────────────────────────────
*
* On 2026-09-05 the MAP button in this app was measured pointing at the V8
* overlay the engine now publishes as retired — a page that still serves, so
* nothing 404'd and no link checker ever went red, but which carries zero
* engine cartridges and no current.json. Measured the same day: that shell has
* 0 cartridge references and 0 current.json references; the canonical shell has
* 20 and 3. An arrival there is silently inert. Vikram hit it on Longfield
* (REPD 8162) and reported "grid engine didnt compute or fire via map button".
* It was never going to.
*
* Driven live for this change, same project, same parameters:
*
* retired receiver zero __GRIDATLAS_* globals, no module list, no nearest()
* function, and the page never even names Longfield
* canonical receiver 14 engine modules including networkTopology,
* electricalDistance, ratingEnvelope and corridorEstimate;
* the arrival popup reads "Longfield solar 500 MW ...
* CM3 3AS · Essex REPD 8162 · awaiting construction", and
* the engine's own nearest() answers BRAINTREE at 9.44 km,
* 400/132 kV, NGET, 4 transformers, 4 circuits
*
* WHY THIS FILE HOLDS NO URL.
* The route was hard-coded in the consumer, in seven files side by side, and
* the engine published nothing for any of them to disagree with. It now does:
* ventus-grid-engine/deeplink/receivers.json names the canonical route, the
* retired ones, and why. This module reads that file. It does not restate the
* answer, because a second copy is the fault being removed rather than a
* safeguard against it — the whole defect was seven copies of a route that had
* quietly stopped being true.
*
* WHAT HAPPENS WHEN IT CANNOT BE READ.
* No fallback to a retired route, ever: that is what shipped a dead button for
* weeks. The link is empty, the cell says which receiver could not be
* established and why, and the reader is told rather than given a link that
* looks right and computes nothing. Silence is the failure mode this whole
* change exists to end.
*
* ORDER MATTERS AND IS ASSERTED. Callers are synchronous — a table row renders
* one link at a time — so loadAtlasReceiverV9_7() must be awaited before the
* first render. loadProjectsV9_5_1() awaits it beside the project payload.
* Before that resolves, buildAtlasDeepLinkV9_7() returns "" and
* atlasReceiverFailureV9_7() says so, rather than guessing.
*/
const RECEIVERS_URL = "https://ventusltd.github.io/ventus-grid-engine/deeplink/receivers.json";
const RECEIVERS_SCHEMA = "ventus.grid-engine.deeplink-receivers.v1";
/* The parameters the deep-link contract names, in its own order. `project` and
* `capacity_mw` are deliberately NOT sent: the contract's PARAMS does not carry
* them, and the canonical receiver resolves the project's identity, name,
* capacity, postcode and status from the REPD reference on its own — verified
* live on REPD 8162 and on REPD 13429, which has no REPD coordinate at all. */
const CONTRACT_PARAMS = Object.freeze(["repd_ref", "technology", "latitude", "longitude", "zoom"]);
let canonicalRoute = "";
let retiredRoutes = [];
let failureReason = "the deep-link contract has not been read yet";
let pending = null;
const stripTrailingSlash = (route) => String(route || "").replace(/\/+$/u, "");
export function isRetiredReceiverV9_7(route) {
return retiredRoutes.includes(stripTrailingSlash(route));
}
export function atlasReceiverV9_7() {
return canonicalRoute;
}
export function atlasReceiverFailureV9_7() {
return canonicalRoute ? "" : failureReason;
}
/* Exposed so a test can drive every branch of this module without a network —
* a check that can only run online is a check that quietly stops running. It
* takes the contract DOCUMENT, never a bare route, so there is still no way to
* name a receiver by hand and have this module believe it. */
export function primeAtlasReceiverV9_7(document_) {
canonicalRoute = "";
retiredRoutes = [];
failureReason = "";
pending = null;
if (!document_ || document_.schema !== RECEIVERS_SCHEMA) {
failureReason = `deep-link contract schema is ${document_ && document_.schema}, expected ${RECEIVERS_SCHEMA}`;
return "";
}
const route = document_.canonical && document_.canonical.route;
if (!route) {
failureReason = "the deep-link contract names no canonical receiver";
return "";
}
if (document_.canonical.carries_engine !== true) {
failureReason = "the deep-link contract's canonical receiver does not claim to carry the engine";
return "";
}
retiredRoutes = (Array.isArray(document_.retired) ? document_.retired : [])
.map((entry) => stripTrailingSlash(entry && entry.route))
.filter(Boolean);
if (isRetiredReceiverV9_7(route)) {
// The contract contradicting itself must fail loudly, not resolve itself.
retiredRoutes = [];
failureReason = "the deep-link contract names its own canonical receiver as retired";
return "";
}
canonicalRoute = route;
return canonicalRoute;
}
export async function loadAtlasReceiverV9_7() {
if (canonicalRoute) return canonicalRoute;
if (!pending) {
pending = (async () => {
try {
const response = await fetch(RECEIVERS_URL, { mode: "cors", cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return primeAtlasReceiverV9_7(await response.json());
} catch (error) {
failureReason = `the deep-link contract at ${RECEIVERS_URL} could not be read (${error.message || error})`;
canonicalRoute = "";
pending = null;
return "";
}
})();
}
return pending;
}
/* True when this record carries a REPD coordinate the map can centre on. The
* 28 records that do not are still linkable: the receiver resolves them from
* the REPD reference and centres on its own geometry, which was measured on
* REPD 13429 (Ossian) — it arrives and names the project. They are labelled
* rather than denied a button, because a button that silently does nothing is
* exactly what hid this defect. */
export function atlasCentresOnRepdPointV9_7(project) {
return Boolean(project) && project.geometry_status === "valid";
}
export function buildAtlasDeepLinkV9_7(project) {
if (!canonicalRoute) return "";
if (!project || project.repd_ref === undefined || project.repd_ref === null || project.repd_ref === "") return "";
const values = {
repd_ref: project.repd_ref,
technology: project.technology,
};
if (atlasCentresOnRepdPointV9_7(project)) {
values.latitude = project.latitude;
values.longitude = project.longitude;
values.zoom = "12";
}
const url = new URL(canonicalRoute);
for (const key of CONTRACT_PARAMS) {
const value = values[key];
if (value === undefined || value === null || value === "") continue;
url.searchParams.set(key, String(value));
}
return url.href;
}
/* What the cell says when there is no link. One sentence, in the row, because
* a title attribute is unreachable on a phone and unreachable is how this hid. */
export function atlasUnavailableReasonV9_7(project) {
if (!canonicalRoute) return `MAP unavailable: ${atlasReceiverFailureV9_7()}`;
if (!project || project.repd_ref === undefined || project.repd_ref === null || project.repd_ref === "") {
return "MAP unavailable: this record carries no REPD reference to resolve";
}
return "";
}Build Federation Systems Map
A Python command-line tool in the scripts folder of GlobalGrid2050 Homepage that reads repo registry and repo edges. It verifies outputs (`verify_outputs`) and writes reports (`write_reports`).
storageglobalgrid2050-homepage / scripts/build_federation_systems_map.py · lines 1–176 of 176 · Entry point · pattern verify_outputs (shared by 2 files)
- What it does
- It loads repo registry and repo edges. Defines 6 functions or classes, including utcnow, sql_path, build_map, verify_outputs, write_reports. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- 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: CSV file repo_registry.csv; CSV file repo_edges.csv; Parquet file nodes.parquet; Parquet file edges.parquet; DuckDB queries; command-line arguments. Out: JSON file FEDERATION_SYSTEMS_MAP_LATEST.json.
- Downstream impact
- Used directly by 1 file: Gridbot Federation Systems Map Workflow (globalgrid2050-homepage).
- What it achieves
- Its name says it builds federation systems map. Defines `utcnow`, `sql_path`, `build_map` and 2 more. It accepts `--registry` and `--edges`.
- Why it matters
- Run by Gridbot Federation Systems Map Workflow.
- Application
- globalgrid2050-homepage · scripts · Python CLI
- Uses
- __future__, argparse, datetime, json, pathlib, duckdb
- Used by
- run by Gridbot Federation Systems Map Workflow (workflow run)
- Produces
- utcnow, sql_path, build_map, verify_outputs, write_reports, main
- Defines here
- utcnow, sql_path, build_map, verify_outputs, write_reports, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 scripts/build_federation_systems_map.py:1-176 · blob 1ce94dd5ed36c99eebf163ab29ae8ea483f2bbb1 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime as dt
import json
from pathlib import Path
import duckdb
ROOT = Path(__file__).resolve().parents[1]
REGISTRY = ROOT / "data/federation/repo_registry.csv"
EDGES = ROOT / "data/federation/repo_edges.csv"
OUT = ROOT / "data/federation/system_map"
REPORTS = ROOT / "reports"
JSON_REPORTS = REPORTS / "json"
METHOD_VERSION = "federation_systems_map_v1_duckdb_parquet"
def utcnow() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def sql_path(path: Path) -> str:
return str(path).replace("'", "''")
def build_map(registry: Path, edges: Path) -> dict[str, object]:
if not registry.exists():
raise FileNotFoundError(registry)
if not edges.exists():
raise FileNotFoundError(edges)
OUT.mkdir(parents=True, exist_ok=True)
con = duckdb.connect()
registry_sql = sql_path(registry)
edges_sql = sql_path(edges)
nodes_parquet = sql_path(OUT / "nodes.parquet")
edges_parquet = sql_path(OUT / "edges.parquet")
con.execute(f"""
COPY (
SELECT
repo_full_name AS node_id,
repo_full_name,
repo_name,
repo_type,
domain,
status,
source_of_truth,
grain,
key_fields,
owns_data,
serves_pages,
notes,
'{METHOD_VERSION}' AS methodVersion,
'{utcnow()}' AS generatedUTC
FROM read_csv_auto('{registry_sql}', all_varchar=true)
) TO '{nodes_parquet}' (FORMAT parquet, COMPRESSION zstd)
""")
con.execute(f"""
COPY (
SELECT
from_repo || '::' || edge_type || '::' || to_repo AS edge_id,
from_repo,
to_repo,
edge_type,
cardinality,
data_product,
status,
notes,
'{METHOD_VERSION}' AS methodVersion,
'{utcnow()}' AS generatedUTC
FROM read_csv_auto('{edges_sql}', all_varchar=true)
) TO '{edges_parquet}' (FORMAT parquet, COMPRESSION zstd)
""")
return verify_outputs()
def verify_outputs() -> dict[str, object]:
con = duckdb.connect()
nodes = sql_path(OUT / "nodes.parquet")
edges = sql_path(OUT / "edges.parquet")
node_rows, node_keys = con.execute(f"SELECT count(*), count(DISTINCT node_id) FROM read_parquet('{nodes}')").fetchone()
edge_rows, edge_keys = con.execute(f"SELECT count(*), count(DISTINCT edge_id) FROM read_parquet('{edges}')").fetchone()
node_nulls = con.execute(f"SELECT count(*) FROM read_parquet('{nodes}') WHERE node_id IS NULL OR node_id = ''").fetchone()[0]
edge_nulls = con.execute(f"SELECT count(*) FROM read_parquet('{edges}') WHERE edge_id IS NULL OR edge_id = ''").fetchone()[0]
missing_node_edges = con.execute(f"""
WITH n AS (SELECT node_id FROM read_parquet('{nodes}')),
e AS (SELECT from_repo AS node_id FROM read_parquet('{edges}') UNION ALL SELECT to_repo AS node_id FROM read_parquet('{edges}'))
SELECT count(DISTINCT e.node_id)
FROM e LEFT JOIN n USING (node_id)
WHERE n.node_id IS NULL
""").fetchone()[0]
duplicate_nodes = int(node_rows - node_keys)
duplicate_edges = int(edge_rows - edge_keys)
if node_nulls:
raise RuntimeError(f"node null keys found: {node_nulls}")
if edge_nulls:
raise RuntimeError(f"edge null keys found: {edge_nulls}")
if duplicate_nodes:
raise RuntimeError(f"duplicate node keys found: {duplicate_nodes}")
if duplicate_edges:
raise RuntimeError(f"duplicate edge keys found: {duplicate_edges}")
return {
"nodeRows": int(node_rows),
"nodeDistinctKeys": int(node_keys),
"edgeRows": int(edge_rows),
"edgeDistinctKeys": int(edge_keys),
"nodeNullKeys": int(node_nulls),
"edgeNullKeys": int(edge_nulls),
"duplicateNodeKeys": duplicate_nodes,
"duplicateEdgeKeys": duplicate_edges,
"edgeEndpointNodesMissingFromRegistry": int(missing_node_edges),
}
def write_reports(report: dict[str, object]) -> None:
REPORTS.mkdir(exist_ok=True)
JSON_REPORTS.mkdir(parents=True, exist_ok=True)
(JSON_REPORTS / "FEDERATION_SYSTEMS_MAP_LATEST.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
lines = [
"# Federation Systems Map Latest",
"",
f"Generated UTC: `{report['generatedUTC']}`",
f"Method: `{METHOD_VERSION}`",
"",
"## Verification",
"",
f"- Node rows: `{report['verification']['nodeRows']}`",
f"- Edge rows: `{report['verification']['edgeRows']}`",
f"- Duplicate node keys: `{report['verification']['duplicateNodeKeys']}`",
f"- Duplicate edge keys: `{report['verification']['duplicateEdgeKeys']}`",
f"- Node null keys: `{report['verification']['nodeNullKeys']}`",
f"- Edge null keys: `{report['verification']['edgeNullKeys']}`",
f"- Edge endpoint nodes missing from registry: `{report['verification']['edgeEndpointNodesMissingFromRegistry']}`",
"",
"## Scaling law",
"",
"The federation map is metadata. One million repositories must be tracked by registry rows, shards and Parquet metadata tables, not by cloning every repository.",
]
(REPORTS / "FEDERATION_SYSTEMS_MAP_LATEST.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser(description="Build GlobalGrid2050 federation systems map")
parser.add_argument("--registry", default=str(REGISTRY))
parser.add_argument("--edges", default=str(EDGES))
args = parser.parse_args()
verification = build_map(Path(args.registry), Path(args.edges))
report = {
"generatedUTC": utcnow(),
"methodVersion": METHOD_VERSION,
"registry": args.registry,
"edges": args.edges,
"outputs": {
"nodes": str(OUT / "nodes.parquet"),
"edges": str(OUT / "edges.parquet"),
},
"verification": verification,
"scalingLaw": "registry plus shards plus Parquet plus DuckDB; never clone one million repos",
}
write_reports(report)
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())Release GridAtlas
A Python command-line tool in the scripts folder of GlobalGrid2050 Homepage that fetches active pages, using SHA-256 from GitHub API and the GridAtlas repository.
automationglobalgrid2050-homepage / scripts/release_gridatlas.py · lines 1–153 of 153 · Entry point · pattern exists (shared by 14 files)
- What it does
- It fetches active pages. Defines 8 functions or classes, including fetch, exists, label, build_release, apply. Uses libraries argparse, datetime, hashlib, json, pathlib. 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.
- Inputs & outputs
- In: data source: GitHub API; data source: gridatlas data; JSON file current.json; JSON file homepage.json; JSON file active-pages.json; JSON file presentation.json; JSON file entity-types.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It builds release (`build_release`) and is built from the fetch step (`fetch`) and the exists step (`exists`). One-command GridAtlas homepage release, plus the domain pin for GlobalGrid2050. It accepts `--published-at`, `--description` and `--reason`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050-homepage · scripts · Python CLI
- Uses
- Releases (import), Build Homepage Fallback (script call), GridAtlas — Atlas Page (estate URL), argparse, datetime, hashlib, json, pathlib, re, subprocess, sys
- Used by
- none found
- Produces
- fetch, exists, label, build_release, apply, release_command, pin_command, main
- Defines here
- fetch, exists, label, build_release, apply, release_command, pin_command, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 scripts/release_gridatlas.py:1-153 · blob 512232a0385befbd092f20f67ee3f370da4d8a2a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""One-command GridAtlas homepage release, plus the domain pin for globalgrid2050.
Run from the repository root:
python scripts/release_gridatlas.py release 202610281340 v9.172 \
--published-at 2026-10-28T18:53:00Z \
--description "Find sites ... Now with ..." # optional
python scripts/release_gridatlas.py pin [COMMIT] # after the release PR merges
`release` reads the live GridAtlas pointer (atlas/current.json on gridatlas main)
and refuses unless its generation and composition_version match the arguments,
so the homepage can only advertise what the canonical route already serves. It
then appends one available release (label "V9.172 - 28 October 2026"), promotes
it with scripts/releases.py (keeping every earlier release and adding an audit
entry), and rebuilds the no-JavaScript fallback in index.html.
Availability is the owner's acceptance of that GridAtlas release, asserted by
whoever runs this command; this script does not test the app.
`pin` prints catalogue/homepage-owner.json for globalgrid2050: the commit plus
SHA-256 of the seven bundle files at that commit (read with `git show`).
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import releases # noqa: E402
ENTITY = "gridatlas"
REPO = "Ventusltd/gridatlas"
LIVE_ROUTE = "https://ventusltd.github.io/gridatlas/atlas/"
PINNED_ROUTE = LIVE_ROUTE + "v/{generation}/"
MANIFEST = LIVE_ROUTE + "manifests/{generation}-composition.json"
CURRENT_RAW = f"https://raw.githubusercontent.com/{REPO}/main/atlas/current.json"
BUNDLE = ("index.html", "assets/versioned-homepage.css", "assets/versioned-homepage.js",
"data/homepage.json", "data/active-pages.json", "data/presentation.json", "data/entity-types.json")
def fetch(url, limit=5_000_000):
request = urllib.request.Request(url, headers={"User-Agent": "globalgrid2050-homepage-release"})
with urllib.request.urlopen(request, timeout=30) as response:
return response.read(limit)
def exists(url):
try:
fetch(url, 1)
return True
except OSError:
return False
def label(version, published_at):
when = datetime.fromisoformat(published_at.replace("Z", "+00:00")).astimezone(timezone.utc)
return f"{version.upper()} - {when.day} {when:%B %Y}"
def build_release(generation, version, published_at, source_ref, archive):
release = {"id": generation, "label": label(version, published_at), "url": LIVE_ROUTE,
"published_at": published_at, "status": "available", "source_ref": source_ref}
if archive:
release["archive_url"], release["archive_kind"] = archive
return release
def apply(data, release, reason, description=None):
entity = next(e for e in data["entities"] if e["id"] == ENTITY)
releases.require(all(r["id"] != release["id"] for r in entity["releases"]), f"release {release['id']} already recorded")
entity["releases"].append(release)
if description:
entity["description"] = description.strip()
return releases.promote(data, ENTITY, release["id"], reason)
def release_command(args):
releases.require(re.fullmatch(r"\d{12}", args.generation) is not None, "generation must be 12 digits (YYYYMMDDhhmm)")
releases.require(re.fullmatch(r"v\d+(\.\d+)+", args.version) is not None, "version must look like v9.172")
releases.iso_date(args.published_at, "--published-at", utc_only=True)
source_ref, archive = args.source_ref, None
if not args.offline:
current = json.loads(fetch(CURRENT_RAW))
releases.require(current.get("generation") == args.generation,
f"live pointer serves {current.get('generation')}, not {args.generation}; release GridAtlas first")
releases.require(current.get("composition_version") == args.version,
f"live pointer composition_version is {current.get('composition_version')}, not {args.version}")
if not source_ref:
commits = json.loads(fetch(f"https://api.github.com/repos/{REPO}/commits?path=atlas/current.json&per_page=1"))
source_ref = f"https://github.com/{REPO}/commit/{commits[0]['sha']}"
raw = f"https://raw.githubusercontent.com/{REPO}/main/atlas/"
if exists(raw + f"v/{args.generation}/index.html"):
archive = (PINNED_ROUTE.format(generation=args.generation), "app")
elif exists(raw + f"manifests/{args.generation}-composition.json"):
archive = (MANIFEST.format(generation=args.generation), "manifest")
releases.require(bool(source_ref), "--source-ref is required with --offline")
if args.archive_url:
archive = (args.archive_url, args.archive_kind)
data = releases.load(args.file)
release = build_release(args.generation, args.version, args.published_at, source_ref, archive)
reason = args.reason or f"GridAtlas {args.version} (generation {args.generation}) is live on the canonical route and accepted by the owner"
data = apply(data, release, reason, args.description)
releases.write_validated(args.file, data)
subprocess.run([sys.executable, str(ROOT / "scripts/build_homepage_fallback.py")], check=True, cwd=ROOT)
print(f"Promoted {ENTITY} to {release['id']} ({release['label']}); earlier releases retained.")
print("Next: run the checks in docs/GRIDATLAS-RELEASE.md, open a PR, merge, then `python scripts/release_gridatlas.py pin`.")
return 0
def pin_command(args):
commit = subprocess.run(["git", "rev-parse", args.commit], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
files = {}
for name in BUNDLE:
blob = subprocess.run(["git", "show", f"{commit}:{name}"], cwd=ROOT, check=True, capture_output=True).stdout
files[name] = hashlib.sha256(blob).hexdigest()
print(json.dumps({"repository": "Ventusltd/globalgrid2050-homepage", "commit": commit, "files": files}, indent=2))
return 0
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
rel = commands.add_parser("release", help="Record and promote a live GridAtlas generation")
rel.add_argument("generation")
rel.add_argument("version")
rel.add_argument("--published-at", required=True, help="UTC time the generation went live, e.g. 2026-10-28T18:53:00Z")
rel.add_argument("--description", help="Replace the GridAtlas description shown in its nest")
rel.add_argument("--reason", help="Promotion audit reason")
rel.add_argument("--source-ref", help="Default: the gridatlas commit that last changed atlas/current.json")
rel.add_argument("--archive-url", help="Default: atlas/v/GENERATION/ if published, else its composition manifest")
rel.add_argument("--archive-kind", choices=("app", "manifest"), default="app")
rel.add_argument("--offline", action="store_true", help="Skip live-pointer checks (requires --source-ref)")
rel.add_argument("--file", type=Path, default=releases.DEFAULT_FILE)
pin = commands.add_parser("pin", help="Print catalogue/homepage-owner.json for globalgrid2050")
pin.add_argument("commit", nargs="?", default="origin/main")
args = parser.parse_args(argv)
try:
return release_command(args) if args.command == "release" else pin_command(args)
except (ValueError, OSError, subprocess.CalledProcessError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())Test Release GridAtlas
A test in the tests folder of GlobalGrid2050 Homepage using data from the GridAtlas repository. It sets up (`setUp`) and is built from the grid atlas release tests class (`GridAtlasReleaseTests`).
testglobalgrid2050-homepage / tests/test_release_gridatlas.py · lines 1–42 of 42 · Entry point
- What it does
- It tests its inputs. Defines GridAtlasReleaseTests, setUp, test_label_format, test_next_release_is_promoted_and_history_retained, test_duplicate_release_refused. Uses libraries copy, importlib.util, json, pathlib, sys. Side effects: reads or writes files.
- 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.
- Inputs & outputs
- In: data source: gridatlas data; JSON file homepage.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- Defines `GridAtlasReleaseTests`, `setUp`, `test_label_format` and 2 more.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- copy, importlib.util, json, pathlib, sys, unittest
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- GridAtlasReleaseTests
- Defines here
- GridAtlasReleaseTests, setUp, test_label_format, test_next_release_is_promoted_and_history_retained, test_duplicate_release_refused
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_release_gridatlas.py:1-42 · blob a1057676d4fad4352d726b3fe010715c3216efdf · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
import copy
import importlib.util
import json
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
spec = importlib.util.spec_from_file_location("release_gridatlas", ROOT / "scripts/release_gridatlas.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class GridAtlasReleaseTests(unittest.TestCase):
def setUp(self):
self.data = module.releases.load(ROOT / "data/homepage.json")
def test_label_format(self):
self.assertEqual(module.label("v9.172", "2026-10-28T18:53:00Z"), "V9.172 - 28 October 2026")
self.assertEqual(module.label("v9.156", "2026-09-24T13:34:00Z"), "V9.156 - 24 September 2026")
def test_next_release_is_promoted_and_history_retained(self):
before = next(e for e in self.data["entities"] if e["id"] == "gridatlas")
release = module.build_release("209912311200", "v9.999", "2099-12-31T12:00:00Z", "https://github.com/Ventusltd/gridatlas/commit/" + "0" * 40,
("https://ventusltd.github.io/gridatlas/atlas/v/209912311200/", "app"))
result = module.apply(copy.deepcopy(self.data), release, "test promotion")
after = next(e for e in result["entities"] if e["id"] == "gridatlas")
self.assertEqual(after["operative_release_id"], "209912311200")
self.assertEqual(after["releases"][:-1], before["releases"])
self.assertEqual(after["description"], before["description"])
self.assertEqual(result["promotions"][-1]["from_release_id"], before["operative_release_id"])
def test_duplicate_release_refused(self):
operative = next(e for e in self.data["entities"] if e["id"] == "gridatlas")["operative_release_id"]
release = module.build_release(operative, "v1.0", "2026-01-01T00:00:00Z", "https://example.org/x", None)
with self.assertRaises(ValueError):
module.apply(copy.deepcopy(self.data), release, "repeat")
if __name__ == "__main__":
unittest.main()GridAtlas GPU
A Python module in Graphics Engines Open Source covering atlas GPU summary, atlas nearest, solar and substations, using SHA-256 and haversine.
storagegraphics-engines-open-source / gridatlas_gpu.py · lines 1–42 of 42 · Not reached from any entry point (candidate for review) · pattern valid (shared by 20 files)
- What it does
- Defines load, valid, unit. Uses libraries argparse, hashlib, json, time, math. Side effects: reads or writes files.
- 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: solar, substations. README: "`gridatlas_gpu.py PROJECTS_JSON SUBSTATIONS_GEOJSON` compares every valid solar point against every valid substation in those supplied snapshots, in bounded GPU batches."
- Inputs & outputs
- In: command-line arguments. Out: JSON file atlas-gpu-summary.json; JSON file atlas-nearest.json.
- What it achieves
- It is built from the load step (`load`), the valid step (`valid`) and the unit step (`unit`). All valid solar points against all valid substations in supplied Atlas snapshots.
- Why it matters
- No other file in the estate was found to import it.
- Application
- graphics-engines-open-source · / · Python module
- Uses
- argparse, hashlib, json, time, math, pathlib, numpy, cupy
- Used by
- none found
- Produces
- load, valid, unit
- Defines here
- load, valid, unit
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 gridatlas_gpu.py:1-42 · blob c8c35d27cc7eeae5564a1b51f8473a30aaf272b2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""All valid solar points against all valid substations in supplied Atlas snapshots.
Geographic proximity only: no connectivity, voltage suitability or capacity inference.
"""
import argparse,hashlib,json,time,math
from pathlib import Path
import numpy as np
import cupy as cp
p=argparse.ArgumentParser();p.add_argument('projects',type=Path);p.add_argument('substations',type=Path);a=p.parse_args()
def load(path):
b=path.read_bytes();return json.loads(b),hashlib.sha256(b).hexdigest()
projects,ph=load(a.projects);subs,sh=load(a.substations)
def valid(lon,lat):
return all(type(v) in (int,float) and math.isfinite(v) for v in (lon,lat)) and -180<=lon<=180 and -90<=lat<=90 and not(lon==0 and lat==0) and not(abs(lon+7.55716)<1e-4 and abs(lat-49.766807)<1e-4)
solar=[];solar_total=0
for row in projects['rows']:
r=dict(zip(projects['fields'],row));technology=projects['dictionaries']['technology'][r['technology']]
if technology!='solar':continue
solar_total+=1
if valid(r['longitude'],r['latitude']):solar.append((str(r['repd_ref']),r['longitude'],r['latitude']))
stations=[]
for i,f in enumerate(subs['features']):
g=f.get('geometry') or {};xy=g.get('coordinates') or []
if g.get('type')=='Point' and len(xy)>=2 and valid(xy[0],xy[1]):stations.append((i,float(xy[0]),float(xy[1])))
if not stations or not solar:raise ValueError('No usable coordinates')
s=np.array([r[1:] for r in solar]);b=np.array([r[1:] for r in stations]);br=np.deg2rad(b);sr=np.deg2rad(s)
def unit(r):return np.c_[np.cos(r[:,1])*np.cos(r[:,0]),np.cos(r[:,1])*np.sin(r[:,0]),np.sin(r[:,1])]
gb=cp.asarray(unit(br));out=[];maxerr=0;start=time.perf_counter()
for first in range(0,len(s),256):
last=min(len(s),first+256);ga=cp.asarray(unit(sr[first:last]));delta=ga[:,None,:]-gb[None,:,:]
chord=cp.sqrt(cp.sum(delta*delta,axis=2));dist=2*6371000.0*cp.arcsin(cp.clip(chord/2,0,1));near=cp.argmin(dist,axis=1);vals=dist[cp.arange(last-first),near]
# Independent CPU haversine for EVERY pair, not just selected nearest points.
lat=sr[first:last,1,None];lon=sr[first:last,0,None]
hav=np.sin((lat-br[None,:,1])/2)**2+np.cos(lat)*np.cos(br[None,:,1])*np.sin((lon-br[None,:,0])/2)**2
cpu=2*6371000.0*np.arctan2(np.sqrt(np.clip(hav,0,1)),np.sqrt(np.clip(1-hav,0,1)))
host=dist.get();error=float(np.max(np.abs(host-cpu)));maxerr=max(maxerr,error);assert error<1e-5,error
ids=near.get();assert np.all(np.abs(cpu[np.arange(last-first),ids]-cpu.min(axis=1))<1e-5)
for k,(idx,d) in enumerate(zip(ids,vals.get())):out.append({'repd_ref':solar[first+k][0],'substation_snapshot_index':stations[int(idx)][0],'straight_distance_m':float(d)})
cp.cuda.Stream.null.synchronize()
result={'project_sha256':ph,'substation_sha256':sh,'solar_records':solar_total,'valid_solar':len(solar),'unlocated_solar':solar_total-len(solar),'substation_records':len(subs['features']),'valid_substations':len(stations),'unlocated_substations':len(subs['features'])-len(stations),'all_pair_checks':len(s)*len(b),'gpu_cpu_max_error_m':maxerr,'elapsed_s':time.perf_counter()-start,'device':cp.cuda.ru … [line shortened here: 605 characters; full line on GitHub]
root=Path(__file__).parent/'.local';root.mkdir(exist_ok=True)
(root/'atlas-gpu-summary.json').write_text(json.dumps(result,indent=2));(root/'atlas-nearest.json').write_text(json.dumps({'provenance':result,'results':out},separators=(',',':')))
print(json.dumps(result))