In this section
- Owner Boundary Proof render · gridatlas / tools/proofs/modules/202609012350-owner-boundary.proof.mjs lines 1–349
- Injection Response Proof render · gridatlas / tools/proofs/modules/202609020015-injection-response.proof.mjs lines 1–351
Owner Boundary Proof
A JavaScript module in the proofs folder of GridAtlas that fetches GB transmission network, transformers, 400kV and 220kV.
rendergridatlas / tools/proofs/modules/202609012350-owner-boundary.proof.mjs · lines 1–349 of 349 · version 2026-09-01 23:50 · Not reached from any entry point (candidate for review) · pattern fakeProduct (shared by 2 files)
- What it does
- It fetches GB transmission network, transformers, 400kV and 220kV. Defines check, N, S, fakeProduct, isBoundary. Uses libraries node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name 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: transformers, 400kV, 220kV, 132kV.
- Inputs & outputs
- In: JSON file gb-transmission-network.v1.json. Voltage levels named: 400kV, 220kV, 132kV.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- It is built from the check step (`check`), the fake product helper (`fakeProduct`) and the is boundary helper (`isBoundary`). Two things must hold and are asserted by construction on small products built by hand: an owner is never inferred (a null is unknown, a circuit with an unknown end is undetermined). Its code works with 400 kV and 132 kV.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs, node:path, node:url
- Used by
- run by Local CI (script call)
- Produces
- check, N, S, fakeProduct, isBoundary
- Defines here
- check, N, S, fakeProduct, isBoundary
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609012350-owner-boundary.proof.mjs:1-349 · blob 21beabc502e79d6e99c31ad0a4b2003660f05129 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* Proof for the owner-boundary module.
*
* Two things must hold and are asserted by construction on small products
* built by hand: an owner is never inferred (a null is unknown, a circuit
* with an unknown end is undetermined), and a boundary circuit is named
* with BOTH owners. Then the real product: 62 boundary circuits and 10
* boundary transformers by node owner, 49 nodes with no published owner
* all on placeholder site codes, and seven circuits whose own owner
* matches neither end.
*
* The harness builds a PRODUCT, not a fake index, because node ownership
* is not something the topology graph hands out; the topology module is
* loaded and the fake product goes through it, so the site, node and
* voltage discipline under test is the real one.
*
* A skip is not a pass: if the sibling data-grid-gb checkout is absent
* this FAILS.
*
* node tools/proofs/modules/202609012350-owner-boundary.proof.mjs
*/
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '..', '..', '..');
const PRODUCT = resolve(ROOT, '..', 'data-grid-gb', 'derived', 'gb-transmission-network.v1.json');
let passed = 0;
const failures = [];
function check(name, condition, detail = '') {
if (condition) { passed += 1; console.log(` [PASS] ${name}`); }
else { failures.push(`${name}${detail ? ' - ' + detail : ''}`); console.log(` [FAIL] ${name}${detail ? ' - ' + detail : ''}`); }
}
const TOPOLOGY = 'atlas/modules/202609012245-network-topology.js';
const OWNER = 'atlas/modules/202609012350-owner-boundary.js';
const window = { __GRIDATLAS_MODULES__: {} };
for (const rel of [TOPOLOGY, OWNER]) {
const path = join(ROOT, rel);
if (!existsSync(path)) { console.error(`missing module: ${rel}`); process.exit(1); }
new Function('window', readFileSync(path, 'utf8'))(window);
}
const NS = window.__GRIDATLAS_MODULES__;
const owner = NS.ownerBoundary;
console.log('\nthe module is what it says it is\n');
check('the module registered and froze its surface', !!owner && Object.isFrozen(owner));
check('it names the one product it reads', owner.accepts === 'data-grid-gb.transmission-network.v1');
check('it says ownership is not a counterparty', /not a statement about who a project would contract with/.test(owner.not_a_counterparty));
check('it says an owner is never inferred', /nothing is read from a site name, a node code or a neighbour/.test(owner.never_inferred));
check('it carries the not-an-assessment discipline', /says nothing about whether any project can connect/.test(owner.not_an_assessment));
const source = readFileSync(join(ROOT, OWNER), 'utf8');
const codeOnly = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
check('the module contains no impedance arithmetic',
!/(r_pct|x_pct|b_pct)\w*\s*[+\-*/]/.test(codeOnly)
&& !/[+\-*/]\s*\w*(r_pct|x_pct|b_pct)/.test(codeOnly));
check('the module never reduces a parameter or rating list',
!/parameters[\s\S]{0,80}\.reduce\(/.test(codeOnly) && !/ratings[\s\S]{0,80}\.reduce\(/.test(codeOnly));
check('no arithmetic operator is applied to a rating value', !/_mva\s*[+\-*/]/.test(codeOnly));
check('it never fetches, never renders and never waits',
!/\b(fetch|document|innerHTML|XMLHttpRequest|setTimeout|setInterval|requestAnimationFrame)\b/.test(codeOnly));
check('it never decodes a voltage from a node code',
!/voltage_digit|charAt|\.slice\(4|node_code_convention/.test(codeOnly));
/* An owner may come from a transmission_owner field and nowhere else. The
module must not consult a site NAME, a node NAME or any lookup table of
its own to fill one in. */
check('the only source of an owner is a transmission_owner field',
!/\bsite_name\b|\.site_name\b|\.name\s*[=!]==?|OFFSHORE|ONSHORE/.test(codeOnly)
&& !/(NGET|SHET|SPT|OFTO)\s*[:=]/.test(codeOnly));
check('the owner values are not hard-coded as a list to default to',
!/\[\s*'(NGET|SHET|SPT|OFTO)'/.test(codeOnly));
const denials = (codeOnly.match(/const (?:NOT_[A-Z_]+|NEVER_INFERRED)\s*=[\s\S]*?;/g) || []).join('\n');
const outsideDenials = codeOnly.split(/const (?:NOT_[A-Z_]+|NEVER_INFERRED)\s*=[\s\S]*?;/).join(' ');
check('the denials were found and they deny spare capacity',
denials.length > 200 && /spare allowance/.test(denials));
check('nothing outside the denials speaks of headroom, spare or availability',
!/headroom|spare|available|availability/i.test(outsideDenials));
check('no key or identifier in the module names headroom',
!/\b\w*(headroom|spare_|available_)\w*\b/i.test(codeOnly));
console.log('\nit fails closed\n');
check('an unrecognised schema yields no index', owner.index({ schema: 'something.else.v9' }) === null);
check('a v2 of the same product is refused until it is read for',
owner.index({ schema: 'data-grid-gb.transmission-network.v2', nodes: [] }) === null);
check('null and undefined are refused', owner.index(null) === null && owner.index(undefined) === null);
/* ── behaviour, on products built by hand ───────────────────────────── */
console.log('\nbehaviour, on products built for the edge cases\n');
const N = (node, site_code, voltage_kv, transmission_owner, ok = true) =>
({ node, site_code, site_name: null, transmission_owner, voltage_kv, voltage_consistent_with_site: ok });
const S = (code, name, transmission_owner) => ({ code, name, transmission_owner, voltages_kv: [] });
function fakeProduct({ nodes = [], sites = [], circuits = [], transformers = [], planned_changes = [] }) {
return { schema: 'data-grid-gb.transmission-network.v1', nodes, sites, circuits, transformers, planned_changes };
}
/* A: a boundary circuit, both owners named. */
{
const idx = owner.index(fakeProduct({
nodes: [N('AAA4-', 'AAA', 400, 'SHET'), N('BBB4-', 'BBB', 400, 'SPT'), N('CCC4-', 'CCC', 400, 'SHET')],
sites: [S('AAA', 'ALPHA', 'SHET'), S('BBB', 'BETA', 'SPT'), S('CCC', 'GAMMA', 'SHET')],
circuits: [
{ node_1: 'AAA4-', node_2: 'BBB4-', transmission_owner: 'SPT', winter_mva: 1500, circuit_type: 'OHL', ohl_km: 30, x_pct_100mva: 2.1 },
{ node_1: 'AAA4-', node_2: 'CCC4-', transmission_owner: 'SHET', winter_mva: 1200 }
]
}));
const r = idx.at('AAA');
check('the site reports its own published owner', r.site.transmission_owner === 'SHET');
check('exactly one circuit is a boundary', r.counts.boundary_circuits === 1 && r.boundary_circuits.length === 1);
const b = r.boundary_circuits[0];
check('the boundary circuit names both owners', b.from_owner === 'SHET' && b.to_owner === 'SPT' && b.ends === 'boundary');
check('the boundary circuit names both sites', b.from_site_code === 'AAA' && b.to_site_code === 'BBB' && b.to_site_name === 'BETA');
check('the circuit\'s own owner is carried separately from the owners of its ends',
b.asset_owner === 'SPT' && b.asset_owner_matches_an_end === true);
check('its rating and parameter are carried, unaltered',
b.ratings_mva.winter === 1500 && b.parameters_pct_100mva.x_pct === 2.1 && b.ohl_km === 30);
check('the internal circuit is not listed as a boundary', !r.boundary_circuits.some(c => c.to_node === 'CCC4-'));
check('assets are counted per owner at the site: one SPT circuit and one SHET circuit',
r.by_voltage[0].by_owner.SPT.circuits === 1 && r.by_voltage[0].by_owner.SHET.circuits === 1);
check('the node is counted under its own owner', r.by_voltage[0].by_owner.SHET.nodes === 1);
check('both owners are listed as present', r.owners_present.join(',') === 'SHET,SPT');
check('the far site sees the same boundary from its side',
idx.at('BBB').boundary_circuits[0].from_owner === 'SPT' && idx.at('BBB').boundary_circuits[0].to_owner === 'SHET');
check('the answer carries the counterparty denial', /not a statement about who a project would contract with/.test(r.not_a_counterparty));
}
/* B: a null owner is unknown, never guessed - not from the site, not from
the far end, not from the circuit. */
{
const idx = owner.index(fakeProduct({
nodes: [N('AAA4-', 'AAA', 400, 'NGET'), N('OFFSHORE 220KV-1', 'OFFS', null, null, false)],
sites: [S('AAA', 'ALPHA', 'NGET')],
circuits: [{ node_1: 'AAA4-', node_2: 'OFFSHORE 220KV-1', transmission_owner: 'OFTO', winter_mva: 400 }]
}));
const r = idx.at('AAA');
check('a circuit to a node with no published owner is undetermined, not a boundary',
r.counts.boundary_circuits === 0 && r.counts.undetermined === 1);
const u = r.undetermined[0];
check('the unknown end is reported as unknown, not as OFTO from the circuit and not as NGET from the site',
u.to_owner === 'unknown' && u.ends === 'undetermined');
check('whether the asset owner matches an end is null when an end is unknown',
u.asset_owner_matches_an_end === null);
check('the asset is still counted under its own published owner', r.by_voltage[0].by_owner.OFTO.circuits === 1);
check('the far node with no site is carried with its code and no invented name',
u.to_site_code === 'OFFS' && u.to_site_name === null);
check('its voltage is undeclared, not decoded from "220KV" in the node name', u.to_voltage_kv === null);
/* and a null owner ON the queried site's own node */
const idx2 = owner.index(fakeProduct({
nodes: [N('AAA4-', 'AAA', 400, null)],
sites: [S('AAA', 'ALPHA', 'NGET')]
}));
const r2 = idx2.at('AAA');
check('a node with no published owner is unknown even when its site publishes one',
r2.nodes[0].transmission_owner === 'unknown' && r2.counts.nodes_with_unknown_owner === 1
&& r2.by_voltage[0].by_owner.unknown.nodes === 1);
}
/* C: an asset whose owner matches neither end. */
{
const idx = owner.index(fakeProduct({
nodes: [N('HUNN2A', 'HUNN', 275, 'SHET'), N('HUNN2C', 'HUNN', 275, 'SHET')],
sites: [S('HUNN', 'HUNTERSTON', 'SHET')],
circuits: [{ node_1: 'HUNN2A', node_2: 'HUNN2C', transmission_owner: 'SPT' }]
}));
const r = idx.at('HUNN');
check('an internal circuit between two SHET nodes is not a boundary', r.counts.boundary_circuits === 0);
check('but its own owner differing from both ends is reported as exactly that',
r.counts.asset_owner_differs_from_both_ends === 1
&& r.asset_owner_differs_from_both_ends[0].asset_owner === 'SPT'
&& r.asset_owner_differs_from_both_ends[0].asset_owner_matches_an_end === false);
check('the circuit is counted under SPT, its published owner, not under the site\'s',
r.by_voltage[0].by_owner.SPT.circuits === 1 && !r.by_voltage[0].by_owner.SHET.circuits);
}
/* D: per voltage, never across; a boundary transformer. */
{
const idx = owner.index(fakeProduct({
nodes: [N('AAA4-', 'AAA', 400, 'NGET'), N('AAA1-', 'AAA', 132, 'NGET'), N('AAA2-', 'AAA', 275, 'NGET', false),
N('BBB4-', 'BBB', 400, 'SPT'), N('CCC1-', 'CCC', 132, 'NGET'), N('DDD1-', 'DDD', 132, 'OFTO')],
sites: [S('AAA', 'ALPHA', 'NGET'), S('BBB', 'BETA', 'SPT'), S('CCC', 'GAMMA', 'NGET'), S('DDD', 'DELTA', 'OFTO')],
circuits: [
{ node_1: 'AAA4-', node_2: 'BBB4-', transmission_owner: 'NGET' },
{ node_1: 'AAA1-', node_2: 'CCC1-', transmission_owner: 'NGET' }
],
transformers: [
{ node_1: 'AAA4-', node_2: 'AAA1-', transmission_owner: 'NGET', rating_mva: 240 },
{ node_1: 'AAA1-', node_2: 'DDD1-', transmission_owner: 'OFTO', rating_mva: 90, voltage_ratio_kv: '132/33' }
]
}));
const all = idx.at('AAA');
const at400 = idx.at('AAA', { voltageKv: 400 });
const at132 = idx.at('AAA', { voltageKv: 132 });
check('voltages are bands, highest first, undeclared last',
all.by_voltage.map(b => b.voltage_kv).join(',') === '400,132,');
/* the internal 400/132 transformer is met first at AAA1- in sorted
node order, so it is counted in the 132 kV band and not the 400 */
check('the 400 kV band counts one circuit and no transformer, the 132 kV band one circuit and two transformers',
all.by_voltage[0].circuits === 1 && all.by_voltage[0].transformers === 0
&& all.by_voltage[1].circuits === 1 && all.by_voltage[1].transformers === 2);
check('an internal transformer is counted once, under the voltage it was first met at',
all.counts.transformers === 2);
check('scoped to 400 kV, only the 400 kV boundary is reported',
at400.counts.boundary_circuits === 1 && at400.boundary_circuits[0].to_owner === 'SPT'
&& at400.counts.boundary_transformers === 0);
check('scoped to 132 kV, the boundary transformer to OFTO is reported with both owners',
at132.counts.boundary_transformers === 1 && at132.boundary_transformers[0].from_owner === 'NGET'
&& at132.boundary_transformers[0].to_owner === 'OFTO' && at132.boundary_transformers[0].rating_mva === 90
&& at132.boundary_transformers[0].voltage_ratio_kv === '132/33');
check('a node the site does not vouch for is counted as undeclared, never as 275',
all.by_voltage[2].voltage_kv === null && all.by_voltage[2].nodes === 1
&& idx.at('AAA', { voltageKv: 275 }).counts.nodes === 0);
check('the unscoped scope says no count spans two voltages', /no count here spans two voltages/.test(all.scope));
check('an unknown site is null', idx.at('ZZZ') === null);
const list = idx.boundaries();
check('the product-wide list names each boundary branch once with both owners',
list.counts.boundary_circuits === 1 && list.counts.boundary_transformers === 1
&& list.counts.by_owner_pair['NGET/SPT'] === 1 && list.counts.by_owner_pair['NGET/OFTO'] === 1);
}
/* ── the real payload ────────────────────────────────────────────────── */
console.log('\nthe published network, four owners\n');
if (!existsSync(PRODUCT)) {
console.error(`\nFAILED: the published product is not at ${PRODUCT}.`);
console.error('A skip is not a pass. Check out Ventusltd/data-grid-gb beside this repository;');
console.error('this proof does not report success on half of itself.');
process.exit(1);
}
const product = JSON.parse(readFileSync(PRODUCT, 'utf8'));
const idx = owner.index(product);
check('the module accepts the published schema', !!idx);
check('the index counts every published node', idx.counts.nodes === 2679);
check('the four owners and unknown are the only node owner values',
Object.keys(idx.counts.nodes_by_owner).sort().join(',') === 'NGET,OFTO,SHET,SPT,unknown');
check('49 nodes publish no owner', idx.counts.nodes_by_owner.unknown === 49, String(idx.counts.nodes_by_owner.unknown));
/* The 49 are all on codes the product does not list as sites, so no
listed site can ever have a node of unknown owner. Verified on the
product, then asserted through the module. */
const siteCodes = new Set(product.sites.map(s => s.code));
const nullNodes = product.nodes.filter(n => !n.transmission_owner);
check('every unowned node is on a code the product does not list as a site',
nullNodes.every(n => !siteCodes.has(n.site_code)),
[...new Set(nullNodes.map(n => n.site_code))].join(','));
/* Independent recount of the boundary branches. */
const nodeOwner = new Map(product.nodes.map(n => [n.node, n.transmission_owner || null]));
const isBoundary = (r) => {
const a = nodeOwner.get(r.node_1), b = nodeOwner.get(r.node_2);
return a && b && a !== b;
};
const expectedCircuits = product.circuits.filter(isBoundary).length;
const expectedTransformers = product.transformers.filter(isBoundary).length;
const list = idx.boundaries();
check(`the module finds every boundary circuit (${list.counts.boundary_circuits})`,
list.counts.boundary_circuits === expectedCircuits, `${list.counts.boundary_circuits} vs ${expectedCircuits}`);
check(`the module finds every boundary transformer (${list.counts.boundary_transformers})`,
list.counts.boundary_transformers === expectedTransformers, `${list.counts.boundary_transformers} vs ${expectedTransformers}`);
check('the survey figure of 62 boundary circuits holds', expectedCircuits === 62, String(expectedCircuits));
check('every boundary branch names two different published owners, neither unknown',
list.branches.every(b => b.from_owner !== b.to_owner && b.from_owner !== 'unknown' && b.to_owner !== 'unknown'));
check('no existing branch has an undetermined end on the real network',
product.circuits.every(r => nodeOwner.get(r.node_1) && nodeOwner.get(r.node_2))
&& product.transformers.every(r => nodeOwner.get(r.node_1) && nodeOwner.get(r.node_2)));
check('the owner pairs are the seams one would expect: SHET/SPT, NGET/SPT, and each with OFTO',
['SHET/SPT', 'NGET/SPT', 'NGET/OFTO', 'OFTO/SHET'].every(p => list.counts.by_owner_pair[p] > 0),
JSON.stringify(list.counts.by_owner_pair));
check('there is no NGET/SHET seam - they do not share a border',
!list.counts.by_owner_pair['NGET/SHET']);
/* Each boundary branch must be visible from BOTH of its sites. */
let bothSides = 0;
let oneSided = [];
for (const b of list.branches) {
const sides = [b.from_site_code, b.to_site_code].filter(c => siteCodes.has(c));
let seen = 0;
for (const code of sides) {
const r = idx.at(code);
const pool = b.kind === 'circuit' ? r.boundary_circuits : r.boundary_transformers;
if (pool.some(x => [x.from_node, x.to_node].sort().join('|') === [b.from_node, b.to_node].sort().join('|'))) seen += 1;
}
if (seen === sides.length) bothSides += 1; else oneSided.push(`${b.from_node}-${b.to_node}`);
}
check(`every boundary branch is reported from every listed site it touches (${bothSides} of ${list.branches.length})`,
oneSided.length === 0, oneSided.join(','));
/* The seven circuits whose own owner matches neither end. */
const neither = product.circuits.filter(r => {
const a = nodeOwner.get(r.node_1), b = nodeOwner.get(r.node_2);
return a && b && r.transmission_owner !== a && r.transmission_owner !== b;
});
check(`the product publishes circuits whose owner matches neither end (${neither.length})`, neither.length === 7, String(neither.length));
const hunn = idx.at('HUNN');
check('Hunterston reports them as asset-owner-differs, not as boundaries',
!!hunn && hunn.counts.asset_owner_differs_from_both_ends >= 2
&& hunn.asset_owner_differs_from_both_ends.every(c => c.asset_owner === 'SPT' && c.from_owner === 'SHET' && c.to_owner === 'SHET'));
/* One real seam, in full. */
const bonb = idx.at('BONB');
check('Bonnybridge is a SHET site with a boundary circuit to an SPT node',
!!bonb && bonb.site.transmission_owner === 'SHET' && bonb.counts.boundary_circuits > 0
&& bonb.boundary_circuits.every(c => c.from_owner === 'SHET' && c.to_owner === 'SPT'));
check('its boundary circuits carry their ratings and parameters as published',
bonb.boundary_circuits.every(c => c.ratings_mva && Number.isFinite(c.ratings_mva.winter) && c.parameters_pct_100mva));
check('no boundary circuit at Bonnybridge mixes voltages: both ends declared and equal, or an end undeclared',
bonb.boundary_circuits.every(c => c.from_voltage_kv === null || c.to_voltage_kv === null || c.from_voltage_kv === c.to_voltage_kv));
check('the 400 kV scope reports only 400 kV nodes and their branches',
idx.at('BONB', { voltageKv: 400 }).nodes.every(n => n.voltage_kv === 400));
/* A wholly internal NGET site has no boundary at all. */
const wbur = idx.at('WBUR');
check('West Burton is NGET throughout with no boundary branch',
wbur.owners_present.join(',') === 'NGET' && wbur.counts.boundary_circuits === 0 && wbur.counts.boundary_transformers === 0);
/* Per-voltage counts reconcile with the topology view, which counts the
same branches under the same voltages; a disagreement here would be
two implementations of "what lands at this voltage". */
const topoWbur = NS.networkTopology.index(product).at('WBUR', { voltageKv: 400 });
const own400 = idx.at('WBUR', { voltageKv: 400 });
/* The topology view counts LANDINGS, so a circuit between two 400 kV
nodes of the same site appears twice there; this module counts each
asset once. The reconciliation is on distinct node pairs. */
const topoPairs = new Set(topoWbur.by_voltage.flatMap(b => b.circuits)
.map(c => [c.from_node, c.to_node].sort().join('|')));
check('the 400 kV circuits at West Burton are the distinct pairs the topology view lands on',
own400.counts.circuits === topoPairs.size && own400.counts.circuits <= topoWbur.counts.circuits,
`${own400.counts.circuits} vs ${topoPairs.size} pairs / ${topoWbur.counts.circuits} landings`);
check('no key in a site answer names headroom, spare capacity or availability',
!JSON.stringify(bonb).replace(/"not_an_assessment":"[^"]*"/, '').match(/headroom|spare|availab/i));
check('the answer carries no kilometre total and no summed rating',
!/total|_sum\b/i.test(JSON.stringify(bonb)));
console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
console.log('FAILURES');
for (const f of failures) console.log(` ${f}`);
process.exit(1);
}
console.log('every owner is the published one, every boundary names both of them, and');
console.log('none of it says who anyone would contract with.');Injection Response Proof
A JavaScript module in the proofs folder of GridAtlas that reads GB transmission network and 400kV.
rendergridatlas / tools/proofs/modules/202609020015-injection-response.proof.mjs · lines 1–351 of 429 · version 2026-09-02 00:15 · Not reached from any entry point (candidate for review) · pattern graphOf (shared by 2 files)
- What it does
- It loads GB transmission network and 400kV. Defines 6 functions or classes, including check, close, graphOf, X, shareOn. Uses libraries node:fs, node:path, node:url. 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 '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: 400kV.
- Inputs & outputs
- In: JSON file gb-transmission-network.v1.json. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- It is built from the check step (`check`), the close step (`close`) and the graph of helper (`graphOf`). Codex's standing condition on any load-flow work is validation against a trusted solver. Its code works with 400 kV, 100 MW and 17.97 MW.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs, node:path, node:url
- Used by
- run by Local CI (script call)
- Produces
- check, close, graphOf, X, shareOn, add
- Defines here
- check, close, graphOf, X, shareOn, add
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609020015-injection-response.proof.mjs:1-351 · blob e04107f557b526e5b8f14c87f8854c4a3228cf0d · 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
/**
* Proof for the injection-response module.
*
* THE VALIDATION PROBLEM, AND HOW IT IS ANSWERED HERE
* ---------------------------------------------------
* Codex's standing condition on any load-flow work is validation against a
* trusted solver. There is no commercial solver in this estate, and
* claiming one had been used would be worse than having none.
*
* So the model is validated the other way that is actually rigorous:
* against networks whose answers are EXACT BY HAND. A DC injection
* response has closed-form solutions on small networks - parallel paths
* divide inversely as their reactances, a series path carries everything,
* a symmetric ring divides two-thirds and one-third - and these are not
* approximations to compare loosely against. They are the physics the
* model claims to implement, and a solver that gets them wrong is wrong.
*
* Every analytic case below is asserted to 1e-9. Then the same solver is
* run on the real published 400 kV network, where the answer is not known
* in advance but Kirchhoff's law still must hold at every bus, and it is
* checked at all of them rather than at the one the module reports.
*
* A skip is not a pass: absent the published product, this FAILS.
*
* WHAT THIS ADDS OVER THE FIRST PROOF
* -----------------------------------
* The first proof passed while the production caller was broken, because
* it tested a case production never takes: it chose a CONNECTED distant
* slack, and the live caller chose the first lexicographic bus. Codex
* found that on review. So the cases below include the production path
* itself, run on the real product, and the two shapes that were wrong:
* a cross-component transfer, and parallel circuits sharing a reactance.
*
* node tools/proofs/modules/202609020015-injection-response.proof.mjs
*/
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '..', '..', '..');
const PRODUCT = resolve(ROOT, '..', 'data-grid-gb', 'derived', 'gb-transmission-network.v1.json');
let passed = 0;
const failures = [];
function check(name, condition, detail = '') {
if (condition) { passed += 1; console.log(` [PASS] ${name}`); }
else { failures.push(`${name}${detail ? ' - ' + detail : ''}`); console.log(` [FAIL] ${name}${detail ? ' - ' + detail : ''}`); }
}
const close = (a, b, tol = 1e-9) => Number.isFinite(a) && Math.abs(a - b) < tol;
const TOPOLOGY = 'atlas/modules/202609012245-network-topology.js';
const FLOW = 'atlas/modules/202609020015-injection-response.js';
const window = { __GRIDATLAS_MODULES__: {} };
for (const rel of [TOPOLOGY, FLOW]) {
const path = join(ROOT, rel);
if (!existsSync(path)) { console.error(`missing module: ${rel}`); process.exit(1); }
new Function('window', readFileSync(path, 'utf8'))(window);
}
const NS = window.__GRIDATLAS_MODULES__;
const topology = NS.networkTopology;
const flow = NS.injectionResponse;
console.log('\nthe model declares itself\n');
check('the module registered', !!flow);
const D = flow.declared_model;
check('it names its method as a DC injection response, not a load flow',
/DC power flow/.test(D.method) && /distribution factor/.test(D.method));
check('it publishes its equations', /P = B′ · θ/.test(D.equations) && /θ_i − θ_j/.test(D.equations));
check('it declares the base it works on', D.base_mva === 100);
check('it states that resistance is not used', /not used/.test(D.resistance));
check('it states that shunt susceptance is not used', /not used/.test(D.shunt_susceptance));
check('it states the flat-voltage assumption', /flat at 1\.0/.test(D.voltages));
check('it states the small-angle assumption', /small/.test(D.angles));
check('it states that losses are zero by construction', /zero by construction/.test(D.losses));
check('it states that taps are not published and not modelled',
/not published/.test(D.transformer_taps));
check('it states that no contingency is modelled', /none/.test(D.contingencies));
check('it refuses to be read as a loading',
/not a loading/i.test(flow.not_a_loading) && /published nowhere/.test(flow.not_a_loading));
check('it refuses to be read as a connection offer',
/not permission/.test(flow.not_a_connection_offer));
/* The rule this module operates under: it MAY use x, and it must still
never use r or b, because the declared model says it does not. */
const source = readFileSync(join(ROOT, FLOW), 'utf8');
const codeOnly = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
check('the module never reads the resistance field', !/r_pct_100mva/.test(codeOnly));
check('the module never reads the susceptance field', !/b_pct_100mva/.test(codeOnly));
check('the module does read the reactance field, which is what it declares',
/x_pct_100mva/.test(codeOnly));
console.log('\nvalidation against networks whose answers are exact by hand\n');
/* A tiny graph harness in the shape the module requires. */
function graphOf(nodes, edges) {
const byNode = new Map();
for (const e of edges) {
for (const [near, far] of [['node_1', 'node_2'], ['node_2', 'node_1']]) {
const n = e.row[near];
if (!byNode.has(n)) byNode.set(n, []);
byNode.get(n).push({ kind: e.kind || 'circuit', row: e.row, near, far });
}
}
return {
schema: 'gridatlas.module.network-topology.graph.v1',
has: (n) => nodes.includes(n),
nodeVoltageKv: () => 400,
nodeSiteCode: (n) => n.slice(0, 4),
edgesAt: (n) => byNode.get(n) || [],
nodesOfSite: () => nodes.slice(),
siteByCode: () => null,
ratingsOf: () => null,
parametersOf: () => null
};
}
const X = (node_1, node_2, x, extra = {}) =>
({ kind: 'circuit', row: Object.assign({ node_1, node_2, x_pct_100mva: x }, extra) });
const shareOn = (result, a, b) => {
const hit = result.branches.find(f =>
(f.from_node === a && f.to_node === b) || (f.from_node === b && f.to_node === a));
if (!hit) return 0;
return (f => f.from_node === a ? f.share_of_injection : -f.share_of_injection)(hit);
};
/* CASE 1 - a single branch carries the whole transfer, whatever its x. */
{
const g = graphOf(['A', 'B'], [X('A', 'B', 7.3)]);
const m = flow.assemble(g, ['A', 'B'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 500, minimumShare: 0 });
check('one branch between injection and slack carries 100% of it',
close(shareOn(r, 'A', 'B'), 1));
check('and carries it in MW, on the declared base', close(r.branches[0].flow_mw, 500, 1e-7));
check('the reactance does not change a single-path answer',
close(shareOn(r, 'A', 'B'), 1));
check('Kirchhoff at the injection is satisfied exactly', r.validation.passes);
check('the solve reports that it converged', r.convergence.converged);
}
/* CASE 2 - two parallel branches divide inversely as their reactances.
x1 = 1, x2 = 2 => 2/3 on the first, 1/3 on the second. Exact. */
{
const g = graphOf(['A', 'B'], [X('A', 'B', 100), X('A', 'B', 200)]);
const m = flow.assemble(g, ['A', 'B'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 300, minimumShare: 0 });
const shares = r.branches.map(b => b.share_of_injection).sort((a, b) => b - a);
check('two parallel paths divide inversely as their reactances (2/3, 1/3)',
close(shares[0], 2 / 3) && close(shares[1], 1 / 3),
shares.map(s => s.toFixed(6)).join(' '));
check('the two shares sum to exactly one', close(shares[0] + shares[1], 1));
check('in MW that is 200 and 100 of a 300 MW injection',
close(r.branches.find(b => close(b.share_of_injection, 2 / 3)).flow_mw, 200, 1e-6));
}
/* CASE 3 - the textbook symmetric ring. Three equal branches A-B, B-C,
C-A. Inject at A, withdraw at B. The direct path A-B is one branch of
reactance x; the indirect path A-C-B is two, so 2x. Inversely as
reactance: 2/3 direct, 1/3 indirect. */
{
const g = graphOf(['A', 'B', 'C'], [X('A', 'B', 50), X('B', 'C', 50), X('C', 'A', 50)]);
const m = flow.assemble(g, ['A', 'B', 'C'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 90, minimumShare: 0 });
check('a symmetric ring sends 2/3 the direct way', close(shareOn(r, 'A', 'B'), 2 / 3));
check('and 1/3 the long way round', close(shareOn(r, 'A', 'C'), 1 / 3));
check('the long way round carries the same share on its second leg',
close(shareOn(r, 'C', 'B'), 1 / 3));
check('a ring puts flow on a branch that touches neither end of the transfer',
Math.abs(shareOn(r, 'C', 'B')) > 0.3);
}
/* CASE 4 - series branches each carry the whole transfer. */
{
const g = graphOf(['A', 'M', 'B'], [X('A', 'M', 30), X('M', 'B', 70)]);
const m = flow.assemble(g, ['A', 'M', 'B'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 250, minimumShare: 0 });
check('every branch in series carries the entire transfer',
close(shareOn(r, 'A', 'M'), 1) && close(shareOn(r, 'M', 'B'), 1));
}
/* CASE 5 - reciprocity. Reversing the transfer reverses every flow and
changes nothing else. This is a property of the linear model, and a
solver that fails it has a sign or an indexing error. */
{
const g = graphOf(['A', 'B', 'C'], [X('A', 'B', 50), X('B', 'C', 30), X('C', 'A', 20)]);
const m = flow.assemble(g, ['A', 'B', 'C'], { voltageKv: 400, includeTransformers: false });
const fwd = flow.respond(m, { atNode: 'A', slackNode: 'C', mw: 100, minimumShare: 0 });
const rev = flow.respond(m, { atNode: 'C', slackNode: 'A', mw: 100, minimumShare: 0 });
let mirrored = true;
for (const f of fwd.branches) {
const back = rev.branches.find(b => b.from_node === f.from_node && b.to_node === f.to_node);
if (!back || !close(back.share_of_injection, -f.share_of_injection, 1e-9)) mirrored = false;
}
check('reversing the transfer reverses every branch flow exactly', mirrored);
}
/* CASE 6 - a zero-reactance branch is a short, not a small reactance. */
{
const g = graphOf(['A', 'A2', 'B'], [X('A', 'A2', 0), X('A2', 'B', 40)]);
const m = flow.assemble(g, ['A', 'A2', 'B'], { voltageKv: 400, includeTransformers: false });
check('the zero-reactance branch was shorted, not modelled',
m.counts.shorted_zero_reactance === 1 && m.counts.branches === 1);
check('the two shorted nodes became one bus', m.counts.buses === 2 && m.counts.nodes === 3);
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 100, minimumShare: 0 });
check('injecting at either end of a short gives the same answer',
close(shareOn(r, 'A2', 'B'), 1));
const r2 = flow.respond(m, { atNode: 'A2', slackNode: 'B', mw: 100, minimumShare: 0 });
check('because they are the same bus', close(shareOn(r2, 'A2', 'B'), 1));
}
/* CASE 7 - injecting and withdrawing at the same bus is not a transfer. */
{
const g = graphOf(['A', 'A2', 'B'], [X('A', 'A2', 0), X('A2', 'B', 40)]);
const m = flow.assemble(g, ['A', 'A2', 'B'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'A2', mw: 100 });
check('a transfer within one bus is refused and explained',
r.same_bus === true && r.branches.length === 0 && /no transfer to distribute/.test(r.reason));
}
/* CASE 8 - a branch with no published reactance is skipped and counted,
never given a default. */
{
const g = graphOf(['A', 'B', 'C'], [X('A', 'B', 50), { kind: 'circuit', row: { node_1: 'B', node_2: 'C' } }]);
const m = flow.assemble(g, ['A', 'B', 'C'], { voltageKv: 400, includeTransformers: false });
check('a branch with no published reactance is not invented',
m.counts.skipped_no_published_reactance === 1 && m.counts.branches === 1);
}
/* CASE 9 - REGRESSION, Codex 202609020030 finding 2. Two genuine parallel
circuits that publish the SAME reactance are two circuits. Collapsing
them into one understated the network on 45 published rows. */
{
const g = graphOf(['A', 'B'], [X('A', 'B', 100), X('A', 'B', 100)]);
const m = flow.assemble(g, ['A', 'B'], { voltageKv: 400, includeTransformers: false });
check('two parallel circuits of EQUAL reactance are two edges, not one',
m.counts.branches === 2, JSON.stringify(m.counts));
const r = flow.respond(m, { atNode: 'A', slackNode: 'B', mw: 200, minimumShare: 0 });
check('and they share the transfer equally, half each',
r.branches.length === 2
&& close(r.branches[0].share_of_injection, 0.5)
&& close(r.branches[1].share_of_injection, 0.5));
check('each carries 100 MW of a 200 MW transfer, not 200',
r.branches.every(b => close(b.flow_mw, 100, 1e-9)));
}
/* CASE 10 - REGRESSION, finding 1. A transfer between two components is
refused BEFORE the solver is asked, because the solver answers anyway. */
{
const g = graphOf(['A', 'B', 'C', 'D'],
[X('A', 'B', 50), X('C', 'D', 50)]);
const m = flow.assemble(g, ['A', 'B', 'C', 'D'], { voltageKv: 400, includeTransformers: false });
check('the model counts its connected components', m.counts.components === 2,
String(m.counts.components));
const r = flow.respond(m, { atNode: 'A', slackNode: 'D', mw: 100, minimumShare: 0 });
check('a cross-component transfer is refused, not solved',
r.publishable === false && r.branches.length === 0);
check('and the refusal says why, naming components',
/different connected components/.test(r.reason));
check('this is the exact shape that returned passes:true before',
r.publishable === false);
}
/* CASE 11 - acceptance is global. A solve that has not converged must not
be publishable even if the injection bus happens to balance. */
{
const g = graphOf(['A', 'B', 'C'], [X('A', 'B', 50), X('B', 'C', 50)]);
const m = flow.assemble(g, ['A', 'B', 'C'], { voltageKv: 400, includeTransformers: false });
const r = flow.respond(m, { atNode: 'A', slackNode: 'C', mw: 100, minimumShare: 0 });
check('a good solve reports available', r.publishable === true);
check('acceptance names all three conditions it checks',
/converged/.test(r.validation.what_it_checks)
&& /every other bus/.test(r.validation.what_it_checks));
check('the worst bus error is reported, not just the injection bus',
Number.isFinite(r.validation.worst_bus_error_mw));
check('the answer names the component it was solved in',
r.component && Number.isFinite(r.component.buses_in_component));
}
/* CASE 12 - the sink rule is stated, not implicit. */
{
const g = graphOf(['A', 'B', 'C'], [X('A', 'B', 50), X('B', 'C', 50)]);
const m = flow.assemble(g, ['A', 'B', 'C'], { voltageKv: 400, includeTransformers: false });
const sink = flow.sinkFor(m, 'A');
check('the declared sink is the most connected bus in the same component',
sink === 'B', String(sink));
check('an isolated bus has no sink, and that is an answer',
flow.sinkFor(flow.assemble(graphOf(['Z'], []), ['Z'],
{ voltageKv: 400, includeTransformers: false }), 'Z') === null);
check('the rule is published so a reader can see it',
/most connected bus in the SAME component/.test(flow.sink_rule));
}
console.log('\nthe real published 400 kV network\n');
if (!existsSync(PRODUCT)) {
console.error(`\nFAILED: the published product is not at ${PRODUCT}.`);
console.error('A skip is not a pass. Check out Ventusltd/data-grid-gb beside this repository.');
process.exit(1);
}
const product = JSON.parse(readFileSync(PRODUCT, 'utf8'));
const index = topology.index(product);
check('the topology module accepts the published schema', !!index);
const graph = index.graph();
const nodes400 = (product.nodes || [])
.filter(n => n.voltage_consistent_with_site === true && n.voltage_kv === 400)
.map(n => n.node);
check(`the product publishes 400 kV nodes whose site vouches for them (${nodes400.length})`,
nodes400.length > 100, `${nodes400.length}`);
const model = flow.assemble(graph, nodes400, { voltageKv: 400, includeTransformers: false });
check('a 400 kV model assembles', !!model && model.counts.branches > 50,
JSON.stringify(model.counts));
console.log(` model: ${JSON.stringify(model.counts)}`);
/* West Burton to a distant slack, on the real network. */
const wbur = nodes400.find(n => n.startsWith('WBUR'));
const slack = nodes400.find(n => n.startsWith('SUND') || n.startsWith('PELH'))
|| nodes400[nodes400.length - 1];
check('West Burton has a 400 kV node in the model', !!wbur, String(wbur));
const answer = flow.respond(model, { atNode: wbur, slackNode: slack, mw: 500, minimumShare: 0.01 });
check('the solve converged on the real network', answer.convergence.converged,
`residual ${answer.convergence.residual}`);
check('Kirchhoff at the injection bus holds to 1e-6',
answer.validation.passes, `error ${answer.validation.kirchhoff_error}`);
check('the answer names its slack, because a transfer has two ends',
answer.slack_node === slack && !!answer.slack_node);
check('some circuits carry a meaningful share of the injection',
answer.branches.length > 0, `${answer.branches.length}`);
check('no branch carries more than the whole injection',
answer.branches.every(b => Math.abs(b.share_of_injection) <= 1 + 1e-9),
answer.branches.map(b => b.share_of_injection.toFixed(3)).slice(0, 5).join(' '));
/* Kirchhoff at EVERY bus, not just the one the module reports. This is
the check that would catch an indexing error the reported one misses. */
{
/* Keyed by BUS, not by node. Five pairs of 400 kV nodes are joined by a
zero-reactance branch and shorted into one bus each; a flow reported
at one member node belongs to the whole bus. Summing per node instead
showed a false 17.97 MW imbalance at ELST41 - which is the shorted
half of its bus, not a solver error. The law is per bus, so the check
must be too. */
const netAt = new Map();
const add = (node, mw) => {
const bus = model.busOf(node);
netAt.set(bus, (netAt.get(bus) || 0) + mw);
};