In this section
- G203 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 1801–2500
G203 Regional Native Viewport
A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, 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). 98% 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.987 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
- sha256 7645828021ee561333c34c0ecaad2b46bd87029ca9101601714d7e520bb680b1
- 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/g203-regional-native-viewport.js · lines 1801–2500 of 8664 (continued from section 576) · pattern regionalEligible (shared by 3 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 241 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.
- Downstream impact
- Used directly by 1 file: G203 Swarm 06 Viewport Lifecycle Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- 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
- Checked by G203 Swarm 06 Viewport Lifecycle Test.
- 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
- referenced by G203 Swarm 06 Viewport Lifecycle Test (new URL import.meta.url)
- Produces
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- destinationPoint, initialBearingDeg, voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf, index, land, siteOf, graph, resolve, at, crossing, describe, legality, startNodes, between
- 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/g203-regional-native-viewport.js:1801-2500 · blob 013cf98a02bb6c09199c357ac96a2b588892c0f4 · 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: production_core
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value);
}
}
const volts = properties.voltage ?? properties.VOLTAGE;
if (volts != null) {
for (const token of String(volts).match(/\d+(?:\.\d+)?/g) || []) {
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value / 1000);
}
}
return [...new Set(out)].sort((a, b) => b - a);
}
/* Projection and bearing, carried in from the sandbox verbatim.
----------------------------------------------------------------------
The deep scan found the body carrying a SECOND geodesy section - "the
geodesy the layout needs, all on R_ATLAS" - four hundred lines away
from the first. Two geodesies in one file, on a constant that must
never differ, is the configuration that produced the divergence the
all-versions proof caught. Both belong here, on the one radius, and
the body now delegates rather than defining.
The bodies below are the incumbent's, character for character apart
from the radius identifier, so parity is a property of the move rather
than something to argue about afterwards. */
function destinationPoint(lon, lat, km, bearingDeg) {
const ad = km / EARTH_RADIUS_KM;
const brg = bearingDeg * DEG;
const p1 = lat * DEG;
const p2 = Math.asin(Math.sin(p1) * Math.cos(ad)
+ Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
const l2 = lon * DEG + Math.atan2(
Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
return [l2 / DEG, p2 / DEG];
}
function initialBearingDeg(lon1, lat1, lon2, lat2) {
const p1 = lat1 * DEG; const p2 = lat2 * DEG;
const dl = (lon2 - lon1) * DEG;
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return (Math.atan2(y, x) / DEG + 360) % 360;
}
NS.geodesy = Object.freeze({
schema: 'gridatlas.module.geodesy.v1',
EARTH_RADIUS_KM,
distanceKm,
destinationPoint,
initialBearingDeg,
representativePoint,
voltagesKv
});
})();
/**
* Module: network-topology
*
* What the network operator publishes about ONE site: its nodes, the
* circuits that land on them, the transformers between them, the changes
* it has published for future years, and which other sites those circuits
* reach. Appendix B of the Electricity Ten Year Statement, read as a
* node/branch model and reported as facts.
*
* Successor at generation 202609012245: the node-level adjacency this module
* already builds is now handed OUT, so that the electrical-distance module
* can traverse it instead of building a second one. A second implementation
* of voltageOf would be a second opinion about which voltages are real, and
* this estate has already shipped one cartridge carrying two geodesies that
* disagreed in the last place. Nothing else changed: at() is byte-for-byte
* the incumbent's, and the parity proof holds the two to identical answers
* on the published payload.
*
* It answers "what is here, and what is it connected to". It does not
* answer "can this project connect", and it cannot: that depends on queue
* position, committed connections, consent and commercial terms which no
* published appendix contains. The product says so itself and the refusal
* travels inside every result, in the same object as the numbers, because
* a caveat in a different place from the figure is a caveat nobody reads.
*
* Three disciplines, each of them a defect this estate has already shipped:
*
* VOLTAGE IS NEVER MIXED. A card printed "5.1-49.6 kA" across a 132 kV
* and a 400 kV busbar and an engineer would have read it as one number
* for one point. So every answer here is grouped by the voltage of the
* node the circuit lands on, and a caller asking for one voltage gets
* only that voltage. There is no site-wide range in this module at all.
*
* VOLTAGE IS NEVER DECODED. The node-code convention (digit 1->132,
* 2->275, 4->400) is derived, not documented, and the product reports
* 726 of 2,679 nodes whose voltage their site does not declare. This
* reads `voltage_kv` and honours `voltage_consistent_with_site`; where
* that is false the voltage is `null` and the node is grouped under
* 'undeclared', never guessed from its name.
*
* R, X AND B ARE NOT A LOAD FLOW. They are published percentages on a
* 100 MVA base. Carrying them is publishing; solving with them would
* need a declared model, generation and load assumptions, tap positions
* and contingencies, and validation against a trusted solver. This
* module carries them and says what base they are on. It computes
* nothing from them.
*
* Fail closed: an unrecognised schema yields no index and therefore no
* answers, rather than plausible ones from a shape that has moved.
*
* Depends on: nothing. Topology is not geometry - this module never
* measures a distance and never touches a coordinate.
*/
(() => {
'use strict';
const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
if (NS.networkTopology) return;
const ACCEPTS = 'data-grid-gb.transmission-network.v1';
const NOT_AN_ASSESSMENT =
'Counts, lengths, ratings and impedances are what the network operator '
+ 'publishes about this site. None of them states whether any project can '
+ 'connect here, which depends on queue position, committed connections, '
+ 'consent and commercial terms that no published appendix contains.';
const IMPEDANCE_BASIS =
'R, X and B are percentages on a 100 MVA base, as published. They are '
+ 'network parameters, not a solved power flow.';
const UNDECLARED = 'undeclared';
/* A node's voltage is trusted only where the product says the site
declares it. Everything else is undeclared - never inferred from the
digit in the node code, which is a derived convention the product
itself marks as undocumented. */
function voltageOf(node) {
if (!node) return null;
if (node.voltage_consistent_with_site !== true) return null;
return Number.isFinite(node.voltage_kv) ? node.voltage_kv : null;
}
const bandKey = (kv) => (kv == null ? UNDECLARED : String(kv));
function ratingsOf(row) {
const seasons = { winter: row.winter_mva, spring: row.spring_mva,
summer: row.summer_mva, autumn: row.autumn_mva };
const published = {};
for (const [season, value] of Object.entries(seasons)) {
if (Number.isFinite(value)) published[season] = value;
}
return Object.keys(published).length ? published : null;
}
/* A published branch is seen once from EACH of its ends, so a site that
owns both ends of a branch publishes it twice.
------------------------------------------------------------------
A transformer's two windings are at the same site by construction, so
almost every transformer lands twice: 1,394 of the 1,472 published
transformers have both ends at one site. Counting landings therefore
reported 2,944 machines where 1,550 site-held machines exist, and
Cowley - five machines, COWL41 to COWL11 and COWL12, 269 to 278 MVA -
said ten.
It is NOT only transformers. Measured against
gb-transmission-network.v1 on 2026-09-03:
transformers 2,944 landings -> 1,550 units, 484 of 525 sites differ
circuits 2,784 landings -> 2,638 units, 78 of 636 sites differ
planned changes 4,460 landings -> 3,696 units, 282 of 645 sites differ
so the same correction is applied to all three site-wide aggregates.
The PER-VOLTAGE lists are untouched and must stay as they are: "at
400 kV, 5 transformers" and "at 132 kV, 5 transformers" are the same
five machines seen from each winding, which is what a reader standing
at a busbar is asking for.
Halving was rejected: it is wrong at 57 of the 525 sites that hold a
transformer, and 24 of them publish an odd number of landings, so
halving would invent a fractional machine. The pair is keyed instead,
and a pair seen from BOTH directions was published twice while a pair
seen from one - which is what a voltage-filtered query sees of an
internal machine - was published once. */
function physicalUnits(records) {
const pairs = new Map();
for (const record of records) {
const near = String(record.from_node);
const far = String(record.to_node);
const forward = near < far;
const key = forward ? near + '\u0000' + far : far + '\u0000' + near;
if (!pairs.has(key)) pairs.set(key, { forward: 0, reverse: 0 });
const seen = pairs.get(key);
if (forward) seen.forward += 1; else seen.reverse += 1;
}
let units = 0;
for (const seen of pairs.values()) {
units += (seen.forward && seen.reverse)
? Math.max(seen.forward, seen.reverse)
: seen.forward + seen.reverse;
}
return units;
}
function parametersOf(row) {
const published = {};
for (const [key, field] of [['r_pct', 'r_pct_100mva'], ['x_pct', 'x_pct_100mva'],
['b_pct', 'b_pct_100mva']]) {
if (Number.isFinite(row[field])) published[key] = row[field];
}
return Object.keys(published).length ? published : null;
}
/**
* @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 nodes = new Map();
for (const node of product.nodes || []) {
if (node && node.node) nodes.set(node.node, node);
}
const sitesByCode = new Map();
const sitesByName = new Map();
for (const site of product.sites || []) {
if (!site || !site.code) continue;
sitesByCode.set(String(site.code).toUpperCase(), site);
if (site.name) sitesByName.set(String(site.name).toUpperCase().trim(), site);
}
/* Branches are indexed by the node they land on, both ends, because a
circuit is a fact about both of its sites. */
const byNode = new Map();
function land(nodeName, entry) {
if (!nodeName) return;
if (!byNode.has(nodeName)) byNode.set(nodeName, []);
byNode.get(nodeName).push(entry);
}
for (const [kind, rows] of [['circuit', product.circuits],
['transformer', product.transformers], ['planned_change', product.planned_changes]]) {
for (const row of rows || []) {
if (!row) continue;
land(row.node_1, { kind, row, near: 'node_1', far: 'node_2' });
land(row.node_2, { kind, row, near: 'node_2', far: 'node_1' });
}
}
function siteOf(nodeName) {
const node = nodes.get(nodeName);
return node ? node.site_code : null;
}
/* The adjacency, handed out rather than rebuilt.
------------------------------------------------------------------
Every accessor here is a READ of the structures at() already uses,
so a traversal cannot disagree with a one-hop view about which
nodes exist, which site a node belongs to, or whether a node's
voltage is trustworthy. planned_change rows are excluded from
edges: a change published for 2029 is not a path a current can
take today, and treating it as one would be the headroom lie in a
new costume. They remain available through at(). */
function graph() {
return {
schema: 'gridatlas.module.network-topology.graph.v1',
has: (name) => nodes.has(name),
nodeVoltageKv: (name) => voltageOf(nodes.get(name)),
nodeSiteCode: (name) => {
const node = nodes.get(name);
return node ? node.site_code : null;
},
/* circuits and transformers only - see above */
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;
}
/**
* Everything published about one site, grouped by the voltage of the
* node each branch lands on. Never a site-wide range.
*
* @param key site code or exact site name
* @param options { voltageKv } to restrict to one voltage
*/
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);
}
/* A neighbour is another SITE this site's circuits reach. An
internal branch is not a neighbour, and a planned change is
not a neighbour either - it has not been built. */
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,
/* Physical units, deduplicated across the two ends a site may
hold of the same branch. The landing tallies are published
beside them so a reader can see the difference rather than
wonder which number the per-voltage lists add up to. */
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
});
})();
/**
* Module: electrical-distance
*
* How far away a substation is, measured in the network operator's own
* published circuits rather than in kilometres.
*
* WHY THIS EXISTS
* ---------------
* Everything this estate has measured until now has been geometry. The
* geodesy module answers "how many kilometres from this project to that
* substation", and it answers it correctly, to the last place. But a
* kilometre is not a connection. Two substations 7 km apart can be on
* opposite sides of a network boundary with no circuit between them; two
* substations 90 km apart can be the two ends of a single published
* circuit. A map that shows only the first number invites the reader to
* infer the second, and that inference is wrong often enough to be
* dangerous in a document someone spends money on.
*
* So this module answers a different question, from a different source:
* on the network Appendix B actually publishes, how many circuits lie
* between these two sites, and which ones? Every hop is a published row
* with an identity. The answer is a citation, not an estimate.
*
* WHAT IT IS NOT
* --------------
* A hop count is not a distance. Two hops is not "twice as far" as one,
* and a site one hop away is not thereby available to connect to. It is
* not an impedance either: R, X and B are carried on every hop exactly as
* published, and this module contains no arithmetic over them at all -
* summing impedance along a path is the first step of a load flow, and a
* load flow needs a declared model, base values, taps, generation and load
* assumptions, contingencies and validation against a trusted solver. None
* of those are in this file, so neither is the sum.
*
* THE ONE RULE THAT SHAPES THE TRAVERSAL
* --------------------------------------
* A voltage may only change across a transformer, and when it does the
* transformer is named in the path. A circuit whose two ends carry
* different declared voltages is not a voltage change - it is a
* contradiction in the data, and the traversal refuses it and says so
* rather than quietly walking through. Undeclared voltages are carried as
* undeclared and never guessed from a node code.
*
* node tools/proofs/modules/202609012245-electrical-distance.proof.mjs
*/
(() => {
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';
/* A traversal must not invent a voltage, so the two ends of an edge are
compared only when BOTH are declared. */
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,
/* The transformer's own published ratio, where it has one. Only 140
of 1,472 transformers carry it, so it is reported when present and
never reconstructed from the two node voltages when absent - a
reconstructed ratio would be this module's opinion wearing the
product's authority. */
voltage_ratio_kv: entry.kind === 'transformer'
&& typeof entry.row.voltage_ratio_kv === 'string'
? entry.row.voltage_ratio_kv : null,
/* carried, never computed with */
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)
};
}
/**
* Is this edge legal to walk?
*
* A transformer is the only thing that may change voltage. A circuit
* that appears to change voltage is a contradiction between two
* published node records, and it is refused and reported rather than
* traversed - a silent walk through it would mix voltages, which is the
* exact failure this estate holds itself to never repeating.
*/
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);
}
/**
* The shortest published path between two sites, in circuits.
*
* Breadth-first, so the first arrival is a fewest-hop path. Where
* several paths tie, the one found first by sorted node order is
* returned and `ties` says how many others arrived at the same depth,
* because "the" path implies a uniqueness the network does not have.
*
* @param index a network-topology index (must expose graph())
* @param fromKey site code or exact site name
* @param toKey site code or exact site name
* @param options { voltageKv, maxHops }
* @returns a result object, or null if either site is unknown
*/
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]
});
}