GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Si

Substation Intelligence (part 3)

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of JavaScript from code-generator, in 1 file. Topic: Grid network and substations. Section 278 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Substation Intelligence geodesy · code-generator / apps/substation-finder/Si/202609060537-substation-intelligence.js lines 2041–2740

Substation Intelligence

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

geodesycode-generator / apps/substation-finder/Si/202609060537-substation-intelligence.js · lines 2041–2740 of 5427 · version 2026-09-06 05:37 (continued from section 275) · Not reached from any entry point (candidate for review) · pattern restoreLayers (shared by 2 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 232 functions or classes, including close, open, dockLayers, restoreLayers, show. 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 upstream_foresight (path word 'substation'): 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, 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 restores layers (`restoreLayers`), saves outline (`saveOutline`) and reads outline (`readOutline`). 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
code-generator · apps/substation-finder/Si · 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
none found
Produces
close, open, dockLayers, restoreLayers, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail
Defines here
legality, startNodes, between, within, seasonsOf, flagsFor, at, makeUnionFind, find, assemble, busOf, componentOf, multiply, solve, sinkFor, respond, modelFor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:2041-2740 · blob fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
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;
return { theta: x, iterations, residual: Math.sqrt(rr) };
}
const SINK_RULE =
'Where no withdrawal bus is declared, the sink is the most connected '
+ 'bus in the SAME component as the injection - the bus with the most '
+ 'published branches landing on it. It is a stated rule, not a '
+ 'convenience: a transfer has two ends and the answer is meaningless '
+ 'without naming both. Declare a sink to override it.';
function sinkFor(model, atNode) {
if (!model || typeof model.componentOf !== 'function') return null;
const atBus = model.busOf(atNode);
const component = model.componentOf(atBus);
let best = null;
let bestDegree = -1;
for (const bus of model.buses) {
if (bus === atBus) continue;
if (model.componentOf(bus) !== component) continue;
const d = model.degreeOf(bus);
if (d > bestDegree || (d === bestDegree && best !== null && bus < best)) {
best = bus;
bestDegree = d;
}
}
return best;
}
function respond(model, options) {
const opts = options || {};
const mw = Number.isFinite(opts.mw) ? opts.mw : 100;
const atBus = model.busOf(opts.atNode);
const slackBus = model.busOf(opts.slackNode);
const i = model.busIndex.get(atBus);
const s = model.busIndex.get(slackBus);
if (i === undefined || s === undefined) return null;
if (i === s) {
return {
schema: SCHEMA,
declared_model: DECLARED_MODEL,
injected_mw: mw,
at_node: opts.atNode,
slack_node: opts.slackNode,
same_bus: true,
reason: 'the injection point and the slack are the same electrical '
+ 'bus once zero-reactance branches are shorted, so there is no '
+ 'transfer to distribute',
branches: [],
not_a_loading: NOT_A_LOADING,
not_a_connection_offer: NOT_A_CONNECTION_OFFER
};
}
if (typeof model.componentOf === 'function'
&& model.componentOf(atBus) !== model.componentOf(slackBus)) {
return {
schema: SCHEMA,
declared_model: DECLARED_MODEL,
injected_mw: mw,
at_node: opts.atNode,
slack_node: opts.slackNode,
same_bus: false,
publishable: false,
reason: 'the injection bus and the withdrawal bus are in different '
+ 'connected components of the published network at this voltage, '
+ 'so there is no transfer between them to distribute. The model '
+ 'has ' + (model.counts ? model.counts.components : 'several')
+ ' components at this voltage; a transfer must be solved within one.',
branches: [],
component: {
injection: model.componentOf(atBus),
slack: model.componentOf(slackBus),
injection_component_buses: model.componentSize(atBus)
},
sink_rule: SINK_RULE,
not_a_loading: NOT_A_LOADING,
not_a_connection_offer: NOT_A_CONNECTION_OFFER
};
}
const n = model.buses.length;
const p = new Float64Array(n);
p[i] = mw / BASE_MVA;
p[s] = -mw / BASE_MVA;
const solved = solve(model, p, s, 1e-10, Math.min(4 * n, 20000));
const minimumShare = Number.isFinite(opts.minimumShare) ? opts.minimumShare : 0.01;
const flows = [];
for (const e of model.edges) {
const flowPu = (solved.theta[e.i] - solved.theta[e.j]) * e.b;
const flowMw = flowPu * BASE_MVA;
const share = mw === 0 ? 0 : flowMw / mw;
if (Math.abs(share) < minimumShare) continue;
const row = e.meta.row;
const ratings = {};
for (const [season, field] of [['winter', 'winter_mva'], ['spring', 'spring_mva'],
['summer', 'summer_mva'], ['autumn', 'autumn_mva']]) {
if (Number.isFinite(row[field])) ratings[season] = row[field];
}
flows.push({
from_node: e.meta.from,
to_node: e.meta.to,
kind: e.meta.kind,
x_pct_100mva: e.meta.x_pu * 100,
flow_mw: flowMw,
share_of_injection: share,
published_ratings_mva: Object.keys(ratings).length ? ratings : null,
transformer_rating_mva: e.meta.kind === 'transformer'
&& Number.isFinite(row.rating_mva) ? row.rating_mva : null
});
}
flows.sort((a, b) => Math.abs(b.share_of_injection) - Math.abs(a.share_of_injection));
const net = new Float64Array(model.buses.length);
for (const e of model.edges) {
const flowPu = (solved.theta[e.i] - solved.theta[e.j]) * e.b;
net[e.i] += flowPu;
net[e.j] -= flowPu;
}
const kirchhoff = net[i] * BASE_MVA / (mw || 1);
let worstBusError = 0;
let worstBus = null;
for (let k = 0; k < net.length; k += 1) {
const expected = k === i ? mw / BASE_MVA : (k === s ? -mw / BASE_MVA : 0);
const error = Math.abs(net[k] - expected);
if (error > worstBusError) { worstBusError = error; worstBus = model.buses[k]; }
}
const worstBusMw = worstBusError * BASE_MVA;
return {
schema: SCHEMA,
declared_model: DECLARED_MODEL,
injected_mw: mw,
at_node: opts.atNode,
slack_node: opts.slackNode,
same_bus: false,
branches: flows,
counts: {
branches_in_model: model.edges.length,
branches_carrying_at_least: minimumShare,
branches_reported: flows.length
},
convergence: {
iterations: solved.iterations,
residual: solved.residual,
converged: solved.residual < 1e-6
},
publishable: solved.residual < 1e-6 && worstBusMw < 1e-6 * Math.max(1, mw)
&& Math.abs(kirchhoff - 1) < 1e-6,
sink_rule: SINK_RULE,
component: {
solved_in: typeof model.componentOf === 'function' ? model.componentOf(atBus) : null,
buses_in_component: typeof model.componentSize === 'function' ? model.componentSize(atBus) : null
},
validation: {
kirchhoff_at_injection: kirchhoff,
kirchhoff_error: Math.abs(kirchhoff - 1),
worst_bus_error_mw: worstBusMw,
worst_bus: worstBus,
passes: Math.abs(kirchhoff - 1) < 1e-6
&& worstBusMw < 1e-6 * Math.max(1, mw)
&& solved.residual < 1e-6,
what_it_checks: 'the shares leaving the injection bus must sum to 1.0, '
+ 'AND net flow must be zero at every other bus, AND the solve '
+ 'must have converged. Any one of the three alone can hold while '
+ 'the answer is wrong.'
},
not_a_loading: NOT_A_LOADING,
not_a_connection_offer: NOT_A_CONNECTION_OFFER
};
}
function modelFor(index, options) {
if (!index || typeof index.graph !== 'function') return null;
const graph = index.graph();
if (!graph || graph.schema !== REQUIRES) return null;
const opts = options || {};
const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
const includeTransformers = opts.includeTransformers === true;
const names = [];
for (const name of (opts.nodeNames || [])) {
if (voltageKv == null || graph.nodeVoltageKv(name) === voltageKv) names.push(name);
}
if (!names.length) return null;
return assemble(graph, names, { voltageKv, includeTransformers });
}
NS.injectionResponse = Object.freeze({
schema: SCHEMA,
requires: REQUIRES,
base_mva: BASE_MVA,
declared_model: DECLARED_MODEL,
not_a_loading: NOT_A_LOADING,
not_a_connection_offer: NOT_A_CONNECTION_OFFER,