In this section
- Regional Native geodesy · gridatlas / atlas/modules/202612012117-regional-native.js lines 3199–3898
Regional Native
A JavaScript file in the atlas folder of GridAtlas 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 atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.994 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
- sha256 6350426294d6ee73ee6b6475003b30b79be79ae5a1e4a5a15de1a780fe517ce0
- target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/modules/202612012117-regional-native.js · lines 3199–3898 of 8607 · version 2026-12-01 21:17 (continued from section 541) · Not reached from any entry point (candidate for review) · pattern regionalEligible (shared by 3 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 239 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- What it achieves
- It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/modules · 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
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- modelFor, asString, asNumber, statusRank, yearRank, publishedToday, index, describe, at, asString, asNumber, bandKey, index, ownerOfNode, relation, describe, at, band, count
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612012117-regional-native.js:3199-3898 · blob e01079f148704c08dfda3ccf7ae8239e3d77a00a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
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));
/* Validation carried in the answer, and GLOBAL.
--------------------------------------------------------------------
This checked Kirchhoff at the injection bus alone, which a
disconnected pair can satisfy while the solve has not converged at
all: a minimal A-B / C-D fixture injecting at A and withdrawing at D
returned validation.passes true with converged false. A page gated on
that could print an impossible transfer.
Now every bus is checked. Net flow must be the injection at the
injection bus, minus it at the slack, and zero everywhere else. */
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,
/* ALL THREE, not one. Convergence alone is not conservation, and
conservation at one bus is not conservation. */
passes: Math.abs(kirchhoff - 1) < 1e-6
&& worstBusMw < 1e-6 * Math.max(1, mw)
&& solved.residual < 1e-6,
/* Exact by Kirchhoff's current law under the DC model: everything
injected at a bus must leave it along the branches. It is
checked at runtime and carried in the answer rather than
asserted in a comment, because a solve that has not converged
produces a plausible-looking set of flows that are wrong. */
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
};
}
/**
* Convenience: build a model over every node at one voltage.
*/
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,
sink_rule: SINK_RULE,
modelFor,
assemble,
sinkFor,
respond
});
})();
/**
* Module: planned-change
*
* What the network operator has PUBLISHED as planned for the circuits and
* transformers that touch one site: additions, changes and removals, by
* the year they are published against.
*
* WHY THIS EXISTS
* ---------------
* Appendix B carries 2,230 rows that are not the network. They are the
* operator's statement of what the network is planned to look like in
* 2026, 2028, 2030 and 2033: a circuit to be added, a circuit whose
* parameters are to change, a transformer to be removed. The topology
* module carries them and the graph it hands out deliberately refuses to
* walk them, which is right - a circuit published for 2030 is not a path
* a current can take today. But refusing to walk them is not the same as
* reporting them, and a reader looking at a site with four published
* additions in 2028 is entitled to be told so, with the year and the
* status and the published parameters, in the operator's own words.
*
* So this module reports the planned rows that land at a site, grouped by
* year and then by status, with real counts. It reads the same product the
* topology module reads and resolves sites, nodes and voltages through the
* topology index rather than through a second opinion of its own.
*
* WHAT IT IS NOT
* --------------
* A published plan is not infrastructure. Every entry this module returns
* is marked as a publication about a future year, it is never mixed into
* a list of circuits that exist, and nothing here can be traversed: the
* module contains no path, no hop and no neighbour, and the graph it
* borrows excludes these rows from its edges by construction.
*
* A published plan is not a commitment either. The operator publishes
* planned changes as its current view of network development; the view
* moves between editions, an addition can be deferred or dropped, and a
* year against a row is the year the row is published for, not a
* consent, not a delivery date and not a date on which anything could
* connect. A "Removed" row says a circuit is planned to be taken out; it
* does not say why, and it does not say what replaces it.
*
* And, as everywhere in this estate: nothing here states whether a project
* can connect. R, X and B on a planned row are carried as published on a
* 100 MVA base and never computed with; ratings on a planned row are the
* planned circuit's, not a spare allowance; voltages are trusted only where
* the product says the site declares them and are never decoded from a
* node code.
*
* ONE PUBLISHED FACT THAT IS WORTH CARRYING
* -----------------------------------------
* 552 of the 2,230 planned rows sit on a node pair that already has a
* circuit or transformer published for today, and 16 of those are marked
* "Addition" - a second circuit on an existing pair, on the face of it.
* Whether a pair is published today is a fact from the same product, so
* each entry carries it. It is a cross-reference, not a judgement about
* what the addition means.
*
* node tools/proofs/modules/202609012345-planned-change.proof.mjs
*/
(() => {
'use strict';
const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (NS.plannedChange) return;
const SCHEMA = 'gridatlas.module.planned-change.v1';
const ACCEPTS = 'data-grid-gb.transmission-network.v1';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';
const NOT_EXISTING =
'Every entry here is a change the network operator has published for '
+ 'a future year. None of it is a circuit or a transformer that exists '
+ 'today, none of it is a path, and none of it is counted among the '
+ 'site\'s circuits anywhere in this estate.';
const NOT_A_COMMITMENT =
'A published plan is the operator\'s current view of network '
+ 'development, and the view moves between editions. It is not a '
+ 'commitment to build, not a consent, and the year on a row is the '
+ 'year it is published for - not a delivery date and not a date on '
+ 'which anything could connect.';
const NOT_AN_ASSESSMENT =
'Nothing here states whether any project can connect at this site, '
+ 'before or after a planned change. That depends on queue position, '
+ 'committed connections, consent and commercial terms which no '
+ 'published appendix contains. A rating on a planned row is the '
+ 'planned asset\'s rating, not a spare allowance.';
const IMPEDANCE_BASIS =
'R, X and B on a planned row are percentages on a 100 MVA base, as '
+ 'published for the planned asset. They are carried and not computed '
+ 'with.';
/* The order the statuses are presented in. Anything the product
publishes that is not one of these three is kept and sorted after
them by name, never dropped. */
const STATUS_ORDER = Object.freeze(['Addition', 'Change', 'Removed']);
const ASSETS = Object.freeze(['circuit', 'transformer']);
const asString = (v) => (typeof v === 'string' && v.length ? v : null);
const asNumber = (v) => (Number.isFinite(v) ? v : null);
function statusRank(status) {
const i = STATUS_ORDER.indexOf(status);
return i === -1 ? STATUS_ORDER.length : i;
}
/* Years are published as strings ("2026"). They are sorted numerically
where they parse and left in their published form on the entry. */
function yearRank(year) {
const n = Number(year);
return Number.isFinite(n) ? n : Number.POSITIVE_INFINITY;
}
/**
* Is there a circuit or a transformer published for TODAY between
* these two nodes? Read off the graph's edges, which are circuits and
* transformers only, so a planned row can never vouch for itself.
*/
function publishedToday(graph, nearNode, farNode) {
const today = { circuit: false, transformer: false };
for (const entry of graph.edgesAt(nearNode)) {
if (entry.row[entry.far] !== farNode) continue;
if (entry.kind === 'circuit') today.circuit = true;
if (entry.kind === 'transformer') today.transformer = true;
}
return today;
}
/**
* @param product the parsed data-grid-gb transmission-network payload
* @returns an index, or null if the schema is not the one this reads
*/
function index(product) {
if (!product || product.schema !== ACCEPTS) return null;
const topology = NS.networkTopology;
if (!topology || typeof topology.index !== 'function') return null;
const base = topology.index(product);
if (!base || typeof base.graph !== 'function') return null;
const graph = base.graph();
if (!graph || graph.schema !== REQUIRES) return null;
const rows = Array.isArray(product.planned_changes) ? product.planned_changes : [];
/* Planned rows land on their two nodes exactly as branches do in the
topology module, so that a site query is a lookup and not a scan. */
const byNode = new Map();
for (const row of rows) {
if (!row) continue;
for (const [near, far] of [['node_1', 'node_2'], ['node_2', 'node_1']]) {
const name = row[near];
if (!name) continue;
if (!byNode.has(name)) byNode.set(name, []);
byNode.get(name).push({ row, near, far });
}
}
/* Product-wide tallies. These are counts of published rows, each
counted once, and they are the only place in this module where a
row is counted without reference to a site. */
const tally = { by_year: {}, by_status: {}, by_asset: {} };
for (const row of rows) {
if (!row) continue;
const y = asString(row.year) || 'unstated';
const s = asString(row.status) || 'unstated';
const a = asString(row.asset) || 'unstated';
tally.by_year[y] = (tally.by_year[y] || 0) + 1;
tally.by_status[s] = (tally.by_status[s] || 0) + 1;
tally.by_asset[a] = (tally.by_asset[a] || 0) + 1;
}
function describe(landing, nearNode) {
const row = landing.row;
const farNode = row[landing.far];
const farSiteCode = graph.nodeSiteCode(farNode) || null;
const farSite = farSiteCode ? graph.siteByCode(farSiteCode) : null;
const nearSiteCode = graph.nodeSiteCode(nearNode) || null;
const asset = asString(row.asset);
const entry = {
publication: 'planned',
year: asString(row.year),
status: asString(row.status),
asset,
from_node: nearNode,
to_node: farNode,
from_site_code: nearSiteCode,
to_site_code: farSiteCode,
to_site_name: farSite ? farSite.name : null,
within_this_site: !!farSiteCode && farSiteCode === nearSiteCode,
/* trusted only where the site declares it; null otherwise */
from_voltage_kv: graph.nodeVoltageKv(nearNode),
to_voltage_kv: graph.has(farNode) ? graph.nodeVoltageKv(farNode) : null,
transmission_owner: asString(row.transmission_owner),
labels: Array.isArray(row.labels) ? row.labels.slice() : [],
/* carried, never computed with */
parameters_pct_100mva: graph.parametersOf(row),
pair_published_today: graph.has(farNode)
? publishedToday(graph, nearNode, farNode)
: { circuit: false, transformer: false }
};
if (asset === 'transformer') {
entry.rating_mva = asNumber(row.rating_mva);
entry.voltage_ratio_kv = asString(row.voltage_ratio_kv);
} else {
entry.circuit_type = asString(row.circuit_type);
entry.ohl_km = asNumber(row.ohl_km);
entry.cable_km = asNumber(row.cable_km);
entry.ratings_mva = graph.ratingsOf(row);
}
return entry;
}
/**
* Every planned change landing at one site, grouped by year and then
* by status. A row landing on two nodes of the same site is reported
* once, from the first node it is met at in sorted node order.
*
* @param key site code or exact site name
* @param options { voltageKv } to restrict to rows landing on a node
* the site declares at that voltage
*/
function at(key, options) {
const site = base.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 seen = new Set();
const entries = [];
for (const nodeName of nodes) {
for (const landing of byNode.get(nodeName) || []) {
if (seen.has(landing.row)) continue;
seen.add(landing.row);
entries.push(describe(landing, nodeName));
}
}
/* year -> status -> entries, in a stable presentation order */
const years = new Map();
for (const entry of entries) {
const y = entry.year || 'unstated';
if (!years.has(y)) years.set(y, new Map());
const statuses = years.get(y);
const s = entry.status || 'unstated';
if (!statuses.has(s)) statuses.set(s, []);
statuses.get(s).push(entry);
}
const by_year = [...years.entries()]
.sort((a, b) => yearRank(a[0]) - yearRank(b[0]) || a[0].localeCompare(b[0]))
.map(([year, statuses]) => {
const by_status = [...statuses.entries()]
.sort((a, b) => statusRank(a[0]) - statusRank(b[0]) || a[0].localeCompare(b[0]))
.map(([status, list]) => {
list.sort((a, b) => String(a.to_node).localeCompare(String(b.to_node)));
const by_asset = {};
for (const a of ASSETS) by_asset[a] = list.filter((e) => e.asset === a).length;
return { status, entries: list, counts: { entries: list.length, by_asset } };
});
const counts = { entries: 0, by_status: {} };
for (const group of by_status) {
counts.entries += group.counts.entries;
counts.by_status[group.status] = group.counts.entries;
}
return { year, by_status, counts };
});
const counts = { planned_changes: entries.length, by_year: {}, by_status: {}, by_asset: {} };
for (const y of by_year) counts.by_year[y.year] = y.counts.entries;
for (const e of entries) {
const s = e.status || 'unstated';
const a = e.asset || 'unstated';
counts.by_status[s] = (counts.by_status[s] || 0) + 1;
counts.by_asset[a] = (counts.by_asset[a] || 0) + 1;
}
counts.on_a_pair_published_today = entries
.filter((e) => e.pair_published_today.circuit || e.pair_published_today.transformer).length;
return {
schema: SCHEMA,
source: ACCEPTS,
site: { code: site.code, name: site.name },
requested_voltage_kv: voltageKv,
scope: voltageKv == null
? 'rows landing on any node of this site; each entry carries the '
+ 'declared voltage of the node it lands on, and undeclared is '
+ 'undeclared'
: 'rows landing on a node this site declares at ' + voltageKv + ' kV only',
nodes_considered: nodes.length,
by_year,
counts,
not_existing: NOT_EXISTING,
not_a_commitment: NOT_A_COMMITMENT,
not_an_assessment: NOT_AN_ASSESSMENT,
impedance_basis: IMPEDANCE_BASIS
};
}
return {
schema: SCHEMA,
source: ACCEPTS,
counts: Object.assign({ planned_changes: rows.length }, tally),
site: base.site,
at
};
}
NS.plannedChange = Object.freeze({
schema: SCHEMA,
accepts: ACCEPTS,
requires: REQUIRES,
status_order: STATUS_ORDER,
not_existing: NOT_EXISTING,
not_a_commitment: NOT_A_COMMITMENT,
not_an_assessment: NOT_AN_ASSESSMENT,
impedance_basis: IMPEDANCE_BASIS,
index
});
})();
/**
* Module: owner-boundary
*
* Which transmission owner the published assets at a site belong to, and
* which circuits cross from one owner's network into another's.
*
* WHY THIS EXISTS
* ---------------
* Great Britain's transmission network is not one network. Appendix B
* publishes a `transmission_owner` on every site, node, circuit and
* transformer, and four values occur: NGET in England and Wales, SPT in
* southern Scotland, SHET in the north of Scotland, and OFTO for the
* offshore assets. Most circuits sit wholly inside one owner's network.
* Sixty-two do not: their two ends are nodes that different owners
* publish, and a circuit like that is the seam between two networks.
*
* That seam is worth naming because a connection near it involves more
* than one party. It is a fact about who publishes what, read straight
* off the product, and it is reported here with both owners named on
* every boundary circuit so that nobody has to infer it from a map colour.
*
* WHAT IT IS NOT
* --------------
* Ownership is not a statement about who a project would contract with.
* Connection agreements in Great Britain are made with the system operator
* and the relevant owner under a framework this data does not describe,
* and a site being NGET's says nothing about the counterparty, the process
* or the terms of any connection at it. This module reports the published
* owner of the published assets and stops there.
*
* Nor is an owner ever inferred. Forty-nine nodes publish no owner - all
* of them on placeholder site codes such as OFFS and ONSH that the product
* does not list as sites - and where a node's owner is not published it is
* reported as unknown. A circuit with an unknown end is reported as
* undetermined, not as a boundary and not as internal. Nothing is read
* from a site name, a node code or a neighbour.
*
* TWO DIFFERENT FACTS, KEPT APART
* -------------------------------
* A circuit carries its own `transmission_owner`, and so do the nodes at
* its two ends. A BOUNDARY circuit is one whose two END nodes belong to
* different owners. Separately, seven circuits in the product carry an
* owner that matches neither end - SPT and OFTO circuits between SHET
* nodes at Hunterston, Inverness and Nedd. That is not a boundary by the
* definition above; it is the asset's own published owner differing from
* the owner of the nodes it lands on, and it is reported as exactly that.
*
* Voltages are trusted only where the site declares them and never decoded
* from a node code; assets are counted per voltage and never across
* voltages. R, X and B are carried and never computed with. No rating here
* is headroom.
*
* node tools/proofs/modules/202609012350-owner-boundary.proof.mjs
*/
(() => {
'use strict';
const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (NS.ownerBoundary) return;
const SCHEMA = 'gridatlas.module.owner-boundary.v1';
const ACCEPTS = 'data-grid-gb.transmission-network.v1';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';
const NOT_A_COUNTERPARTY =
'The transmission owner is the party the network operator publishes '
+ 'as owning an asset. It is not a statement about who a project would '
+ 'contract with, under what process, or on what terms; none of that '
+ 'is in any published appendix.';
const NOT_AN_ASSESSMENT =
'An ownership boundary is a fact about who publishes which asset. It '
+ 'says nothing about whether any project can connect on either side '
+ 'of it, and a rating on a boundary circuit is that circuit\'s rating, '
+ 'not a spare allowance across the boundary.';
const NEVER_INFERRED =
'An owner is reported only where the product publishes one on the '
+ 'record in question. A node with no published owner is unknown, a '
+ 'circuit with an unknown end is undetermined, and nothing is read '
+ 'from a site name, a node code or a neighbour.';
const UNKNOWN = 'unknown';
const UNDECLARED = 'undeclared';
const asString = (v) => (typeof v === 'string' && v.length ? v : null);
const asNumber = (v) => (Number.isFinite(v) ? v : null);
const bandKey = (kv) => (kv == null ? UNDECLARED : String(kv));
/**
* @param product the parsed data-grid-gb transmission-network payload
* @returns an index, or null if the schema is not the one this reads
*/
function index(product) {
if (!product || product.schema !== ACCEPTS) return null;
const topology = NS.networkTopology;
if (!topology || typeof topology.index !== 'function') return null;
const base = topology.index(product);
if (!base || typeof base.graph !== 'function') return null;
const graph = base.graph();
if (!graph || graph.schema !== REQUIRES) return null;
/* The owner of a NODE, from the node record and nowhere else. The
graph does not hand this out, so it is read from the product here;
the graph is still the only authority on which nodes exist, which
site they belong to and what voltage may be trusted. */
const nodeOwner = new Map();
for (const node of product.nodes || []) {
if (node && node.node) nodeOwner.set(node.node, asString(node.transmission_owner));
}
const ownerOfNode = (name) => (nodeOwner.has(name) ? nodeOwner.get(name) : null);
/**
* The relation between the two ends of a branch, by published owner.
* 'boundary' both ends published, and they differ
* 'internal' both ends published, and they agree
* 'undetermined' at least one end publishes no owner
*/
function relation(nearOwner, farOwner) {
if (nearOwner == null || farOwner == null) return 'undetermined';
return nearOwner === farOwner ? 'internal' : 'boundary';
}
function describe(entry, nearNode) {
const row = entry.row;
const farNode = row[entry.far];
const nearOwner = ownerOfNode(nearNode);
const farOwner = graph.has(farNode) ? ownerOfNode(farNode) : null;
const assetOwner = asString(row.transmission_owner);
const nearSiteCode = graph.nodeSiteCode(nearNode) || null;
const farSiteCode = graph.has(farNode) ? graph.nodeSiteCode(farNode) || null : null;
const farSite = farSiteCode ? graph.siteByCode(farSiteCode) : null;
const out = {
kind: entry.kind,
from_node: nearNode,
to_node: farNode,
from_site_code: nearSiteCode,
to_site_code: farSiteCode,
to_site_name: farSite ? farSite.name : null,
within_this_site: !!farSiteCode && farSiteCode === nearSiteCode,
from_voltage_kv: graph.nodeVoltageKv(nearNode),
to_voltage_kv: graph.has(farNode) ? graph.nodeVoltageKv(farNode) : null,
/* the three published owners, each named for what it is */
from_owner: nearOwner || UNKNOWN,
to_owner: farOwner || UNKNOWN,
asset_owner: assetOwner || UNKNOWN,
ends: relation(nearOwner, farOwner),
/* the asset's own owner set against the ends it lands on; null
where either end is unknown, because "matches neither" cannot
be said of an end that has not been published */
asset_owner_matches_an_end: assetOwner && nearOwner && farOwner
? (assetOwner === nearOwner || assetOwner === farOwner)
: null,
/* carried, never computed with */
parameters_pct_100mva: graph.parametersOf(row)
};
if (entry.kind === 'circuit') {
out.circuit_type = asString(row.circuit_type);
out.ohl_km = asNumber(row.ohl_km);
out.cable_km = asNumber(row.cable_km);
out.ratings_mva = graph.ratingsOf(row);
} else {
out.rating_mva = asNumber(row.rating_mva);
out.voltage_ratio_kv = asString(row.voltage_ratio_kv);
}
return out;
}
/**
* Ownership at one site: the site's own published owner, the owner of
* each of its nodes, the assets landing on those nodes counted per
* owner within each voltage, and every boundary branch named with both
* owners.
*
* @param key site code or exact site name
* @param options { voltageKv } to restrict to nodes the site declares
* at that voltage
*/
function at(key, options) {
const site = base.site(key);
if (!site) return null;
const opts = options || {};
const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
const nodeNames = graph.nodesOfSite(site.code)
.filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);
const nodes = nodeNames.map((name) => ({
node: name,
voltage_kv: graph.nodeVoltageKv(name),
transmission_owner: ownerOfNode(name) || UNKNOWN
}));
/* Assets are counted once per site even when both ends are here,
and grouped under the declared voltage of the node they were
first met at in sorted node order. */
const seen = new Set();
const bands = new Map();
const boundary_circuits = [];
const boundary_transformers = [];
const undetermined = [];
const asset_owner_differs = [];
function band(kv) {
const k = bandKey(kv);
if (!bands.has(k)) {
bands.set(k, { voltage_kv: kv, by_owner: {}, circuits: 0, transformers: 0, nodes: 0 });
}
return bands.get(k);
}
function count(b, owner, what) {
const o = owner || UNKNOWN;
if (!b.by_owner[o]) b.by_owner[o] = { nodes: 0, circuits: 0, transformers: 0 };
b.by_owner[o][what] += 1;
b[what] += 1;
}
for (const n of nodes) count(band(n.voltage_kv), n.transmission_owner, 'nodes');
for (const nodeName of nodeNames) {
for (const entry of graph.edgesAt(nodeName)) {
if (seen.has(entry.row)) continue;
seen.add(entry.row);
const d = describe(entry, nodeName);
const b = band(d.from_voltage_kv);
count(b, d.asset_owner === UNKNOWN ? null : d.asset_owner,
entry.kind === 'circuit' ? 'circuits' : 'transformers');
if (d.ends === 'boundary') {
(entry.kind === 'circuit' ? boundary_circuits : boundary_transformers).push(d);
} else if (d.ends === 'undetermined') {
undetermined.push(d);
}
if (d.asset_owner_matches_an_end === false) asset_owner_differs.push(d);
}
}
const by_voltage = [...bands.entries()]
.sort((a, b) => {
if (a[0] === UNDECLARED) return 1;
if (b[0] === UNDECLARED) return -1;