In this section
- Build Payload geodesy · pipelinenews / tools/intelligence/cartridges/grid-proximity/build_payload.py lines 391–533
- Proof render · pipelinenews / tools/intelligence/cartridges/grid-proximity/proof.mjs lines 1–281
- Verify Widen ingest · pipelinenews / tools/intelligence/cartridges/grid-proximity/verify_widen.py lines 1–125
- Widen Spine storage · pipelinenews / tools/intelligence/cartridges/grid-proximity/widen_spine.py lines 1–143
Build Payload
A Python command-line tool in the grid proximity folder of PipelineNews that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine and SHA-256.
geodesypipelinenews / tools/intelligence/cartridges/grid-proximity/build_payload.py · lines 391–533 of 533 (continued from section 1040) · Entry point · pattern build_index (shared by 3 files)
- What it does
- It loads grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 13 functions or classes, including curvature, haversine_km, cell_of, load_segments, load_substations. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV, 220kV, 132kV, 66kV, 33kV, 11kV.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_33kv_East_of_England.geojson; GeoJSON file grid_33kv_London_Area.geojson; GeoJSON file grid_33kv_North_East_England.geojson. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 220kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- What it achieves
- It loads segments (`load_segments`), loads substations (`load_substations`) and loads UKPN 11kv (`load_ukpn_11kv`). Grid proximity payload builder. Its code works with 11 kV, 33 kV and 132 kV. It accepts `--gg2050`, `--spine` and `--out`.
- Why it matters
- Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity · Python CLI
- Uses
- argparse, hashlib, json, math, os, time
- Used by
- named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- curvature, haversine_km, cell_of, load_segments, load_substations, load_ukpn_11kv, build_index, swept_radius_km, nearest_segment, nearest_substations, grid_probable, main
- Defines here
- _num
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-proximity/build_payload.py:391-533 · blob 674b71fb2cb346ad37891cbadcff12f0ba5eccec · 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: production_core
per_voltage_full[kv] = hit
circuit = min(per_voltage_full.values(), key=lambda h: h["km"]) if per_voltage_full else None
# West Burton and Cottam connect at 400 and 132 kV because of their size,
# with 33 kV four to eight kilometres away. Reporting only "nearest" would
# answer the wrong question for them. Both are published; which one
# matters is the reader's judgement, not an assumption coded in here.
tr = [h for kv, h in per_voltage_full.items() if kv in TRANSMISSION]
di = [h for kv, h in per_voltage_full.items() if kv not in TRANSMISSION]
transmission = min(tr, key=lambda h: h["km"]) if tr else None
distribution = min(di, key=lambda h: h["km"]) if di else None
nearby = nearest_substations(lon, lat, subs, sub_index, want=5)
substation = nearby[0] if nearby else None
# Outside the UKPN licence area the nearest "11 kV" point is hundreds of
# kilometres away and means nothing. Report null, never a large number:
# a coverage hole wearing a number is the defect this whole model exists
# to avoid.
est11 = (nearest_substations(lon, lat, ukpn, ukpn_index, want=1) or [None])[0] if ukpn else None
if est11 and est11["km"] > EST_11KV_MAX_KM:
est11 = None
published = None
try:
published = float(row[21])
except (ValueError, IndexError):
pass
out_rows.append({
"ref": row[0],
"name": row[4],
"operator": row[5],
"town": row[6],
"county": row[7],
"region": row[8],
"country": row[9],
"at": [round(lon, 6), round(lat, 6)],
"mw": _num(row[1]), # column 1 is capacity MW: median 25, max 1450
"tech": row[2],
"status": row[3],
"circuit": circuit,
"circuit_transmission": transmission,
"circuit_distribution": distribution,
"circuit_by_kv": by_voltage,
"grid_probable": grid_probable(circuit, nearby[0] if nearby else None),
"substation": substation,
"substations_nearby": nearby[1:],
"substation_11kv_estimated": est11,
"published_circuit_km": published,
})
payload = {
"schema": "pipelinenews.v9.grid-proximity.v1",
"generation": args.generation,
"record_count": len(out_rows),
"earth_model": {
"formula": "haversine",
"radius_km": R_ATLAS,
"radius_source": "WGS84 semi-major axis; the constant used by "
"ventus-corev8engine.js and atlasHaversineKm",
"segment_projection": "local tangent plane from WGS84 M and N at "
"the site latitude",
"matches": ["gridatlas ventus-corev8engine.js",
"gis-sld-financial-sandbox atlasHaversineKm"],
"differs_from": {
"project_intelligence_circuit_km": 6371.0088,
"reads_short_by_pct": 0.1119,
},
},
"network": {
"voltages_kv": VOLTAGES,
"transmission_kv": TRANSMISSION,
"distribution_kv": [33],
"segments": len(segments),
"substations": len(subs),
"measure": "perpendicular distance to the circuit, not to a sampled vertex",
"estimated_11kv_points": len(ukpn),
"estimated_11kv_max_km": EST_11KV_MAX_KM,
"estimated_11kv_note": "UKPN licence area only, tagged (est) at source. "
"Absence elsewhere means the layer does not cover it, "
"not that no 11 kV network exists.",
},
"grid_probable_rule": {
"purpose": "A screening band from measured geometry. It says how close "
"the mapped network is, not whether a connection is obtainable.",
"bands": [
{"band": "STRONG", "circuit_km_max": 2.0, "substation_km_max": 1.0},
{"band": "MODERATE", "circuit_km_max": 5.0, "substation_km_max": 3.0},
{"band": "DISTANT", "circuit_km_max": 15.0, "substation_km_max": 10.0},
{"band": "REMOTE", "circuit_km_max": None, "substation_km_max": None},
],
"not_modelled": [
"capacity-to-voltage suitability (awaiting ENA and DNO published practice)",
"connection queue position, curtailment or headroom",
"33 kV and 11 kV distribution, where most sub-50 MW schemes connect",
"DNO licence area, ownership or IDNO presence",
],
"honesty": "Every input to the band is published beside it. Nothing here "
"is inferred from capacity, and no assumption about connection "
"voltage has been made without a cited source.",
},
"caveat": {
"straight_line": "Straight-line distance to mapped geometry. Not a "
"cable route, not a connection length, and no "
"wayleave, crossing, terrain or consent content.",
"substation": "A mapped substation point does not confirm capacity, "
"voltage suitability, connection rights, queue position "
"or acceptance by any network party.",
"coverage": "OpenStreetMap-derived. Absence from the layer is not "
"absence on the ground.",
"voltage_is_not_connection": "The nearest circuit is not the connection "
"voltage. Large schemes connect at transmission whatever runs "
"past the gate - West Burton and Cottam sit 4 to 8 km from 33 kV "
"and connect at 400 and 132 kV. Transmission and distribution "
"distances are published separately for that reason; no "
"capacity-to-voltage rule is applied without a cited source.",
"precision": "Quoted to 10 m because the geometry supports it; the "
"site coordinate is a register centroid and may sit "
"hundreds of metres from the point of connection.",
},
"provenance": {
"spine": "DESNZ Renewable Energy Planning Database Q2 2026, OGL v3.0",
"network": "OpenStreetMap via the pinned Ventus voltage layers, "
"ODbL-1.0, (c) OpenStreetMap contributors",
},
"rows": out_rows,
}
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
with open(args.out, "w", encoding="utf-8") as handle:
handle.write(body)
digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
with open(args.out + ".sha256", "w", encoding="utf-8") as handle:
handle.write(digest + "\n")
print("wrote %s (%d rows, %.1f MB) in %.1fs\nsha256 %s"
% (args.out, len(out_rows), len(body) / 1e6, time.time() - started, digest))
def _num(value):
try:
return float(value)
except (TypeError, ValueError):
return None
if __name__ == "__main__":
main()Proof
A JavaScript module in the grid proximity folder of PipelineNews that opens tab, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.
renderpipelinenews / tools/intelligence/cartridges/grid-proximity/proof.mjs · lines 1–281 of 281 · Not reached from any entry point (candidate for review) · pattern openTab (shared by 2 files)
- What it does
- It draws substations, 33kV and solar. Defines 7 functions or classes, including ok, wait, settle, openTab, hav. Uses libraries node:fs/promises, node:path, jsdom. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: substations, 33kV, solar, 11kV.
- Inputs & outputs
- In: command-line arguments. Voltage levels named: 33kV, 11kV.
- What it achieves
- It opens tab (`openTab`) and is built from the wait step (`wait`) and the settle step (`settle`). Grid-proximity render proof. Its code works with 33 kV and 11 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity · JavaScript module
- Uses
- node:fs/promises, node:path, jsdom
- Used by
- none found
- Produces
- ok, wait, settle, openTab, hav, firstColumnValues, expected
- Defines here
- ok, wait, settle, openTab, hav, firstColumnValues, expected
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-proximity/proof.mjs:1-281 · blob 64c47bfb9e4da2a9bec0c9858ac6508720b00840 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* grid-proximity render proof.
*
* render_proof.mjs in tools/intelligence is written against the
* project-intelligence cartridge specifically - its payload filename, its
* contract name and its mount function are all hardcoded - so it cannot prove
* any other cartridge. This proves this one, against a real DOM rather than a
* stub, and independently re-derives the radius arithmetic rather than
* trusting the cartridge's own answer.
*
* Usage:
* node proof.mjs <path-to-release-dir> <generation>
*/
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { JSDOM } from "jsdom";
const root = process.argv[2];
const gen = process.argv[3];
if (!root || !gen) {
console.error("usage: node proof.mjs <release-dir> <generation>");
process.exit(2);
}
const payloadPath = join(root, "data", `${gen}-grid-proximity.json`);
const payloadText = await readFile(payloadPath, "utf8");
const payload = JSON.parse(payloadText);
// pretendToBeVisual gives jsdom a requestAnimationFrame. Without it the scope
// takes its no-animation path, which is also worth proving works.
const dom = new JSDOM("<!doctype html><html><body></body></html>", { pretendToBeVisual: true });
globalThis.window = dom.window;
globalThis.document = dom.window.document;
globalThis.Blob = dom.window.Blob;
globalThis.URL = dom.window.URL;
if (!globalThis.URL.createObjectURL) {
globalThis.URL.createObjectURL = () => "blob:proof";
globalThis.URL.revokeObjectURL = () => {};
}
let fetchCalls = 0;
globalThis.fetch = async (url) => {
fetchCalls += 1;
if (!String(url).includes("grid-proximity")) throw new Error("unexpected fetch " + url);
return { ok: true, status: 200, json: async () => JSON.parse(payloadText) };
};
const modPath = "file://" + join(root, "assets", `${gen}-grid-proximity.mjs`).replace(/\\/g, "/");
const mod = await import(modPath);
const contract = mod.GRID_PROXIMITY_CARTRIDGE_CONTRACT;
const checks = [];
const ok = (name, pass, detail = "") => checks.push({ name, pass: Boolean(pass), detail });
ok("contract generation matches release", contract.generation === gen, `${contract.generation} vs ${gen}`);
ok("contract declares additive_only", contract.additive_only === true);
ok("contract declares mutates_existing_dom false", contract.mutates_existing_dom === false);
ok("contract declares zero project bindings", contract.project_bindings === 0);
ok("contract is not eligible for news signal", contract.eligible_for_news_signal === false);
const host = document.createElement("div");
document.body.appendChild(host);
const before = document.body.innerHTML.length;
const result = mod.mountGridProximity({
host,
payloadAsset: { path: payloadPath, url: payloadPath },
});
ok("mount requests no payload", fetchCalls === 0, `fetchCalls=${fetchCalls}`);
ok("mount reports zero payload requests", result.payloadRequests === 0);
ok("mount reports zero project bindings", result.projectBindings === 0);
ok("mount rendered inside its own host", host.children.length === 1 && document.body.children.length === 1);
ok("mount added nothing outside the host", document.body.innerHTML.length > before);
const tabButtons = Array.from(host.querySelectorAll("button"));
ok("all five tabs present", tabButtons.length === 5, tabButtons.map((b) => b.textContent).join(","));
const wait = (ms = 0) => new Promise((r) => setTimeout(r, ms));
// requestAnimationFrame in jsdom fires on a ~16 ms timer, so a loop of
// setTimeout(0) never advances it. The scope needs real elapsed time.
const settle = async (ms) => { const end = Date.now() + ms; while (Date.now() < end) await wait(20); };
async function openTab(label) {
const b = tabButtons.find((x) => x.textContent === label);
b.click();
for (let i = 0; i < 30; i += 1) await wait();
return host.textContent;
}
const radiusText = await openTab("RADIUS");
ok("payload fetched once, on first tab", fetchCalls === 1, `fetchCalls=${fetchCalls}`);
ok("RADIUS tab renders its controls",
radiusText.includes("PROJECTS WITHIN A RADIUS") && host.querySelector("#gpCentre") !== null);
/* --- independently re-derive a radius query and compare ------------------ */
const R = 6378.137;
const DEG = Math.PI / 180;
const hav = (lo1, la1, lo2, la2) => {
const dLat = (la2 - la1) * DEG;
const dLon = (lo2 - lo1) * DEG;
const x = Math.sin(dLat / 2) ** 2 + Math.cos(la1 * DEG) * Math.cos(la2 * DEG) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
};
const centre = payload.rows[0];
const RADIUS_KM = 25;
const expected = payload.rows.filter((r) => hav(centre.at[0], centre.at[1], r.at[0], r.at[1]) <= RADIUS_KM);
host.querySelector("#gpCentre").value = centre.ref;
host.querySelector("#gpRadius").value = String(RADIUS_KM);
host.querySelector("#gpGo").click();
for (let i = 0; i < 30; i += 1) await wait();
const reported = Number((host.querySelector("#gpOut strong") || {}).textContent);
ok("radius search count matches an independent haversine sweep",
reported === expected.length, `cartridge=${reported} independent=${expected.length}`);
const gauges = host.querySelectorAll("#gpOut .gauges strong");
ok("radius search reports capacity in the circle", gauges.length >= 2 && gauges[1].textContent.length > 0,
gauges.length >= 2 ? gauges[1].textContent : "");
/* --- sorting ------------------------------------------------------------- */
const sortText = await openTab("SORT");
ok("SORT tab renders the table", sortText.includes("EVERY PROJECT, SORTED"));
const heads = Array.from(host.querySelectorAll("th[data-k]")).map((t) => t.dataset.k);
for (const needed of ["mw", "town", "county", "region", "_ckm", "_skm"]) {
ok(`sortable column present: ${needed}`, heads.includes(needed));
}
function firstColumnValues(colIndex) {
return Array.from(host.querySelectorAll("tbody tr")).slice(0, 20)
.map((tr) => tr.children[colIndex].textContent);
}
const mwIdx = heads.indexOf("mw");
const mwDesc = firstColumnValues(mwIdx).map((v) => parseFloat(v)).filter(Number.isFinite);
ok("default sort is capacity, largest first",
mwDesc.every((v, i) => i === 0 || mwDesc[i - 1] >= v), mwDesc.slice(0, 5).join(","));
const townTh = Array.from(host.querySelectorAll("th[data-k]")).find((t) => t.dataset.k === "town");
townTh.click();
for (let i = 0; i < 10; i += 1) await wait();
const townIdx = Array.from(host.querySelectorAll("th[data-k]")).map((t) => t.dataset.k).indexOf("town");
const towns = firstColumnValues(townIdx).filter(Boolean);
ok("clicking TOWN clusters towns together alphabetically",
towns.every((v, i) => i === 0 || towns[i - 1].localeCompare(v) <= 0), towns.slice(0, 4).join(" | "));
/* --- connections --------------------------------------------------------- */
const connectText = await openTab("CONNECT");
ok("CONNECT tab renders", connectText.includes("AUTO-DRAWN CONNECTIONS"));
let exported = null;
const realBlob = globalThis.Blob;
globalThis.Blob = class extends realBlob {
constructor(parts, opts) { super(parts, opts); exported = JSON.parse(parts[0]); }
};
host.querySelector("#gpGeo").click();
for (let i = 0; i < 10; i += 1) await wait();
globalThis.Blob = realBlob;
const withCircuit = payload.rows.filter((r) => r.circuit).length;
const withSub = payload.rows.filter((r) => r.substation).length;
ok("GeoJSON export builds", exported && exported.type === "FeatureCollection");
ok("one connection line per project per target",
exported && exported.features.length === withCircuit + withSub,
exported ? `${exported.features.length} vs ${withCircuit + withSub}` : "");
ok("every exported line has two ends",
exported && exported.features.every((f) => f.geometry.coordinates.length === 2));
ok("every exported line stamps its measurement method",
exported && exported.features.every((f) => f.properties.measurement_method === "atlas_haversine_6378_137_km"));
ok("export carries the caveat block", exported && Boolean(exported.properties.caveat.straight_line));
/* --- target scope --------------------------------------------------------- */
const targetText = await openTab("TARGET");
ok("TARGET tab renders the scope", targetText.includes("DRAW STRAIGHT TO NEAREST SUBSTATION"));
const canvas = host.querySelector("#gpScope");
ok("scope canvas exists and is square", canvas && canvas.width === canvas.height, canvas ? `${canvas.width}x${canvas.height}` : "absent");
ok("scope styles are scoped to the cartridge host", (() => {
const style = document.getElementById("gp-scope-style");
if (!style) return false;
const selectors = style.textContent.match(/^\s*#?[^@{}]+\{/gm) || [];
return selectors.every((s) => s.includes("#gridProximityHost"));
})(), "no selector may escape #gridProximityHost");
const scopeTarget = payload.rows.find((r) => r.substation && r.substation.name);
host.querySelector("#gpTargetPick").value = scopeTarget.ref;
host.querySelector("#gpTargetGo").click();
await settle(1400);
const readoutText = host.querySelector("#gpReadout").textContent;
ok("scope acquires a named target", readoutText.includes(scopeTarget.substation.name.slice(0, 12)),
readoutText.slice(0, 60));
ok("scope reports a bearing in degrees", /\d{3}°/.test(readoutText));
ok("scope lists every voltage in reach",
Object.keys(scopeTarget.circuit_by_kv).every((kv) => readoutText.includes(`${kv} kV`)),
Object.keys(scopeTarget.circuit_by_kv).join("/"));
ok("scope carries the ETAP / DIgSILENT caveat",
readoutText.includes("ETAP") && readoutText.includes("chartered engineer"));
// The bearing shown must be the real one, re-derived here.
{
const D = Math.PI / 180;
const [lo1, la1] = scopeTarget.at; const [lo2, la2] = scopeTarget.substation.at;
const y = Math.sin((lo2 - lo1) * D) * Math.cos(la2 * D);
const x = Math.cos(la1 * D) * Math.sin(la2 * D) - Math.sin(la1 * D) * Math.cos(la2 * D) * Math.cos((lo2 - lo1) * D);
const brg = (Math.atan2(y, x) / D + 360) % 360;
const shown = Number((readoutText.match(/(\d{3})°/) || [])[1]);
ok("the bearing shown matches an independent derivation",
Math.abs(shown - brg) <= 1, `shown ${shown} independent ${brg.toFixed(1)}`);
}
/* --- method -------------------------------------------------------------- */
const methodText = await openTab("METHOD");
ok("METHOD tab states the radius", methodText.includes("6378.137"));
ok("METHOD tab names the tools it agrees with",
methodText.includes("ventus-corev8engine.js") && methodText.includes("atlasHaversineKm"));
ok("METHOD tab carries the straight-line caveat",
methodText.includes("Not a") && methodText.toLowerCase().includes("cable route"));
/* --- payload integrity --------------------------------------------------- */
ok("payload uses the atlas radius", payload.earth_model.radius_km === 6378.137);
ok("payload covers all six mapped voltages",
payload.network.voltages_kv.join(",") === "400,275,220,132,66,33");
ok("transmission and distribution are separated",
payload.network.transmission_kv.join(",") === "400,275,220,132,66"
&& payload.network.distribution_kv.join(",") === "33");
ok("every row answers transmission and distribution separately",
payload.rows.every((r) => r.circuit_transmission && r.circuit_distribution));
ok("the transmission answer is never a distribution voltage",
payload.rows.every((r) => payload.network.transmission_kv.includes(r.circuit_transmission.kv)));
ok("the overall nearest is the better of the two",
payload.rows.every((r) => Math.abs(
Math.min(r.circuit_transmission.km, r.circuit_distribution.km) - r.circuit.km) < 1e-9));
ok("estimated 11 kV is capped, not extrapolated across the country",
payload.rows.every((r) => !r.substation_11kv_estimated
|| r.substation_11kv_estimated.km <= payload.network.estimated_11kv_max_km),
`${payload.rows.filter((r) => r.substation_11kv_estimated).length} of ${payload.rows.length} in the UKPN area`);
ok("the estimated layer says it is estimated",
payload.network.estimated_11kv_note.includes("(est)")
&& payload.network.estimated_11kv_note.includes("Absence"));
ok("the payload warns that nearest is not connection voltage",
payload.caveat.voltage_is_not_connection.includes("West Burton"));
// West Burton and Cottam are large, public, and connect at transmission. If the
// model ever reports distribution as their nearest, it has gone wrong.
for (const nm of ["West Burton Solar", "Cottam Solar"]) {
const row = payload.rows.find((r) => (r.name || "").includes(nm));
ok(`${nm} reads transmission, not 33 kV`,
row && row.circuit_transmission.km < row.circuit_distribution.km,
row ? `${row.circuit_transmission.km} km @${row.circuit_transmission.kv} kV vs ${row.circuit_distribution.km} km @33 kV` : "not found");
}
ok("every row carries a grid probable band",
payload.rows.every((r) => r.grid_probable && r.grid_probable.band));
ok("the band is reproducible from its own published rule", payload.rows.every((r) => {
const g = r.grid_probable;
if (g.band === "UNKNOWN") return true;
const bands = payload.grid_probable_rule.bands;
const expected = (bands.find((b) => b.circuit_km_max !== null
&& r.circuit.km <= b.circuit_km_max && r.substation.km <= b.substation_km_max) || { band: "REMOTE" }).band;
return expected === g.band;
}));
ok("the rule publishes what it does not model",
payload.grid_probable_rule.not_modelled.length >= 4);
ok("no capacity-to-voltage assumption has been smuggled in",
payload.grid_probable_rule.not_modelled.some((s) => s.includes("capacity-to-voltage")));
ok("every row carries a snapped circuit foot",
payload.rows.every((r) => r.circuit && Array.isArray(r.circuit.foot) && r.circuit.foot.length === 2));
ok("every row carries a nearest substation", payload.rows.every((r) => r.substation));
ok("every row carries four more substations for the scope",
payload.rows.every((r) => Array.isArray(r.substations_nearby) && r.substations_nearby.length === 4));
ok("nearby substations are ordered by range",
payload.rows.every((r) => [r.substation, ...r.substations_nearby]
.every((s, i, a) => i === 0 || a[i - 1].km <= s.km)));
ok("every row carries the nearest circuit at each voltage",
payload.rows.every((r) => Object.keys(r.circuit_by_kv).length >= 1));
ok("the overall nearest circuit equals the best of the per-voltage set",
payload.rows.every((r) => {
const best = Math.min(...Object.values(r.circuit_by_kv).map((v) => v.km));
return Math.abs(best - r.circuit.km) < 1e-6;
}));
const failed = checks.filter((c) => !c.pass);
for (const c of checks) {
console.log(` [${c.pass ? "PASS" : "FAIL"}] ${c.name}${c.detail ? " " + c.detail : ""}`);
}
console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`);
process.exit(failed.length ? 1 : 0);Verify Widen
A Python command-line tool in the grid proximity folder of PipelineNews that reads substations. It is built from the rows of helper (`rows_of`).
ingestpipelinenews / tools/intelligence/cartridges/grid-proximity/verify_widen.py · lines 1–125 of 125 · Entry point · pattern rows_of (shared by 2 files)
- What it does
- It loads substations. Defines rows_of, main. Uses libraries argparse, collections, json. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: substations.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Prove the widened payload changed nothing it should not have. It accepts `--baseline`, `--widened` and `--published`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity · Python CLI
- Uses
- argparse, collections, json
- Used by
- none found
- Produces
- rows_of, main
- Defines here
- rows_of, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-proximity/verify_widen.py:1-125 · blob 42671edf5b541497b176723e7d55431c722fadb6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""verify_widen.py - prove the widened payload changed nothing it should not have.
WHY THIS EXISTS
Adding rows to the spine and re-running the engine is only safe if the rows that were
already there come out identical. If they do not, the adapter has perturbed a published
measurement, and every solar and bess distance in the product silently moved.
That is easy to get wrong in a way no eyeball catches. build_payload.py builds a spatial
index over the segments and sweeps outward from each site; a denser or differently ordered
row set could in principle change which candidate a search settles on. This asserts it did
not, per row and per field, rather than trusting that it could not.
Three checks, in the order that makes a failure legible:
1. REPRODUCTION - re-running the ORIGINAL spine through today's engine must reproduce
the published file. If this fails, the published file was built by a different engine
or from a different spine, and no comparison after it means anything. Comparing the
widened output against a stale published file instead of against a fresh baseline is
how a real regression gets attributed to drift and waved through.
2. INVARIANCE - every ref present in the baseline must appear in the widened payload
with byte-identical JSON. Not "close", not "within tolerance": identical. A distance
that moves by 1e-9 still means the search changed, and the next change might not be
1e-9.
3. COVERAGE - the new rows must actually carry measurements, not nulls. A row added to
the file that reports nothing is worse than an absent row, because absence is honest
and a null in a populated column reads as "measured, nothing near".
Usage:
python verify_widen.py --baseline <baseline.json> --widened <widened.json>
[--published <shipped grid-proximity.json>]
"""
import argparse
import collections
import json
def rows_of(path):
d = json.load(open(path, encoding="utf-8"))
rs = d if isinstance(d, list) else next(
v for v in d.values() if isinstance(v, list) and v and isinstance(v[0], dict))
return d, {r["ref"]: r for r in rs}, rs
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--baseline", required=True)
ap.add_argument("--widened", required=True)
ap.add_argument("--published")
a = ap.parse_args()
_, base, base_rows = rows_of(a.baseline)
_, wide, wide_rows = rows_of(a.widened)
fail = 0
if a.published:
_, pub, pub_rows = rows_of(a.published)
same = sum(1 for k in pub
if k in base and json.dumps(pub[k], sort_keys=True)
== json.dumps(base[k], sort_keys=True))
print(f"1. REPRODUCTION published {len(pub)} rows | baseline {len(base)} rows | "
f"identical {same}")
if same != len(pub) or len(pub) != len(base):
fail += 1
print(" FAIL - today's engine does not reproduce the published file.")
for k in list(pub)[:400]:
if k in base and json.dumps(pub[k], sort_keys=True) != json.dumps(
base[k], sort_keys=True):
for f in pub[k]:
if json.dumps(pub[k].get(f), sort_keys=True) != json.dumps(
base[k].get(f), sort_keys=True):
print(f" first diff ref {k}.{f}: "
f"{pub[k].get(f)!r} -> {base[k].get(f)!r}")
break
break
else:
print(" ok - the engine reproduces what is shipped, so the comparison below "
"is engine-vs-engine")
missing = [k for k in base if k not in wide]
moved = [k for k in base
if k in wide and json.dumps(base[k], sort_keys=True)
!= json.dumps(wide[k], sort_keys=True)]
print(f"\n2. INVARIANCE baseline rows {len(base)} | present in widened "
f"{len(base)-len(missing)} | moved {len(moved)}")
if missing or moved:
fail += 1
print(f" FAIL - {len(missing)} dropped, {len(moved)} changed")
for k in moved[:5]:
for f in base[k]:
if json.dumps(base[k].get(f), sort_keys=True) != json.dumps(
wide[k].get(f), sort_keys=True):
print(f" ref {k}.{f}: {base[k].get(f)!r} -> {wide[k].get(f)!r}")
break
else:
print(" ok - every previously published row is byte-identical")
new = [wide[k] for k in wide if k not in base]
with_circuit = [r for r in new if r.get("circuit")]
with_sub = [r for r in new if r.get("substation")]
print(f"\n3. COVERAGE new rows {len(new)} | with a circuit "
f"{len(with_circuit)} | with a substation {len(with_sub)}")
tech = collections.Counter(r.get("tech") for r in new)
print(" new tech:", tech.most_common())
if new and len(with_circuit) < len(new):
print(f" note: {len(new)-len(with_circuit)} new row(s) matched no circuit at all")
if not new:
fail += 1
print(" FAIL - nothing was added")
elif len(with_circuit) < 0.95 * len(new):
fail += 1
print(" FAIL - most new rows carry no measurement; a populated column of nulls "
"reads as 'measured, nothing near', which is a different claim from 'absent'")
allrows = collections.Counter(r.get("tech") for r in wide_rows)
print(f"\n widened total {len(wide_rows)} rows: {allrows.most_common()}")
print("\n" + ("VERDICT: PASS" if not fail else f"VERDICT: FAIL ({fail} check(s))"))
return 1 if fail else 0
if __name__ == "__main__":
raise SystemExit(main())Widen Spine
A Python command-line tool in the grid proximity folder of PipelineNews that reads solar and battery storage (BESS), using haversine.
storagepipelinenews / tools/intelligence/cartridges/grid-proximity/widen_spine.py · lines 1–143 of 143 · Entry point
- What it does
- It loads solar and battery storage (BESS). Defines title_status, load_wider, to_spine_row, main. Uses libraries argparse, json, os, collections. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): 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, battery storage (BESS), 33kV.
- Inputs & outputs
- In: command-line arguments. Voltage levels named: 33kV.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It loads wider (`load_wider`) and is built from the title status helper (`title_status`) and the to spine row helper (`to_spine_row`). Put the wider fleet through the same grid-proximity engine. Its code works with 33 kV. It accepts `--spine`, `--wider` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity · Python CLI
- Uses
- argparse, json, os, collections
- Used by
- none found
- Produces
- title_status, load_wider, to_spine_row, main
- Defines here
- title_status, load_wider, to_spine_row, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-proximity/widen_spine.py:1-143 · blob 31e69c2ecbf6bc1eaa162d89e385681d1c005e54 · 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: production_core
"""widen_spine.py - put the wider fleet through the same grid-proximity engine.
WHY THIS EXISTS
grid-proximity.json carried 3047 rows and exactly two technologies: solar (1747) and
bess (1300). The obvious reading is that the builder filters, and that a technology
filter needs relaxing. It does not filter. build_payload.py reads every spine row that
has usable coordinates and passes `tech` straight through from column 2. The narrowness
was never in the engine - the spine it is fed contains only solar and bess.
gridatlas/_build-plan/PROJECT-STUDIES/_evidence/master.tsv
3054 rows: solar 1750, bess 1304; 7 have unusable coordinates; 3047 published.
Meanwhile wider-fleet.json holds 1104 further projects - biomass 823, hydro 151,
hydrogen 62, act 37, tidal 18, geothermal 7, caes 4, flywheel 1, other 1 - and 1092 of
them have no grid proximity computed at all. They are not absent because anything decided
they should be. They are absent because they were never in the file the builder reads.
WHY THIS IS AN ADAPTER AND NOT A SECOND BUILDER
The temptation is to write a small proximity calculation for the wider fleet. That would
be the estate's known failure: two implementations of the same measurement that disagree
in public. build_payload.py already does this correctly and carefully - point to SEGMENT
rather than to the nearest sampled vertex, all five mapped voltages plus the eleven 33 kV
regional files, full geometry at 163,905 vertices rather than a 47,897-point decimation,
and haversine on R = 6378.137 so a distance measured in Pipeline News equals the same
distance measured in the Atlas or the Sandbox.
So this writes no geometry at all. It reshapes wider-fleet rows into the spine's 40-column
contract and hands them to the existing engine unchanged. The solar and bess rows must
come out byte-identical; verify_widen.py asserts exactly that, and a single moved value
there means this adapter changed something it had no business changing.
WHAT IS DELIBERATELY LEFT EMPTY
`town` is left empty for every wider-fleet row. In the spine that column is the PLANNING
AUTHORITY, not the settlement - "Doncaster" is who decides a project, not where it is -
and the wider-fleet source carries no authority field. The settlement is often recoverable
from the project name, and a local model extracts it at 98.3% precision, but 98.3% is a
machine for generating plausible wrong towns in a field a reader would trust. An empty
column is honest; a filled one that is wrong 1 time in 60 is not. Region and country are
empty for the same reason: not present in the source, and not guessable from a postcode
outcode without a gazetteer this repository does not carry.
Usage:
python widen_spine.py --spine <master.tsv> --wider <wider-fleet.json> --out <combined.tsv>
"""
import argparse
import json
import os
SPINE_COLUMNS = 40
# spine column -> wider-fleet key. Everything not named here stays empty.
# 0 ref 1 capacity MW 2 tech 3 status 4 name 5 operator
# 6 town (planning authority - absent upstream, left empty on purpose)
# 7 county 8 region 9 country 10 lon 11 lat
COL_REF, COL_MW, COL_TECH, COL_STATUS = 0, 1, 2, 3
COL_NAME, COL_OPERATOR, COL_TOWN, COL_COUNTY = 4, 5, 6, 7
COL_REGION, COL_COUNTRY, COL_LON, COL_LAT = 8, 9, 10, 11
def title_status(s):
"""The spine writes 'Awaiting Construction'; wider-fleet writes 'awaiting construction'.
Same vocabulary, different case. Normalising here keeps one status vocabulary in the
output instead of two that a reader would have to know are the same thing.
"""
return " ".join(w.capitalize() for w in str(s or "").split())
def load_wider(path):
d = json.load(open(path, encoding="utf-8"))
rows = d if isinstance(d, list) else next(
v for v in d.values() if isinstance(v, list) and v and isinstance(v[0], dict))
return rows
def to_spine_row(r):
ll = r.get("ll") or []
if len(ll) != 2:
return None
row = [""] * SPINE_COLUMNS
row[COL_REF] = str(r.get("ref") or "")
row[COL_MW] = "" if r.get("c") in (None, "") else str(r["c"])
row[COL_TECH] = str(r.get("t") or "")
row[COL_STATUS] = title_status(r.get("s"))
row[COL_NAME] = str(r.get("n") or "")
row[COL_OPERATOR] = str(r.get("o") or "")
row[COL_COUNTY] = str(r.get("cty") or "")
row[COL_LON] = str(ll[0])
row[COL_LAT] = str(ll[1])
# town, region, country: intentionally empty. See module docstring.
return row
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--spine", required=True)
ap.add_argument("--wider", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
base = [l.rstrip("\n").split("\t") for l in open(a.spine, encoding="utf-8") if l.strip()]
bad = [r for r in base if len(r) != SPINE_COLUMNS]
if bad:
raise SystemExit(f"spine is not {SPINE_COLUMNS} columns on {len(bad)} row(s); "
"the column contract this adapter targets has moved")
seen = {r[COL_REF] for r in base}
wider = load_wider(a.wider)
added, skipped_dup, skipped_geom = [], 0, 0
for r in wider:
row = to_spine_row(r)
if row is None:
skipped_geom += 1
continue
if row[COL_REF] in seen:
# A ref already in the spine is already measured. Appending it again would
# publish the same project twice under one ref.
skipped_dup += 1
continue
seen.add(row[COL_REF])
added.append(row)
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
with open(a.out, "w", encoding="utf-8", newline="") as h:
for row in base + added:
h.write("\t".join(row) + "\n")
print(f"spine {len(base)} + wider {len(added)} = {len(base)+len(added)} rows -> {a.out}")
if skipped_dup:
print(f" {skipped_dup} wider row(s) already in the spine, not duplicated")
if skipped_geom:
print(f" {skipped_geom} wider row(s) had no usable coordinate pair")
from collections import Counter
print(" added tech:", Counter(r[COL_TECH] for r in added).most_common())
if __name__ == "__main__":
main()