In this section
- Substation Intelligence geodesy · testcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js lines 1830–2529
Substation Intelligence
A JavaScript file in the cartridges folder of Testcode that maps elizabeth line and london underground, using haversine and SHA-256, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.
Set aside from the main view: 99% of its lines are the same as apps/substation-finder/Si/202609060537-substation-intelligence.js (code-generator), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9913 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
- sha256 916bad1b531c94d9acd3bc54f6ed205b467b96e6c1d86beea47a7d66e2f51669
- target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesytestcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js · lines 1830–2529 of 5400 · version 2026-09-06 04:59 (continued from section 453) · Not reached from any entry point (candidate for review) · pattern _zoneDrawRefreshEditor (shared by 3 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 230 functions or classes, including close, open, show, clearValues, validOutline. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json. Out: CSV file gridatlas-polygon-vertices.csv; downloaded file gridatlas-polygon-; downloaded file gridatlas-polygon-vertices.csv; downloaded file gridatlas-; downloaded file globalgrid2050-map-; browser storage (setItem); interactive map; canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- What it achieves
- It saves outline (`saveOutline`), reads outline (`readOutline`) and exports outline (`exportOutline`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 400 kV and 100 MVA. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/202609060459/atlas/cartridges · script
- VEDIC
- SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
- Used by
- mentioned in Standalone (comment link)
- Produces
- close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on
- Defines here
- resolve, at, crossing, describe, legality, startNodes, between, within, seasonsOf, flagsFor, at, makeUnionFind, find, assemble, busOf, componentOf, multiply, solve
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js:1830-2529 · blob fd03f2ae502f2d404cb773df8858c2746ada6401 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
nodeVoltageKv: (name) => voltageOf(nodes.get(name)),
nodeSiteCode: (name) => {
const node = nodes.get(name);
return node ? node.site_code : null;
},
edgesAt: (name) => (byNode.get(name) || [])
.filter((entry) => entry.kind !== 'planned_change'),
nodesOfSite: (code) => {
const wanted = String(code || '').toUpperCase();
const out = [];
for (const node of nodes.values()) {
if (String(node.site_code || '').toUpperCase() === wanted) out.push(node.node);
}
return out.sort();
},
siteByCode: (code) => sitesByCode.get(String(code || '').toUpperCase()) || null,
ratingsOf,
parametersOf
};
}
function resolve(key) {
if (!key) return null;
const wanted = String(key).toUpperCase().trim();
return sitesByCode.get(wanted) || sitesByName.get(wanted) || null;
}
function at(key, options) {
const site = resolve(key);
if (!site) return null;
const wantedKv = options && Number.isFinite(options.voltageKv)
? options.voltageKv : null;
const siteNodes = [];
for (const node of nodes.values()) {
if (node.site_code !== site.code) continue;
const kv = voltageOf(node);
if (wantedKv != null && kv !== wantedKv) continue;
siteNodes.push({ node: node.node, voltage_kv: kv });
}
siteNodes.sort((a, b) => a.node.localeCompare(b.node));
const byVoltage = new Map();
const neighbours = new Map();
for (const entry of siteNodes) {
for (const landing of byNode.get(entry.node) || []) {
const farNode = landing.row[landing.far];
const farSiteCode = siteOf(farNode);
const farSite = farSiteCode ? sitesByCode.get(farSiteCode) : null;
const internal = farSiteCode === site.code;
const key2 = bandKey(entry.voltage_kv);
if (!byVoltage.has(key2)) {
byVoltage.set(key2, { voltage_kv: entry.voltage_kv,
circuits: [], transformers: [], planned_changes: [] });
}
const band = byVoltage.get(key2);
const published = {
from_node: entry.node,
to_node: farNode,
to_site_code: farSiteCode,
to_site_name: farSite ? farSite.name : null,
within_this_site: internal,
transmission_owner: landing.row.transmission_owner || null,
parameters_pct_100mva: parametersOf(landing.row),
ratings_mva: ratingsOf(landing.row)
};
if (landing.kind === 'circuit') {
published.circuit_type = landing.row.circuit_type || null;
if (Number.isFinite(landing.row.ohl_km)) published.ohl_km = landing.row.ohl_km;
if (Number.isFinite(landing.row.cable_km)) published.cable_km = landing.row.cable_km;
band.circuits.push(published);
} else if (landing.kind === 'transformer') {
if (Number.isFinite(landing.row.rating_mva)) published.rating_mva = landing.row.rating_mva;
delete published.ratings_mva;
band.transformers.push(published);
} else {
published.year = landing.row.year || null;
published.status = landing.row.status || null;
published.asset = landing.row.asset || null;
band.planned_changes.push(published);
}
if (landing.kind === 'circuit' && !internal && farSiteCode) {
if (!neighbours.has(farSiteCode)) {
neighbours.set(farSiteCode, {
site_code: farSiteCode,
site_name: farSite ? farSite.name : null,
circuits: 0
});
}
neighbours.get(farSiteCode).circuits += 1;
}
}
}
const voltages = [...byVoltage.entries()]
.sort((a, b) => {
if (a[0] === UNDECLARED) return 1;
if (b[0] === UNDECLARED) return -1;
return Number(b[0]) - Number(a[0]);
})
.map(([, band]) => band);
return {
schema: 'gridatlas.module.network-topology.v1',
source: ACCEPTS,
site: {
code: site.code,
name: site.name,
transmission_owner: site.transmission_owner || null,
voltages_kv: Array.isArray(site.voltages_kv) ? site.voltages_kv.slice() : []
},
requested_voltage_kv: wantedKv,
nodes: siteNodes,
by_voltage: voltages,
neighbours: [...neighbours.values()].sort((a, b) => b.circuits - a.circuits),
counts: {
nodes: siteNodes.length,
circuits: physicalUnits(voltages.flatMap(band => band.circuits)),
transformers: physicalUnits(voltages.flatMap(band => band.transformers)),
planned_changes: physicalUnits(voltages.flatMap(band => band.planned_changes)),
circuit_landings: voltages.reduce((sum, band) => sum + band.circuits.length, 0),
transformer_landings: voltages.reduce((sum, band) => sum + band.transformers.length, 0),
planned_change_landings: voltages.reduce((sum, band) => sum + band.planned_changes.length, 0),
neighbour_sites: neighbours.size
},
counts_are_units: 'A site holds both ends of a transformer and of any '
+ 'internal circuit, so the same branch lands twice. The counts above '
+ 'are physical units; the landing tallies beside them are what the '
+ 'per-voltage lists contain.',
impedance_basis: IMPEDANCE_BASIS,
not_an_assessment: NOT_AN_ASSESSMENT
};
}
return {
schema: 'gridatlas.module.network-topology.v1',
source: ACCEPTS,
counts: {
sites: sitesByCode.size,
nodes: nodes.size,
branch_landings: byNode.size
},
site: resolve,
at,
graph
};
}
NS.networkTopology = Object.freeze({
schema: 'gridatlas.module.network-topology.v1',
accepts: ACCEPTS,
not_an_assessment: NOT_AN_ASSESSMENT,
impedance_basis: IMPEDANCE_BASIS,
index
});
})();
(() => {
const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (NS.electricalDistance) return;
const SCHEMA = 'gridatlas.module.electrical-distance.v1';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';
const NOT_A_DISTANCE =
'Hops are published circuits between two sites, not a distance. A site '
+ 'one hop away may be a hundred kilometres away, and a site ten '
+ 'kilometres away may be on no shared circuit at all.';
const NOT_A_CAPACITY =
'A path existing on the published network says nothing about whether '
+ 'anything can flow along it for a new project. Ratings are the '
+ 'circuit\'s, not a spare allowance, and queue position, committed '
+ 'connections, consent and commercial terms appear in no appendix.';
const IMPEDANCE_CARRIED =
'R, X and B are reproduced on each hop exactly as published, on a '
+ '100 MVA base. They are not added, scaled or combined anywhere in '
+ 'this module. A sum of them would be the beginning of a load flow, '
+ 'which needs a declared model this data does not contain.';
const UNDECLARED = 'undeclared';
function crossing(graph, nearNode, farNode) {
const near = graph.nodeVoltageKv(nearNode);
const far = graph.nodeVoltageKv(farNode);
return {
near_kv: near,
far_kv: far,
both_declared: near != null && far != null,
changes: near != null && far != null && near !== far
};
}
function describe(graph, entry, nearNode) {
const farNode = entry.row[entry.far];
const cross = crossing(graph, nearNode, farNode);
return {
kind: entry.kind,
from_node: nearNode,
to_node: farNode,
from_site_code: graph.nodeSiteCode(nearNode) || null,
to_site_code: graph.nodeSiteCode(farNode) || null,
from_voltage_kv: cross.near_kv,
to_voltage_kv: cross.far_kv,
voltage_changed: cross.changes,
voltage_ratio_kv: entry.kind === 'transformer'
&& typeof entry.row.voltage_ratio_kv === 'string'
? entry.row.voltage_ratio_kv : null,
ratings_mva: graph.ratingsOf(entry.row),
transformer_rating_mva: entry.kind === 'transformer'
&& Number.isFinite(entry.row.rating_mva) ? entry.row.rating_mva : null,
parameters_pct_100mva: graph.parametersOf(entry.row)
};
}
function legality(kind, cross) {
if (!cross.changes) return { legal: true, refusal: null };
if (kind === 'transformer') return { legal: true, refusal: null };
return {
legal: false,
refusal: 'a ' + kind + ' whose two ends carry different declared '
+ 'voltages (' + cross.near_kv + ' kV and ' + cross.far_kv + ' kV); '
+ 'only a transformer may change voltage, so this edge is not walked'
};
}
function startNodes(graph, site, voltageKv) {
const nodes = graph.nodesOfSite(site.code);
if (voltageKv == null) return nodes;
return nodes.filter((name) => graph.nodeVoltageKv(name) === voltageKv);
}
function between(index, fromKey, toKey, options) {
if (!index || typeof index.graph !== 'function') return null;
const graph = index.graph();
if (!graph || graph.schema !== REQUIRES) return null;
const from = index.site(fromKey);
const to = index.site(toKey);
if (!from || !to) return null;
const opts = options || {};
const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
const maxHops = Number.isFinite(opts.maxHops) ? opts.maxHops : 6;
const targets = new Set(graph.nodesOfSite(to.code));
const origins = startNodes(graph, from, voltageKv);
const base = {
schema: SCHEMA,
from: { code: from.code, name: from.name },
to: { code: to.code, name: to.name },
requested_voltage_kv: voltageKv,
max_hops: maxHops,
not_a_distance: NOT_A_DISTANCE,
not_a_capacity: NOT_A_CAPACITY,
impedance_basis: IMPEDANCE_CARRIED
};
if (!origins.length) {
return Object.assign({}, base, {
reached: false,
reason: voltageKv == null
? 'the origin site publishes no nodes in this product'
: 'the origin site publishes no node at ' + voltageKv + ' kV',
hops: null, path: [], refusals: [], ties: 0, explored_nodes: 0
});
}
if (from.code === to.code) {
return Object.assign({}, base, {
reached: true, hops: 0, path: [], refusals: [], ties: 0,
explored_nodes: origins.length,
reason: 'the same site'
});
}
const seen = new Map();
const refusals = [];
let frontier = [];
for (const name of origins.slice().sort()) {
if (targets.has(name)) {
return Object.assign({}, base, {
reached: true, hops: 0, path: [], refusals: [], ties: 0,
explored_nodes: 1,
reason: 'both site codes resolve to the same node'
});
}
seen.set(name, null);
frontier.push(name);
}
for (let depth = 1; depth <= maxHops; depth += 1) {
const next = [];
const arrivals = [];
for (const nearNode of frontier) {
for (const entry of graph.edgesAt(nearNode)) {
const farNode = entry.row[entry.far];
if (!farNode || !graph.has(farNode)) continue;
const cross = crossing(graph, nearNode, farNode);
const verdict = legality(entry.kind, cross);
if (!verdict.legal) {
refusals.push({
at_node: nearNode, to_node: farNode,
kind: entry.kind, reason: verdict.refusal
});
continue;
}
if (seen.has(farNode)) continue;
seen.set(farNode, { via: entry, from: nearNode });
if (targets.has(farNode)) arrivals.push(farNode);
else next.push(farNode);
}
}
if (arrivals.length) {
arrivals.sort();
const path = [];
let cursor = arrivals[0];
while (cursor) {
const step = seen.get(cursor);
if (!step) break;
path.unshift(describe(graph, step.via, step.from));
cursor = step.from;
}
return Object.assign({}, base, {
reached: true,
hops: path.length,
path,
transformers_crossed: path.filter((h) => h.kind === 'transformer').length,
voltage_changes: path.filter((h) => h.voltage_changed).length,
ties: arrivals.length - 1,
refusals,
explored_nodes: seen.size,
arrival_node: arrivals[0]
});
}
if (!next.length) break;
frontier = next.sort();
}
return Object.assign({}, base, {
reached: false,
reason: 'no published path within ' + maxHops + ' hops'
+ (voltageKv == null ? '' : ' from a ' + voltageKv + ' kV node')
+ '; this is a statement about the published network, not about '
+ 'whether the two sites are connected in reality',
hops: null, path: [], refusals, ties: 0, explored_nodes: seen.size
});
}
function within(index, key, options) {
if (!index || typeof index.graph !== 'function') return null;
const graph = index.graph();
if (!graph || graph.schema !== REQUIRES) return null;
const site = index.site(key);
if (!site) return null;
const opts = options || {};
const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
const limit = Number.isFinite(opts.hops) ? opts.hops : 2;
const origins = startNodes(graph, site, voltageKv);
const seen = new Set(origins);
const bySite = new Map();
const refusals = [];
let frontier = origins.slice().sort();
for (let depth = 1; depth <= limit; depth += 1) {
const next = [];
for (const nearNode of frontier) {
for (const entry of graph.edgesAt(nearNode)) {
const farNode = entry.row[entry.far];
if (!farNode || !graph.has(farNode) || seen.has(farNode)) continue;
const cross = crossing(graph, nearNode, farNode);
const verdict = legality(entry.kind, cross);
if (!verdict.legal) {
refusals.push({ at_node: nearNode, to_node: farNode,
kind: entry.kind, reason: verdict.refusal });
continue;
}
seen.add(farNode);
next.push(farNode);
const code = graph.nodeSiteCode(farNode);
if (!code || String(code).toUpperCase() === String(site.code).toUpperCase()) continue;
if (bySite.has(code)) continue;
const far = graph.siteByCode(code);
bySite.set(code, {
code,
name: far ? far.name : null,
hops: depth,
first_node: farNode,
voltage_kv: cross.far_kv,
via: entry.kind
});
}
}
if (!next.length) break;
frontier = next.sort();
}
const sites = [...bySite.values()].sort((a, b) =>
a.hops - b.hops || String(a.code).localeCompare(String(b.code)));
return {
schema: SCHEMA,
site: { code: site.code, name: site.name },
requested_voltage_kv: voltageKv,
hop_limit: limit,
origin_nodes: origins.length,
sites,
counts: {
sites: sites.length,
by_hop: sites.reduce((acc, s) => {
acc[s.hops] = (acc[s.hops] || 0) + 1;
return acc;
}, {})
},
refusals,
not_a_distance: NOT_A_DISTANCE,
not_a_capacity: NOT_A_CAPACITY
};
}
NS.electricalDistance = Object.freeze({
schema: SCHEMA,
requires: REQUIRES,
not_a_distance: NOT_A_DISTANCE,
not_a_capacity: NOT_A_CAPACITY,
impedance_basis: IMPEDANCE_CARRIED,
undeclared: UNDECLARED,
between,
within
});
})();
(() => {
const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (NS.ratingEnvelope) return;
const SCHEMA = 'gridatlas.module.rating-envelope.v1';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';
const SEASONS = Object.freeze(['winter', 'spring', 'summer', 'autumn']);
const FIELD = Object.freeze({
winter: 'winter_mva', spring: 'spring_mva',
summer: 'summer_mva', autumn: 'autumn_mva'
});
const NEVER_SUMMED =
'These are per-circuit thermal ratings under stated seasonal '
+ 'conditions. They are not additive and they are not simultaneous: '
+ 'the sum of the circuits at a site is not a quantity that exists in '
+ 'the network, and this module contains no code that produces one.';
const NOT_A_CAPACITY =
'A rating is what a circuit is rated to carry, not what is free on '
+ 'it. Existing flows, committed connections, queue position, outage '
+ 'conditions and commercial terms decide what a project could use, '
+ 'and no published appendix contains any of them.';
const IMPLAUSIBLE_MVA = 9999;
function seasonsOf(row) {
const published = {};
const absent = [];
for (const season of SEASONS) {
const value = row[FIELD[season]];
if (Number.isFinite(value)) published[season] = value;
else absent.push(season);
}
return { published, absent };
}
function flagsFor(published) {
const flags = [];
for (const [season, value] of Object.entries(published)) {
if (value >= IMPLAUSIBLE_MVA) {
flags.push({
season,
value,
reason: 'at or above ' + IMPLAUSIBLE_MVA + ' MVA, which has the '
+ 'shape of a placeholder rather than a thermal rating; it is '
+ 'reported and excluded from the range below'
});
}
}
return flags;
}
function at(index, key, options) {
if (!index || typeof index.graph !== 'function') return null;
const graph = index.graph();
if (!graph || graph.schema !== REQUIRES) return null;
const site = index.site(key);
if (!site) return null;
const opts = options || {};
const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
const nodes = graph.nodesOfSite(site.code)
.filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);
const circuits = [];
const seen = new Set();
for (const nodeName of nodes) {
for (const entry of graph.edgesAt(nodeName)) {
if (entry.kind !== 'circuit') continue;
const far = entry.row[entry.far];
const id = [nodeName, far].sort().join('|');
if (seen.has(id)) continue;
seen.add(id);
const { published, absent } = seasonsOf(entry.row);
if (!Object.keys(published).length) continue;
circuits.push({
from_node: nodeName,
to_node: far,
to_site_code: graph.nodeSiteCode(far) || null,
voltage_kv: graph.nodeVoltageKv(nodeName),
circuit_type: typeof entry.row.circuit_type === 'string' ? entry.row.circuit_type : null,
ohl_km: Number.isFinite(entry.row.ohl_km) ? entry.row.ohl_km : null,
cable_km: Number.isFinite(entry.row.cable_km) ? entry.row.cable_km : null,
ratings_mva: published,
seasons_not_published: absent,
flags: flagsFor(published),
parameters_pct_100mva: graph.parametersOf(entry.row)
});
}
}
circuits.sort((a, b) => String(a.to_node).localeCompare(String(b.to_node)));
const by_season = {};
for (const season of SEASONS) {
const values = circuits
.filter((c) => Number.isFinite(c.ratings_mva[season])
&& c.ratings_mva[season] < IMPLAUSIBLE_MVA)
.map((c) => c.ratings_mva[season]);
const excluded = circuits
.filter((c) => Number.isFinite(c.ratings_mva[season])
&& c.ratings_mva[season] >= IMPLAUSIBLE_MVA).length;
by_season[season] = values.length
? {
lowest_circuit_mva: Math.min.apply(null, values),
highest_circuit_mva: Math.max.apply(null, values),
circuits: values.length,
excluded_as_implausible: excluded
}
: { circuits: 0, excluded_as_implausible: excluded, published: false };
}
const flagged = circuits.filter((c) => c.flags.length);
const missingSeasons = circuits.filter((c) => c.seasons_not_published.length);
return {
schema: SCHEMA,
site: { code: site.code, name: site.name },
requested_voltage_kv: voltageKv,
scope: voltageKv == null
? 'every voltage at this site; a range across two busbar voltages '
+ 'is a number about neither of them'
: voltageKv + ' kV nodes at this site only',
circuits,
by_season,
counts: {
circuits: circuits.length,
with_a_flagged_value: flagged.length,
with_a_season_not_published: missingSeasons.length
},
never_summed: NEVER_SUMMED,
not_a_capacity: NOT_A_CAPACITY
};
}
NS.ratingEnvelope = Object.freeze({
schema: SCHEMA,
requires: REQUIRES,
seasons: SEASONS,
implausible_mva: IMPLAUSIBLE_MVA,
never_summed: NEVER_SUMMED,
not_a_capacity: NOT_A_CAPACITY,
at
});
})();
(() => {
const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (NS.injectionResponse) return;
const SCHEMA = 'gridatlas.module.injection-response.v2';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';
const BASE_MVA = 100;
const DECLARED_MODEL = Object.freeze({
method: 'linear DC power flow (injection response / power transfer distribution factor)',
equations: 'P = B′ · θ ; branch flow f_ij = (θ_i − θ_j) / x_ij',
base_mva: BASE_MVA,
reactance: 'x = x_pct_100mva / 100, per unit, as published',
resistance: 'not used; the DC approximation neglects series resistance',
shunt_susceptance: 'not used; line charging does not appear in a DC model',
voltages: 'assumed flat at 1.0 per unit; not published and not solved',
angles: 'assumed small, so sin θ ≈ θ',
losses: 'zero by construction; real losses are of order 1-2% and are not represented',
transformer_taps: 'not published, therefore not modelled; transformers are their series reactance only',
contingencies: 'none; this is the intact network',
slack: 'declared explicitly on every answer, never inferred silently'
});
const NOT_A_LOADING =
'This is the response to a NEW injection, not a loading. What is '
+ 'already flowing on these circuits is published nowhere in this '
+ 'product, so the total flow - which is what decides whether a '
+ 'circuit is full - cannot be computed here by anyone.';
const NOT_A_CONNECTION_OFFER =
'A fraction of an injection appearing on a circuit is not permission '
+ 'to use that circuit. Queue position, committed connections, outage '
+ 'conditions, consent and commercial terms decide what a project may '
+ 'connect, and no published appendix contains any of them.';
function makeUnionFind() {
const parent = new Map();
function find(x) {
if (!parent.has(x)) { parent.set(x, x); return x; }
let root = x;
while (parent.get(root) !== root) root = parent.get(root);
let cursor = x;
while (parent.get(cursor) !== cursor) {
const next = parent.get(cursor);
parent.set(cursor, root);
cursor = next;
}
return root;
}
return {
find,
union(a, b) {
const ra = find(a);
const rb = find(b);
if (ra === rb) return false;
parent.set(ra, rb);
return true;
}
};
}
function assemble(graph, nodeNames, { voltageKv, includeTransformers }) {
const inScope = new Set(nodeNames);
const uf = makeUnionFind();
for (const n of nodeNames) uf.find(n);
const branches = [];
const seen = new Set();
let shorted = 0;
let skippedNoReactance = 0;
for (const name of nodeNames) {
for (const entry of graph.edgesAt(name)) {
if (entry.kind === 'transformer' && !includeTransformers) continue;
const far = entry.row[entry.far];
if (!inScope.has(far)) continue;
if (seen.has(entry.row)) continue;
seen.add(entry.row);
const xPct = entry.row.x_pct_100mva;
if (!Number.isFinite(xPct)) { skippedNoReactance += 1; continue; }
if (xPct === 0) {
if (uf.union(name, far)) shorted += 1;
continue;
}
branches.push({
from: name, to: far, kind: entry.kind,
x_pu: xPct / 100,
row: entry.row
});
}
}
const busOf = (name) => uf.find(name);
const buses = [...new Set(nodeNames.map(busOf))].sort();
const busIndex = new Map(buses.map((b, i) => [b, i]));
const edges = [];
for (const b of branches) {
const i = busIndex.get(busOf(b.from));
const j = busIndex.get(busOf(b.to));
if (i === undefined || j === undefined || i === j) continue;
edges.push({ i, j, b: 1 / b.x_pu, meta: b });
}
const comp = makeUnionFind();
for (const b of buses) comp.find(b);
for (const e of edges) comp.union(buses[e.i], buses[e.j]);
const componentOf = (bus) => comp.find(bus);
const componentSizes = new Map();
for (const b of buses) {
const root = componentOf(b);
componentSizes.set(root, (componentSizes.get(root) || 0) + 1);
}
const degree = new Map();
for (const e of edges) {
degree.set(buses[e.i], (degree.get(buses[e.i]) || 0) + 1);
degree.set(buses[e.j], (degree.get(buses[e.j]) || 0) + 1);
}
return {
schema: SCHEMA,
declared_model: DECLARED_MODEL,
componentOf,
componentSize: (bus) => componentSizes.get(componentOf(bus)) || 0,
degreeOf: (bus) => degree.get(bus) || 0,
voltage_kv: voltageKv,
includes_transformers: includeTransformers,
buses, busIndex, busOf, edges,
counts: {
nodes: nodeNames.length,
buses: buses.length,
branches: edges.length,
shorted_zero_reactance: shorted,
skipped_no_published_reactance: skippedNoReactance,
components: componentSizes.size,
largest_component: Math.max(0, ...componentSizes.values())
}
};
}
function multiply(model, x, slackIndex) {
const y = new Float64Array(x.length);
for (const e of model.edges) {
if (e.i === slackIndex || e.j === slackIndex) {
if (e.i !== slackIndex) y[e.i] += e.b * x[e.i];
if (e.j !== slackIndex) y[e.j] += e.b * x[e.j];
continue;
}
const d = x[e.i] - x[e.j];
y[e.i] += e.b * d;
y[e.j] -= e.b * d;
}
return y;
}
function solve(model, injection, slackIndex, tolerance, maxIterations) {
const n = model.buses.length;
const x = new Float64Array(n);
let r = new Float64Array(injection);
r[slackIndex] = 0;
let p = new Float64Array(r);
let rr = 0;
for (let k = 0; k < n; k += 1) rr += r[k] * r[k];
const target = tolerance * tolerance * Math.max(rr, 1e-30);
let iterations = 0;
for (; iterations < maxIterations && rr > target; iterations += 1) {
const ap = multiply(model, p, slackIndex);
let pap = 0;
for (let k = 0; k < n; k += 1) pap += p[k] * ap[k];
if (!(Math.abs(pap) > 1e-30)) break;
const alpha = rr / pap;
let rrNext = 0;
for (let k = 0; k < n; k += 1) {
x[k] += alpha * p[k];
r[k] -= alpha * ap[k];
rrNext += r[k] * r[k];
}
const beta = rrNext / rr;
for (let k = 0; k < n; k += 1) p[k] = r[k] + beta * p[k];
rr = rrNext;
}
x[slackIndex] = 0;