In this section
- Substation Intelligence V9 63 geodesy · code-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js lines 1401–2100
Substation Intelligence V9 63
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/.
Set aside from the main view: 100% 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.9974 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
- sha256 d94b0de50deddac77643325b10fbe490ce44b8c406dbc6c67e6e7cadbdaa8ec6
- target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesycode-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js · lines 1401–2100 of 8590 · version 2026-09-06 23:58 (continued from section 283) · Not reached from any entry point (candidate for review) · pattern switchOn (shared by 4 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 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 '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: 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
- 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
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- pointOf, endTouch, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf, index, land, siteOf, graph, resolve, at
- 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/202609062358-substation-intelligence-v9-63.js:1401-2100 · blob 2c8121b277e1b152a96688f6a2e0d7ef83471376 · 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: duplicate_candidate
const layerObject = {
id: `l-${layer.id}`, type: layer.type === 'line' ? 'line' : 'circle', source: `src-${layer.id}`, layout: { visibility: 'none' },
paint: layer.type === 'line' ? { 'line-color': layer.color, 'line-width': layer.width } : { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000' }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${layer.id}`);
});
});
// ── Heavy Industry (Custom VIP styling) ──
map.addSource('src-naei_co2', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({
id: `l-naei_co2-glow`,
type: 'circle',
source: 'src-naei_co2',
filter: ['>=', ['coalesce', ['get', 'emission_tco2e'], 0], 50000],
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,20,200000,40,1000000,60,5000000,90],
'circle-opacity': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,0.15,200000,0.25,1000000,0.35],
'circle-blur': 1.0,
'circle-stroke-width': 0
}
});
map.addLayer({
id: 'l-naei_co2',
type: 'circle',
source: 'src-naei_co2',
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,'#ffcc00',50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,6,50000,10,200000,14,1000000,20,5000000,28],
'circle-stroke-width': 1.5,
'circle-stroke-color': '#000',
'circle-opacity': 0.85
}
});
allLayerIds.push('l-naei_co2-glow', 'l-naei_co2');
Object.keys(TRANSIT_URLS).forEach(sourceId => { map.addSource(sourceId, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } }); });
TRANSIT_IDS.forEach(id => {
const layer = getLayerConfig(id);
const layerObject = {
id: `l-${id}`, type: 'circle', source: TRANSIT_SOURCE_MAP[id], layout: { visibility: 'none' },
paint: { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${id}`);
});
map.addSource('src-ev', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-ev', type: 'circle', source: 'src-ev', layout: { visibility: 'none' }, paint: { 'circle-color': '#00ff88', 'circle-radius': 5, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 } });
allLayerIds.push('l-ev');
map.addSource('src-repd', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
REPD_IDS.forEach(id => {
const layer = getLayerConfig(id);
if (id === 'solar_roof') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 1.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capaci … [line shortened here: 513 characters; full line on GitHub]
}
if (id === 'solar') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 4.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],4.0,'#ffff00',20.0,'#ffaa00',50.0,'#ff4400',200.0,'#ff0000'], 'circle-radius': ['interpolate',['linear'],['coalesc … [line shortened here: 638 characters; full line on GitHub]
}
if (id === 'solar_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#00ff88',50.0,'#00cc66',200.0,'#009944',350.0,'#006622'], 'circle-radius': ['interpolate',['linear'],['coal … [line shortened here: 645 characters; full line on GitHub]
}
if (id === 'bess_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#ffb3d9',50.0,'#ff69b4',200.0,'#ff1493',350.0,'#cc0066'], 'circle-radius': ['interpolate',['linear'],['coal … [line shortened here: 645 characters; full line on GitHub]
}
if (id === 'wind_onshore_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ffee',50.0,'#00ffcc',200.0,'#00ccaa',350.0,'#008877'], 'circle-radius': ['interpolate',['linear'],['coal … [line shortened here: 645 characters; full line on GitHub]
}
if (id === 'wind_offshore_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ccff',50.0,'#3399ff',200.0,'#0055dd',350.0,'#003399'], 'circle-radius': ['interpolate',['linear'],['coal … [line shortened here: 645 characters; full line on GitHub]
}
const circlePaint = id === 'solar_roof'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffcc00',0.99,'#ffcc00',1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,7,0.5,7,0.99,8,1.0,16,2.0,18,5.0,22,10.0,28], 'circle-stroke-width': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,1,0.99,1,1.0,2], 'circ … [line shortened here: 449 characters; full line on GitHub]
: id === 'solar'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffff00',20.0,'#ffcc00',50.0,'#ffaa00',200.0,'#ff6600',500.0,'#ff2200'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 }
: id === 'solar_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#66ff99',10,'#33ff77',50,'#00dd55',100,'#00bb44',200,'#008833',350,'#006622',500,'#004411'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,10,10,14,50,18,100,22,200,28,350,35,500,42], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'bess_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffccee',10,'#ffb3d9',50,'#ff69b4',100,'#ff1493',200,'#dd0077',350,'#990066',500,'#660044'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'wind_onshore_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ccfff5',10,'#99ffee',50,'#00ffcc',100,'#00ddaa',200,'#00aa88',350,'#007766',500,'#004433'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'wind_offshore_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#cce5ff',10,'#99ccff',50,'#3399ff',100,'#0066ee',200,'#0044bb',350,'#003399',500,'#001166'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: { 'circle-color': layer.color, 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 };
map.addLayer({ id: `l-${id}`, type: 'circle', source: 'src-repd', filter: layer.filter, layout: { visibility: 'none' }, paint: circlePaint });
allLayerIds.push(`l-${id}`);
});
// ── PERF: seed the visible layer cache from actual map state after all layers are added
_rebuildVisibleCache(allLayerIds);
// ── Map Events ────────────────────────────────────────────────────────────
let _pendingToolClick = null;
map.getCanvas().addEventListener('mousedown', e => {
if (!zoneDrawMode) return;
const lngLat = map.unproject([e.offsetX, e.offsetY]);
_zoneDrawOnMouseDown({ lngLat, preventDefault: () => e.preventDefault() });
});
/* A FINGER IS ALSO A POINTER.
Before this, zone editing had no touch path at all: dragging a corner
was bound to mousedown/mousemove/mouseup only, so on a phone or a
tablet the corners could be seen and never moved. A browser does
synthesise a click after a tap, which is why placing a zone worked on
a phone while shaping one did not - the failure looked like a fiddly
control rather than an absent one.
Touch coordinates are page-relative, so they are converted through the
canvas rectangle rather than read from offsetX/offsetY, which a touch
event does not carry. preventDefault is called only once a corner has
actually been grabbed, so an ordinary one-finger pan over the map is
untouched. */
/* Which add-a-point dots fit on an edge depends on how long that edge
is ON SCREEN, so it changes with the zoom. Without this the dots are
computed once when the zone is drawn and then go stale: zoom out and
the drawing still shows dots the hit test has already suppressed, so
what you see stops being what you can press. Redrawn on zoom, and only
when a zone exists. */
map.on('zoomend', () => {
if (zoneDrawMode && zoneDrawPoints.length >= 3) _zoneDrawUpdateLayers(false);
});
(function attachZoneTouch() {
const canvas = map.getCanvas();
const pointOf = touch => {
const r = canvas.getBoundingClientRect();
return map.unproject([touch.clientX - r.left, touch.clientY - r.top]);
};
canvas.addEventListener('touchstart', e => {
if (!zoneDrawMode || e.touches.length !== 1) return;
_zoneDrawOnMouseDown({ lngLat: pointOf(e.touches[0]), preventDefault: () => {} });
if (zoneDrawDragging) e.preventDefault();
}, { passive: false });
canvas.addEventListener('touchmove', e => {
if (!zoneDrawMode || !zoneDrawDragging || e.touches.length !== 1) return;
e.preventDefault();
_zoneDrawOnMouseMove({ lngLat: pointOf(e.touches[0]) });
}, { passive: false });
const endTouch = () => { if (zoneDrawMode && zoneDrawDragging) _zoneDrawOnMouseUp(); };
canvas.addEventListener('touchend', endTouch);
canvas.addEventListener('touchcancel', endTouch);
})();
map.on('click', e => {
if (measureMode) {
_pendingToolClick = setTimeout(() => {
_pendingToolClick = null;
if (!measureClosed) {
measurePoints.push([e.lngLat.lng, e.lngLat.lat]);
updateMeasureLayers();
updateMeasureDisplay();
}
}, CLICK_DEBOUNCE_MS);
return;
}
if (zoneDrawMode) { _zoneDrawOnClick(e); return; }
if (radiusMode) { doRadiusSearch(e.lngLat.lng, e.lngLat.lat); return; }
if (radiusAreaMode) { doRadiusAreaMeasure(e.lngLat.lng, e.lngLat.lat); return; }
if (!_visibleInteractiveIds.length) return;
const features = map.queryRenderedFeatures(e.point, { layers: _visibleInteractiveIds });
if (!features.length) return;
const p = features[0].properties || {}; const name = p.name || p.SiteName || p['Site Name'] || 'Unnamed Asset';
if (p.type === 'supermarket') {
const address = [p.street, p.city, p.postcode].filter(Boolean).join(', '); const area = p.area_m2 ? `${p.area_m2.toLocaleString()} m²` : '';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:${p.colour || '#00ffff'};font-size:13px">${escapeHTML(p.brand || name)}</b><br>${p.name && p.name !== p.brand ? `<span style="color:#fff">${escapeHTML(p.name)}</span><br>` : ''}<span style="color:#888">${escapeHTML(address)}</span><br>${area ? `<span style="color:#ffae00">Area: ${esc … [line shortened here: 445 characters; full line on GitHub]
}
if (p.type === 'elizabeth_line_station') {
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#60399E;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">Elizabeth Line Station</span><br><span style="color:#555;font-size:10px">${escapeHTML(p.operator)}</span></div>`); return;
}
if (p.type === 'stadium') {
const club = p.club ? `<span style="color:#fff">${escapeHTML(p.club)}</span><br>` : ''; const cap = p.capacity && p.capacity !== "Unknown" ? `Capacity: ${Number(p.capacity).toLocaleString()}` : 'Capacity: Unknown';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#e5ff00;font-size:13px">${escapeHTML(name)}</b><br>${club}<span style="color:#888">${escapeHTML(p.sport)}</span><br><span style="color:#ffae00">${escapeHTML(cap)}</span></div>`); return;
}
if (p.type === 'naei_emitter') {
const tonnes = p.emission_tco2e ? Number(p.emission_tco2e).toLocaleString('en-GB', { maximumFractionDigits: 0 }) : 'Unknown';
const dataLabel = p.datatype === 'O' ? 'Self-reported by the company' : p.datatype === 'M' ? 'Estimated by the government' : 'Official figures';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:8px 10px;border:1px solid #ff4400;border-radius:4px;min-width:220px;max-width:280px"><b style="color:#ff4400;font-size:13px">🏭 ${escapeHTML(name)}</b><br><span style="color:#888;font-size:10px">Run by: ${escapeHTML(p.operator || 'Unknown')}</span><br><span style="color:#aaa;font-size:10px">Industry: ${es … [line shortened here: 952 characters; full line on GitHub]
}
const tech = p.tech || ''; const rawTech = p.raw_tech || p.type || tech; const voltage = p.voltage || ''; const capacity = parseFloat(p.capacity) || 0; const powerKw = p.power_kw || null; const connectors = p.connectors || ''; const status = p.status || ''; const operator = p.operator || ''; const mounting = (p.mounting && p.mounting !== 'nan') ? ` | ${escapeHTML(p.mounting)}` : ''; co … [line shortened here: 808 characters; full line on GitHub]
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">${escapeHTML(rawTech)}${voltage ? ` | ${escapeHTML(voltage)}` : ''}${mounting}</span><br>${evFields}${capStr ? `<span style="color:#ffae00">${escapeHTML(capStr)}</span>` : ''}${status ? `<span style="color:${stat … [line shortened here: 578 characters; full line on GitHub]
});
map.on('dblclick', e => {
if (_pendingToolClick) { clearTimeout(_pendingToolClick); _pendingToolClick = null; }
if (zoneDrawMode) { e.preventDefault(); return; }
if (!measureMode || measurePoints.length < 2) return;
e.preventDefault();
measureClosed = true;
updateMeasureLayers();
updateMeasureDisplay();
});
window.addEventListener('mouseup', () => { if (zoneDrawMode) _zoneDrawOnMouseUp(); });
map.on('mousemove', e => {
if (zoneDrawMode) { _zoneDrawOnMouseMove(e); return; }
if (measureMode || radiusMode || radiusAreaMode) { map.getCanvas().style.cursor = 'crosshair'; return; }
if (!_visibleHoverIds.length) { map.getCanvas().style.cursor = ''; return; }
const now = Date.now();
if (now - _lastHoverMs < HOVER_THROTTLE_MS) return;
_lastHoverMs = now;
if (_lastMouseMoveRaf) return;
_lastMouseMoveRaf = requestAnimationFrame(() => {
_lastMouseMoveRaf = null;
const features = map.queryRenderedFeatures(e.point, { layers: _visibleHoverIds });
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
});
});
GRID_CONFIG.forEach(group => { group.layers.forEach(layer => { if (layer.preload && layer.id !== '400') hydrateLayer(layer.id); }); });
const state400 = RUNTIME_STATE['400'];
if (state400) { state400.loaded = true; state400.loading = false; updateUIState('400', 'OK'); }
focusCanonicalProjectDeepLink();
});
};
/**
* Module: geodesy
*
* One Earth radius for the whole estate, and the three operations every
* measurement here is built from. This existed three times tonight - in
* the sandbox, in the substation cartridge and in the data repository -
* which is exactly how two of them end up on different radii without
* anyone noticing.
*
* Radius 6378.137 km, matching Ventusltd/grid-distance-maths. Haversine.
* No projection, no turf, no second radius for geometry.
*
* Pure functions. No DOM, no network, no state.
*/
(() => {
'use strict';
const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
if (NS.geodesy) return;
const EARTH_RADIUS_KM = 6378.137;
const DEG = Math.PI / 180;
function distanceKm(lon1, lat1, lon2, lat2) {
const dLat = (lat2 - lat1) * DEG;
const dLon = (lon2 - lon1) * DEG;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
/* atan2, in this operand order, because that is the form every version
of this estate has shipped - ventus-corev8engine.js haversine() and
every cartridge carried from it.
-------------------------------------------------------------------
The extraction wrote 2 * R * asin(sqrt(a)) instead. Algebraically the
same; numerically one unit in the last place apart, which the
all-versions proof caught on West Burton Solar to Cottam:
7.050150827184836 shipped, 7.050150827184837 from the module. It is
1e-15 km and changes no figure any reader will ever see - and it is
still wrong, because the claim being made is PARITY. A module that is
nearly the incumbent is a module that has to be argued about every
time a digit differs. */
return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
/* A polygon reduces to the mean of its outer ring, not its first corner.
A substation drawn as a compound outline would otherwise be measured
from whichever vertex the mapper happened to start at.
Point, Polygon and MultiPolygon, and NOTHING ELSE. The first draft of
this module accepted any nested coordinate array and so returned a
mean for a LineString where the incumbent returns null; the parity
proof caught it against the live cartridge. Extraction is not the
moment to change behaviour, so the behaviour is pinned here and any
widening becomes its own version with its own reasoning.
One deliberate difference, on malformed input only: this returns null
where the incumbent would throw on a Point with no coordinates. No
real geometry reaches that path, and a proof asserts it. */
function representativePoint(geometry) {
if (!geometry) return null;
const { type, coordinates } = geometry;
if (type === 'Point') {
return Array.isArray(coordinates) && coordinates.length >= 2
? [coordinates[0], coordinates[1]] : null;
}
const ring = type === 'Polygon' ? coordinates && coordinates[0]
: type === 'MultiPolygon' ? coordinates && coordinates[0] && coordinates[0][0]
: null;
if (!Array.isArray(ring) || !ring.length) return null;
let sumLon = 0;
let sumLat = 0;
for (const point of ring) {
sumLon += point[0];
sumLat += point[1];
}
return [sumLon / ring.length, sumLat / ring.length];
}
/* OpenStreetMap's `voltage` is VOLTS at every magnitude, and a feature
may carry several separated by a semicolon. Magnitude is not the unit:
750 is a DC traction supply at a railway depot, not 750 kV. An audit
of the served payload found 229 features (3.95%) carrying a token
below 1,000, every one of which had been misread. An explicit `kv`
property is already kilovolts and is trusted as such. */
function voltagesKv(properties) {
if (!properties) return [];
const out = [];
const explicit = properties.kv ?? properties.KV;
if (explicit != null && String(explicit).trim() !== '') {
for (const token of String(explicit).match(/\d+(?:\.\d+)?/g) || []) {
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;
}
}