In this section
- UKPN Secondary Substations energy-data · gridatlas / atlas/modules/202612010912-ukpn-secondary-substations.js lines 1–282
- Single-Line Diagram (SLD) Sandbox Body geodesy · gridatlas / atlas/parts/202609012045-sld-sandbox-body.js lines 1–418
UKPN Secondary Substations
A JavaScript file in the atlas folder of GridAtlas covering grid UKPN secondary, using SHA-256 and uses data from UK Power Networks open data and the data-grid-GB repository.
energy-datagridatlas / atlas/modules/202612010912-ukpn-secondary-substations.js · lines 1–282 of 282 · version 2026-12-01 09:12 · pattern augmentPopup (shared by 2 files)
- What it does
- It draws grid UKPN secondary, UKPN transformers, 11kV and substations. Defines 21 functions or classes, including sharedDatabase, registerPinned, detailsFor, scalar, normalize. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- 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: 11kV, substations, 400kV.
- Inputs & outputs
- In: data source: data-grid-gb data; data source: UK Power Networks open data; Parquet file grid_ukpn_secondary.parquet; Parquet file ukpn_transformers.parquet; DuckDB queries. Voltage levels named: 400kV, 11kV.
- Downstream impact
- Used directly by 2 files: Build (gridatlas); Regional Interface Test (gridatlas). Reached from 3 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); CI PR Gate (gridatlas); Map Promotion Rehearsal (gridatlas).
- What it achieves
- It registers pinned (`registerPinned`) and binds map (`bindMap`). Native `ukConfig` extension, pinned UKPN transformer archive. Its code works with 11 kV and 400 kV. It responds to change events.
- Why it matters
- Imported by Build. Checked by Regional Interface Test.
- Application
- gridatlas · atlas/modules · script
- Uses
- none found
- Used by
- referenced by Build (new URL import.meta.url), referenced by Regional Interface Test (new URL import.meta.url), mentioned in Standalone (comment link)
- Produces
- sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, installZoomGate, controls, main, eligible
- Defines here
- sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, installZoomGate, controls, main, eligible, note, sync, augmentPopup, line, current, add, bindMap, attach, load
- 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/202612010912-ukpn-secondary-substations.js:1-282 · blob c9cf42138fea07af581e9f90f852ac2826f95aff · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Native ukConfig extension, pinned UKPN transformer archive. No synthetic data. */
(() => {
'use strict';
const W = window;
const ID = 'ukpn_secondary', ROUTE = '/gridatlas/ukpn-secondary-sites.map-ready';
const ARCHIVE = 'https://raw.githubusercontent.com/Ventusltd/data-grid-gb/2502549fed826106c70865047a540a170dd68919/ukpn-secondary/ukpn-secondary-site-transformers.zip';
const SHA = 'c75933d86f4872a5f54712c0a945c283bb9038323a2ae9567df51ba3ce1b75c5';
const SOURCE = 'UK Power Networks secondary site transformers';
// Published, immutable Parquet derivatives; source ZIP remains the independent oracle.
const DATA = 'https://raw.githubusercontent.com/Ventusltd/data-grid-gb/1fd3185a258f528768ca9137b721e6ec65ea3551/ukpn-secondary/202612010912/';
const MAP_FILE = 'grid_ukpn_secondary.parquet', DETAIL_FILE = 'ukpn_transformers.parquet';
const pins = {
[MAP_FILE]: {bytes:870439,sha:'32cb071845049e6955421baa31d59799f5e4c8a24d07271cca01f3833f644991'},
[DETAIL_FILE]: {bytes:3930813,sha:'3c55aeebd0a92cee6fc53d4a13a99de3faf431565832c4dce1e513599fcf0c7e'}
};
const metrics = W.__GRIDATLAS_UKPN_DATA__ = {mapRequests:0,detailRequests:0,mapMs:null,detailMs:null,mapRows:null,sharedRuntime:false};
async function sharedDatabase() {
// The immutable bridge starts the one page-wide runtime after 400 kV readiness.
// Do not instantiate another worker or WASM heap here.
const until=performance.now()+30000;
while(!W.__GRIDATLAS_DUCKDB_RUNTIME__?.promise && performance.now()<until)
await new Promise(resolve=>W.setTimeout(resolve,50));
const held=W.__GRIDATLAS_DUCKDB_RUNTIME__;
if(!held?.promise)throw Error('UKPN shared DuckDB runtime unavailable');
const {database}=await held.promise;
metrics.sharedRuntime=true;
return database;
}
async function registerPinned(database,name) {
const pin=pins[name];
if(name===MAP_FILE)metrics.mapRequests++;else metrics.detailRequests++;
const response=await previousFetch(DATA+name,{cache:'force-cache',redirect:'error',credentials:'omit',signal:AbortSignal.timeout(30000)});
if(!response.ok)throw Error('UKPN Parquet HTTP '+response.status);
const bytes=new Uint8Array(await response.arrayBuffer());
const digest=[...new Uint8Array(await W.crypto.subtle.digest('SHA-256',bytes))].map(n=>n.toString(16).padStart(2,'0')).join('');
if(bytes.byteLength!==pin.bytes||digest!==pin.sha)throw Error('UKPN Parquet integrity mismatch: '+name);
await database.registerFileBuffer(name,bytes);
}
let registeredDetails=null;
async function detailsFor(site) {
const start=performance.now(), database=await sharedDatabase();
// Only acquire the full transformer register after a real high-zoom card selection.
// Query one exact FLOC; never add the entire register to MapLibre properties.
registeredDetails ||= registerPinned(database,DETAIL_FILE).catch(error=>{registeredDetails=null;throw error;});
await registeredDetails;
const connection=await database.connect();
try {
const escaped=String(site).replaceAll("'","''");
const table=await connection.query("SELECT feature_json FROM read_parquet('"+DETAIL_FILE+"') WHERE site_id = '"+escaped+"' ORDER BY source_row");
const scalar=v=>typeof v==='number'&&Number.isFinite(v)||typeof v==='string'&&v.trim()?v:null;
const distinct=new Map();
for(const raw of table.toArray()){
const row=typeof raw.toJSON==='function'?raw.toJSON():raw;
const p=JSON.parse(String(row.feature_json)).properties;
if(p.secondarysitefunctionallocation!==site)throw Error('UKPN detail identity mismatch');
const detail=[p.transformerfunctionallocation,scalar(p.primarywinding),scalar(p.secondarywinding),scalar(p.onanrating),scalar(p.opvolts)];
distinct.set(JSON.stringify(detail),detail);
}
metrics.detailMs=performance.now()-start;
return [...distinct.values()];
} finally {await connection.close();}
}
function normalize(raw) {
if (raw?.type !== 'FeatureCollection' || raw.features?.length !== 74719)
throw Error('UKPN source row count mismatch');
const sites = new Map(), transformers = new Set();
let points = 0;
for (const f of raw.features) {
const p = f.properties || {}, site = p.secondarysitefunctionallocation;
if (typeof site !== 'string' || !site || typeof p.transformerfunctionallocation !== 'string' ||
!['EPN','SPN','LPN'].includes(p.dno)) throw Error('UKPN identity invalid');
transformers.add(p.transformerfunctionallocation);
let s = sites.get(site);
if (!s) {s = {site, dno:p.dno, coords:null, ids:new Set(), voltages:new Set(), details:new Map()}; sites.set(site,s);}
if (s.dno !== p.dno) throw Error('UKPN conflicting network');
s.ids.add(p.transformerfunctionallocation);
// Retain distinct published values, not an arbitrary winner for duplicate FLOCs.
const scalar=v=>typeof v==='number'&&Number.isFinite(v)||typeof v==='string'&&v.trim()?v:null;
const detail=[p.transformerfunctionallocation,scalar(p.primarywinding),scalar(p.secondarywinding),scalar(p.onanrating),scalar(p.opvolts)];
s.details.set(JSON.stringify(detail),detail);
if (typeof p.primarywinding === 'number' && p.primarywinding > 0) s.voltages.add(p.primarywinding);
if (f.geometry === null) continue;
const c = f.geometry?.coordinates;
if (f.geometry?.type !== 'Point' || !Array.isArray(c) || c.length !== 2 ||
!c.every(Number.isFinite) || c[0] < -11 || c[0] > 3 || c[1] < 49.5 || c[1] > 61.5)
throw Error('UKPN invalid point');
points++;
if (s.coords && (s.coords[0] !== c[0] || s.coords[1] !== c[1])) throw Error('UKPN conflicting site points');
s.coords = c;
}
const features = [...sites.values()].filter(s=>s.coords).sort((a,b)=>a.site < b.site ? -1 : a.site > b.site ? 1 : 0).map(s=>({
type:'Feature', id:s.site, geometry:{type:'Point',coordinates:s.coords},
properties:{name:s.site, type:'Secondary substation (transformer register)', operator:'UK Power Networks ('+s.dno+')',
voltage:[...s.voltages].sort((a,b)=>a-b).map(v=>v+' kV primary').join(', '),
transformer_count:s.ids.size, ukpn_transformers:JSON.stringify([...s.details.values()]), source:'UK Power Networks secondary site transformers', asset_class:'secondary_substation'}
}));
if (sites.size !== 56309 || features.length !== 54558 || points !== 56685 || transformers.size !== 74712)
throw Error('UKPN source closure mismatch');
return {type:'FeatureCollection',features};
}
async function unpack(bytes) {
const v = new DataView(bytes);
if (bytes.byteLength !== 2068796 || v.getUint32(0,true) !== 0x04034b50 ||
v.getUint16(6,true) !== 0 || v.getUint16(8,true) !== 8 ||
v.getUint32(18,true) !== 2068618 || v.getUint32(22,true) !== 33070781)
throw Error('UKPN archive structure mismatch');
const start = 30 + v.getUint16(26,true) + v.getUint16(28,true);
const stream = new Blob([bytes.slice(start,start+2068618)]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
const raw = await new Response(stream).arrayBuffer();
if (raw.byteLength !== 33070781) throw Error('UKPN unpacked size mismatch');
return normalize(JSON.parse(new TextDecoder().decode(raw)));
}
function extend(options) {
if (!Array.isArray(options.config)) throw Error('GridAtlas ukConfig absent');
if (options.config.flatMap(g=>g.layers).some(l=>l.id===ID)) return options;
let found = false;
const layer = {id:ID,label:'Secondary subs (UKPN)',color:'#35e6bb',type:'point',
radius:['interpolate',['linear'],['zoom'],14,3,18,8],url:ROUTE,minzoom:14,preload:false};
const config = options.config.map(g=>{
if (!g.layers.some(l=>l.id==='11kv')) return g;
found=true; return {...g,layers:[...g.layers.map(l=>l.id==='11kv'?{...l,minzoom:13,preload:false,label:'11 kV (OSM - quarantined)'}:l),layer]};
});
if (!found) throw Error('GridAtlas UK topology group absent');
return {...options,config};
}
// Gate native checkbox activation before the native handler can enqueue work.
// No second map, network queue or source is created. MapLibre still owns rendering.
function installZoomGate() {
const doc=W.document;
if (!doc) return null;
let map=null;
const deferred=new Set();
const controls=id=>[...doc.querySelectorAll('input[data-layer-id="'+id+'"]')];
const main=()=>doc.querySelector('#scada-ui-container input[data-layer-id="'+ID+'"]');
const eligible=()=>!!map && map.getZoom()>=14 && !!main()?.checked;
const note=(input,message)=>{
const label=input.closest('label');
if (!label) return;
let hint=label.querySelector('[data-ukpn-zoom-hint]');
if (!hint) {
hint=doc.createElement('small'); hint.dataset.ukpnZoomHint='1';
hint.style.cssText='font-size:10px;color:#aaa;display:block;white-space:normal';
label.appendChild(hint);
}
hint.textContent=message;
hint.hidden=!message;
hint.style.display=message?'block':'none';
};
function sync() {
for (const input of controls('11kv')) {
input.checked=false;input.disabled=true;
note(input,'Historical OSM; not verified UKPN data');
}
for (const input of controls(ID)) note(input,input.checked && (!map || map.getZoom()<14)?'Zoom in to view (14+)':'');
if (deferred.has(ID) && eligible()) {
deferred.delete(ID);
main().dispatchEvent(new W.Event('change',{bubbles:true}));
}
}
// Extend only the native popup that the immutable engine already opened.
// No second popup, map, or competing click-selection path.
function augmentPopup() {
const popup=map?.getContainer().querySelector('.maplibregl-popup-content');
if (!popup) return;
const heading=popup.querySelector('b');
if (!heading || !popup.textContent.includes('Secondary substation (transformer register)')) return;
if (map.getZoom()<14 || !main()?.checked) {W._closePopupKeepShape?.();return;}
const feature=map.getSource('src-'+ID)?.serialize().data?.features?.find(f=>f.id===heading.textContent);
if (!feature) return;
let card=popup.querySelector('[data-ukpn-detail]');
if (!card) {
card=doc.createElement('section');card.dataset.ukpnDetail='1';
card.style.cssText='font:12px/1.4 monospace;color:#ddd;background:#000;padding:6px;max-height:min(32vh,180px);overflow:auto;overflow-wrap:anywhere';
card.setAttribute('aria-label','UKPN substation information');
popup.appendChild(card);
}
const detailLevel=map.getZoom()>=16?'full':'summary';
if (card.dataset.level===detailLevel && card.dataset.site===feature.id) return;
card.dataset.level=detailLevel;card.dataset.site=feature.id;
card.replaceChildren();
const line=(label,value)=>{
const item=doc.createElement('div');item.textContent=label+': '+(value??'Not supplied');card.appendChild(item);
};
const p=feature.properties;
line('Transformer count',p.transformer_count);
line('Location',feature.geometry.coordinates.map(v=>v.toFixed(6)).join(', ')+' (longitude, latitude)');
if (detailLevel==='full') {
const detailBox=doc.createElement('div');
detailBox.textContent='Loading transformer records…';card.appendChild(detailBox);
const current=()=>card.isConnected && card.dataset.level==='full' && card.dataset.site===feature.id && detailBox.isConnected && map.getZoom()>=16 && main()?.checked;
detailsFor(feature.id).then(details=>{
if(!current())return;
if(new Set(details.map(row=>row[0])).size!==p.transformer_count)throw Error('UKPN transformer count mismatch');
detailBox.replaceChildren();
const add=(label,value)=>{const item=doc.createElement('div');item.textContent=label+': '+(value??'Not supplied');detailBox.appendChild(item);};
const groups=new Map();
for(const row of details){if(!groups.has(row[0]))groups.set(row[0],[]);groups.get(row[0]).push(row);}
for(const [id,rows] of groups){
add('Transformer FLOC',id);
if(rows.length>1)add('Source records','Conflicting published values retained');
for(const [,primary,secondary,rating,operating] of rows){
add('Primary winding (source value)',primary);
add('Secondary winding (source value)',secondary);
add('ONAN rating (source value)',rating);
add('Operating voltage (source value)',operating);
}
}
}).catch(error=>{if(current())detailBox.textContent='Transformer details unavailable: '+String(error.message||error);});
} else line('Transformer details','Zoom to 16 or higher');
const credit=doc.createElement('a');
credit.href='https://ukpowernetworks.opendatasoft.com/explore/assets/ukpn-secondary-site-transformers/';
credit.target='_blank';credit.rel='noopener noreferrer';credit.style.color='#7eead0';
credit.textContent='UK Power Networks · 27 Nov 2025 · CC BY 4.0';
card.appendChild(credit);
line('Interpretation','Installed ratings are not available capacity');
}
function bindMap() {
if (map) return;
map=W.__GRIDATLAS_V9_MAP__ || null;
if (map) {map.on('load',sync);map.on('zoomend',()=>{sync();augmentPopup();});map.on('click',()=>W.setTimeout(augmentPopup,0));sync();}
}
doc.addEventListener('change',event=>{
const input=event.target,id=input?.dataset?.layerId;
if (id==='11kv') {
event.stopImmediatePropagation();sync();return;
}
if (id!==ID) return;
bindMap();
if (!input.checked) {deferred.delete(ID);for(const c of controls(ID))c.checked=false;sync();augmentPopup();return;}
if (!map || map.getZoom()<14) {
event.stopImmediatePropagation();
for(const c of controls(ID))c.checked=true;
deferred.add(ID);sync();
} else {deferred.delete(ID);sync();}
},true);
let frames=0;
function attach() {bindMap();if(!map && ++frames<1200)W.requestAnimationFrame(attach);}
attach();
return {canAcquire:eligible, defer(){if(main()?.checked)deferred.add(ID);W.setTimeout(sync,0);}};
}
let zoomGate=null;
const originalInit = W.initVentusMap;
if (typeof originalInit !== 'function') throw Error('GridAtlas native init unavailable');
W.initVentusMap = function(options) {zoomGate=installZoomGate();return originalInit.call(this,extend(options));};
const previousFetch = W.fetch.bind(W);
let pending = null;
async function load() {
const started=performance.now(), database=await sharedDatabase();
await registerPinned(database,MAP_FILE);
let connection;
try {
connection=await database.connect();
const table=await connection.query("SELECT feature_id, geometry_json, properties_json FROM read_parquet('"+MAP_FILE+"') ORDER BY feature_index");
const features=table.toArray().map(raw=>{
const row=typeof raw.toJSON==='function'?raw.toJSON():raw;
const id=String(row.feature_id), geometry=JSON.parse(String(row.geometry_json)), properties=JSON.parse(String(row.properties_json));
if(!id||properties.name!==id||geometry.type!=='Point'||!geometry.coordinates?.every(Number.isFinite))throw Error('UKPN map row invalid');
return {type:'Feature',id,geometry,properties};
});
if(features.length!==54558||new Set(features.map(f=>f.id)).size!==54558)throw Error('UKPN map closure mismatch');
metrics.mapRows=features.length;metrics.mapMs=performance.now()-started;
return {type:'FeatureCollection',features};
} finally {
try {if(connection)await connection.close();} finally {await database.dropFile(MAP_FILE);}
}
}
W.fetch = async function(input,init) {
const url = new URL(typeof input==='string'?input:input.url||input.href,W.location.href);
if (url.origin!==W.location.origin || url.pathname!==ROUTE) return previousFetch(input,init);
if (init?.signal?.aborted) throw new DOMException('Aborted','AbortError');
// Recheck at native queue acquisition, in case zoom or visibility changed while queued.
if (zoomGate && !zoomGate.canAcquire()) {zoomGate.defer();throw new DOMException('UKPN acquisition deferred until zoom 14','AbortError');}
// Headers first, as in the streaming Parquet bridge; native hydrateLayer owns the UI.
return new Response(new ReadableStream({start(controller){
pending ||= load().finally(()=>{pending=null;});
pending.then(fc=>{controller.enqueue(new TextEncoder().encode(JSON.stringify(fc)));controller.close();},
error=>controller.error(error));
}}),{headers:{'Content-Type':'application/geo+json','X-GridAtlas-Data-Plane':'PINNED_UKPN_PARQUET'}});
};
W.__GRIDATLAS_MODULES__ ||= {};
W.__GRIDATLAS_MODULES__.ukpnSecondary = Object.freeze({normalize,unpack,extend,archive:ARCHIVE,sha256:SHA,source:SOURCE});
})();Single-Line Diagram (SLD) Sandbox Body
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.
Set aside from the main view: 96% of its lines are the same as atlas/parts/202609040229-sld-sandbox-arrival-identity.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Single-Line Diagram (SLD) Sandbox Arrival Identity; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9622 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040229-sld-sandbox-arrival-identity.js:1-5948 2c1486ea5aef879022fc222d4363b779d22e165b
- sha256 4494ff9a6fd9db05b7208e2e420f65705b1eaac919f77995f13ff45c3e9e69b9
- target sha256 7c0d4eb1ef95c845bb8bcbf9fa7020eb009c025ed3edbb34afa0cc085c20b5d5
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/parts/202609012045-sld-sandbox-body.js · lines 1–418 of 5782 · version 2026-09-01 20:45 · Not reached from any entry point (candidate for review) · pattern provisionalDeclaredConnection (shared by 9 files)
- What it does
- It maps grid substations, solar, transformers and 400kV. Defines 183 functions or classes, including coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: solar, transformers, 400kV, 750kV, 415kV, 275kV.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; browser storage (getItem); DuckDB queries; form fields (user input). Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 66kV, 33kV.
- What it achieves
- It resolves declared connection (`resolveDeclaredConnection`), opens corridor sheet (`openCorridorSheet`) and runs grid point (`runGridAtPoint`). GridAtlas cartridge — neon substation links and the SLD layout sandbox. Its code works with 400 kV, 33 kV and 132 kV. It responds to click, keydown and touchstart events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/parts · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- none found
- Used by
- none found
- Produces
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet
- Defines here
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet
- 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/parts/202609012045-sld-sandbox-body.js:1-418 · blob e1451b1f9330cecde3e94fbe6ad608a6425c028d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
/**
* GridAtlas cartridge — neon substation links and the SLD layout sandbox.
*
* Assembled under the generation named in the header above; this part
* states no generation of its own, because a second identity inside the
* same file is one that can disagree with the first. Slot: replace-script for
* 202608292126-pre-snapped-config-adapter.js.
*
* WHAT IT DOES
* ------------
* Select a solar, battery or onshore wind project and the map draws animated
* neon lines from it to the nearest substations at 33 kV and above. The same
* distances are written onto the project card the engine has just opened,
* marked BETA, with the reasons a distance is not a connection stated on the
* card itself rather than hidden in a tooltip.
*
* WHY IT REPLACES THE CONFIG ADAPTER RATHER THAN ADDING A SCRIPT
* -------------------------------------------------------------
* The composer in atlas/index.html supports exactly one slot, `replace-script`.
* There is no append slot, and inventing one would mean changing the composer,
* which is a larger contract change than this feature is worth. So this
* cartridge carries the pre-snapped config adapter's behaviour VERBATIM -- same
* layer ids, same closure assertion, same failure mode, same public state
* object -- and adds the link layer beside it. The immutable shell is not
* touched, and `__GRIDATLAS_PRE_SNAPPED_CONFIG__` still reports exactly what it
* reported before, so anything asserting on it keeps working.
*
* HOW IT HOOKS IN WITHOUT SHELL MUTATION
* --------------------------------------
* Two decorators, both of things the engine has already published by the time
* this script runs:
*
* window.initVentusMap wrapped for the pre-snap config, as before.
* maplibregl.Map wrapped to capture the instance, because the engine
* keeps `map` in a closure and returns nothing. The
* engine constructs its map inside initVentusMap, which
* runs after this file, so the constructor is still
* ours to wrap.
*
* THE MEASUREMENT
* ---------------
* Haversine on R = 6378.137 km, the same constant as ventus-corev8engine.js,
* pipelinenews and Ventusltd/grid-distance-maths, so a distance read here
* equals the same distance read there. Substations are mapped as points AND as
* polygons; a polygon is reduced to its ring mean, because its first vertex is
* a corner rather than the site.
*
* Scope is 33 kV and above. 11 kV is rare for utility-scale export and where it
* occurs is often a private network behind the meter, so it is not a screening
* signal. `voltage` is written `33000`, `33000;11000` for two voltages, and
* `33000:11000` for a transformer ratio -- a 33/11 primary still carries 33 kV.
*
* WHAT A LINE IS NOT
* ------------------
* A straight line to mapped geometry. Not a cable route, not a connection
* length, no wayleave, crossing, terrain or consent content. A mapped
* substation does not confirm capacity, voltage suitability or connection
* rights, and fault level and thermal headroom cannot be inferred from distance
* at all -- they need DNO network data such as source impedance and a
* connection study, alongside right of way, wayleaves and easements, land
* control and consent. The card says all of that on screen.
*/
(() => {
'use strict';
const GENERATION = '202609012045';
/* ══════════════════════════════════════════════════════════════════════
PART 1 — the pre-snapped config adapter, carried forward unchanged.
══════════════════════════════════════════════════════════════════════ */
const PRE_SNAPPED_LAYER_IDS = new Set(['400', '275', '220', '132', '66']);
const originalInit = window.initVentusMap;
if (typeof originalInit !== 'function') {
throw new Error('V8 engine init function is unavailable before map-ready adapter');
}
const state = {
schema: 'gridatlas.pre-snapped-config-adapter.v1',
generation: '202608292126',
applied: false,
changed_layer_ids: [],
preserved_preload_flags: true,
failures: []
};
window.__GRIDATLAS_PRE_SNAPPED_CONFIG__ = state;
window.initVentusMap = function gridAtlasMapReadyInit(options) {
try {
const changed = [];
const config = options.config.map(group => ({
...group,
layers: group.layers.map(layer => {
if (!PRE_SNAPPED_LAYER_IDS.has(String(layer.id))) return layer;
if (layer.snap !== true) {
throw new Error(`expected V8 snap=true for topology layer ${layer.id}`);
}
changed.push(String(layer.id));
return { ...layer, snap: false };
})
}));
const expected = [...PRE_SNAPPED_LAYER_IDS].sort();
if (JSON.stringify([...changed].sort()) !== JSON.stringify(expected)) {
throw new Error(`pre-snapped layer closure mismatch: ${JSON.stringify(changed)}`);
}
state.applied = true;
state.changed_layer_ids = changed;
return originalInit({ ...options, config });
} catch (error) {
state.failures.push(String(error?.message || error));
throw error;
}
};
/* ══════════════════════════════════════════════════════════════════════
PART 2 — neon substation links.
══════════════════════════════════════════════════════════════════════ */
/* ONE geodesy, and it is the module's.
----------------------------------------------------------------------
This file used to declare R_ATLAS = 6378.137 and its own distanceKm,
four hundred lines from a second geodesy section, while the assembled
cartridge ALSO carried the geodesy module in front of it. Two radii and
two haversines in one served file, agreeing only because nobody had
changed one of them yet - and on 1 Sep 2026 the all-versions proof
found that they had in fact stopped agreeing in the last bit.
The Grid Finding Scope already did this correctly: it calls its module
and computes nothing itself. Geodesy was the exception. It is not now.
A missing module is a hard failure at load, not a fallback: a fallback
would silently restore exactly the duplication this removes. */
const GEODESY = (window.__GRIDATLAS_MODULES__ || {}).geodesy;
if (!GEODESY) throw new Error('sld-sandbox requires the geodesy module');
const R_ATLAS = GEODESY.EARTH_RADIUS_KM;
const DEG = Math.PI / 180;
const MIN_KV = 33;
const LINK_COUNT = 5; // how many substations to reach for
const MAX_LINK_KM = 40; // beyond this, silence is more honest
const SUBS_URL = 'data/grid_substations.geojson';
const SUBS_LAYER_ID = 'l-subs'; // engine convention: layer `l-<id>`, source `src-<id>`
// Project technologies this fires for. Onshore only: an offshore turbine's
// export route is nothing like a straight line to the nearest onshore
// substation, so drawing one would be a picture of a lie.
/* Every technology the register actually uses, and then some.
----------------------------------------------------------------------
This set was solar, bess and two spellings of wind, and it silently
rejected the rest. Counted against the shipped register: 2,399 onshore
wind projects and 109 offshore, so 2,508 of 7,680 — a third of the
register — had a MAP button that did nothing at all. Not an error, not a
message, nothing: the deep link tested membership and returned.
The register writes `wind_onshore`. The engine has had a `wind_onshore`
layer the whole time. Only this list disagreed with both.
So it no longer decides alone. The list below is the fast path, and
anything the ENGINE has a layer control for is accepted too — the engine
owns the layers, so the engine's vocabulary is the authority and this
stops being a place a technology can be forgotten. */
const PROJECT_TECHS = new Set([
'solar', 'solar_operational', 'solar_roof',
'bess', 'bess_operational',
'wind', 'wind_onshore', 'wind_onshore_operational',
'wind_offshore', 'wind_offshore_operational',
// The rest of the engine's own generation and storage dashboard, read off
// the live page rather than guessed. Note wind_onshore is NOT among the
// engine's layer ids -- it has `wind` and `wind_onshore_operational` --
// yet the register writes wind_onshore for 2,399 projects. Asking the
// engine alone would still have missed every one of them, which is why the
// explicit entry above is not redundant with the lookup below.
'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal',
'flywheel', 'caes', 'act',
/* `other` is what the register writes for a category it has no
bucket for. Over the 11,069-row REPD product this Atlas's search
lane reads, 25 DESNZ categories normalise to 14 ids and `other` was
the only one missing here - 4 projects, 2 Unknown and 2 Air Source
Heat Pumps. Not many; not zero; and written again the next time the
register gains a category. */
'other'
]);
/* Which technologies measure, and what each measurement is OF, is owned by
the technology-coverage module rather than by this file. It is assembled
into this cartridge ahead of this part, so it is here by the time any of
this runs; the fallback below exists only so a proof can load this part
alone, and it reproduces the module's answer rather than a different one.
Offshore NO LONGER WITHHOLDS. It used to open a card and draw nothing, on
reasoning about export cables and landfalls that was right about routes
and wrong about whether to measure at all. An offshore project's export
cable does land at an onshore substation, so the distance is a
measurement of something real. What changed is the answer; what did not
change is a single word of the route reasoning, which the module now
prints beside the number instead of instead of it. */
const coverage = (() => {
try {
const module = window.__GRIDATLAS_MODULES__?.technologyCoverage;
if (module && typeof module.policy === 'function') return module;
} catch (_) { /* fall through to the local reproduction */ }
const OFF = new Set(['wind_offshore', 'wind_offshore_operational']);
return {
policy: (tech) => ({ technology: tech || null, measure: true,
offshore: OFF.has(String(tech || '')),
sample: 'nearest of the mapped substations at or above the voltage '
+ 'floor that this search could see',
notes: [] }),
namedOffshore: () => false
};
})();
const OFFSHORE_TECHS = new Set(['wind_offshore', 'wind_offshore_operational']);
function isProjectTech(tech) {
if (!tech) return false;
if (PROJECT_TECHS.has(tech)) return true;
// Ask the engine. If it has a control for this layer, it is a technology
// this map knows about, whatever this cartridge was written knowing.
try {
return Boolean(document.querySelector(
'input[type=checkbox][data-layer-id="' + String(tech).replace(/"/g, '') + '"]'));
} catch (error) {
return false;
}
}
// SCADA on a dark map, not arcade neon. These are the muted siblings of the
// engine's own layer colours: enough saturation to read as live, low enough
// not to shout over the basemap or the grid layers underneath.
const TECH_COLOUR = {
solar: '#d8c96a', solar_operational: '#d8c96a', solar_roof: '#d8c96a',
bess: '#d9963c', bess_operational: '#d9963c',
wind: '#6fb582', wind_onshore: '#6fb582', wind_onshore_operational: '#6fb582',
// Offshore reads cooler than onshore: it is the one technology here whose
// links are deliberately not drawn, and it should not look like the others.
wind_offshore: '#5f9fb5', wind_offshore_operational: '#5f9fb5',
biomass: '#b58f6f', hydro: '#6f9fd8', hydrogen: '#a98fd8',
tidal: '#5fb5a8', geothermal: '#b57f6f',
flywheel: '#9f9fb5', caes: '#9f9fb5', act: '#9f9fb5'
};
const SUBSTATION_COLOUR = '#5fbdc2'; // teal, the substation end of a link
/* ── the 400 kV public record ────────────────────────────────────────
The nearest-substations list is a measurement and nothing more. But
the DCO-scale schemes each carry a PUBLIC declared point of connection
at 400 kV - usually through a new customer substation consented within
the scheme itself - and this card used to say nothing about it while
listing closer 33 and 132 kV points, which read as connecting them to
the wrong network. The rule holds: bind to the public record or say
nothing. Every entry below is sourced from Development Consent Orders,
Planning Inspectorate documents, or public project statements; the
table binds a register identity to a NAMED substation in the served
payload, and the distance shown is measured, never asserted. */
const DECLARED_COLOUR = '#d8b64a'; // gold: declared, and the far end exists today
/* Pink: declared, and the thing at the far end has not been built. One
Earth's point of connection is a National Grid substation that does not
exist yet; Thorpe Marsh's is under construction. Drawing those in the
same gold as a connection into a live substation would say something
untrue about the network, so they get their own colour and the card
says which it is. The distinction is taken from the public record, not
from the map: an unbuilt substation can be absent from OSM, or present
because someone mapped the consented site. */
const DECLARED_UNBUILT_COLOUR = '#d87aa8';
/* The table itself, and the three functions that bind it to the payload,
moved to the declared-connections module at generation 202609012128.
The body keeps the colours (rendering) and the state; the record is
read from the module, which a proof can open on its own and a cut
hashes on its own. A missing module is a hard failure at load, for
the same reason as geodesy: a fallback would quietly restore a second
copy of the table. */
const DECLARED = (window.__GRIDATLAS_MODULES__ || {}).declaredConnections;
if (!DECLARED) throw new Error('sld-sandbox requires the declared-connections module');
let currentRepdRef = null;
let currentDeclared = null;
let currentNearest400 = null;
/* The coverage policy for the CURRENT selection. It carries no arithmetic
and changes no result - it decides only which sentences go under the
distances. The measurement itself is coordinates, a candidate set and a
distance, and reads no technology at all. */
let currentPolicy = null;
/* The capacity Pipeline News sent, kept where the network card can
reach it. Without this the powerflow answer would have to invent a
figure, and an invented megawatt is exactly the kind of number that
gets quoted back as the project's own. */
let currentCapacityMw = null;
/* What the Order says is known the moment the identity is known: the
substation, the voltage class, the route, the consented works and the
citation need no payload, no fetch and no map. On a phone that is the
difference between a card that answers and a card that waits. The
distance is the one part that must be measured, so it is the one part
marked pending until it has been. */
function provisionalDeclaredConnection(repdRef) {
return DECLARED.provisional(repdRef);
}
function resolveDeclaredConnection(repdRef, origin, subs) {
return DECLARED.resolve(repdRef, origin, subs);
}
function nearestTransmission(origin, subs) {
return DECLARED.nearestTransmission(origin, subs);
}
/* EVERY SUPERLATIVE CARRIES ITS SAMPLE.
--------------------------------------------------------------------
"Nearest 400 kV substation" is nearest among what this search could
see, and two different things limit that. The search runs over the
substation features the map has loaded, so the first number is how
many of them were actually eligible - counted by the measurement
itself, not assumed. And the operator's own published list is only
partly located: ETYS names substations and does not place them, so
the geometry comes from OpenStreetMap through a GridAtlas release and
a fraction of the network is invisible to any search by distance.
Both numbers are COMPUTED at render time from what was fetched. A
literal would go quietly false the day the pinned product moves -
Codex's join correction alone takes located points from 502 to 489 -
and a stale denominator under the word "nearest" is worse than none.
It states the sample. It does not grade the result. */
/* A straight line is not a route, and the card said nothing about it.
--------------------------------------------------------------------
ADDITIVE. The straight-line distance is unchanged, still first, still
the measurement; the corridor figure sits beside it and is labelled an
estimate every time it appears.
Only for a CABLE question. The factor is calibrated on cable circuits,
which follow the highway network; overhead line crosses open country
and measures 1.13. The module publishes that number and deliberately
offers no forOverhead(), so this cannot quietly become the answer to a
question it was not measured on.
Under about a kilometre the module withholds the estimate rather than
scaling, and the card says why: at that separation the straight line
between two site centroids is not measuring route factor at all. */
function corridorBeside(km) {
const module = (() => {
try { return window.__GRIDATLAS_MODULES__?.corridorEstimate || null; }
catch (_) { return null; }
})();
if (!module) return '';
const estimate = module.forCable(km);
if (!estimate) return '';
const basis = module.basis;
if (estimate.withheld) {
return ` <span class="neon-caveat">No corridor estimate at this `
+ `separation: ${escapeHtml(estimate.withheld)}.</span>`;
}
return ` · ~${estimate.km.toFixed(1)} km corridor estimate `
+ `(×${estimate.factor}, ${basis.within_15_pct}% of GB transmission `
+ `cable circuits within 15% of published length, `
+ `${basis.distinct_site_pairs} distinct site pairs). `
+ `<span class="neon-caveat">${escapeHtml(module.caveat)} `
+ `${escapeHtml(module.not_for_overhead)}</span>`;
}
/* A 44 px action, and a sheet that is the corridor figures in full.
--------------------------------------------------------------------
The card line beside each distance is one sentence. A reader who wants
the basis - what the factor was calibrated on, how wrong it typically
is, and what it is not for - should not have to take that from a
sentence, and on a phone there is no room to print it inline.
44 px because that is the smallest target a thumb hits reliably; the
estate's own layers toggle was widened to the same at 202609030116.
The sheet is opened three ways and all of them end in one function:
the button, a right-click on the map (the engine binds no contextmenu
- measured, zero occurrences in the shell, in index.html and in every
composed part), and a long press.
THE LONG PRESS DEFERS TO EVERYTHING. It arms on touchstart, and it is
cancelled by a movement of more than 10 px, by a second finger, by
touchend, and by an SLD drag already being in progress - the sandbox
binds its own touchstart for dragging the array, its handle and its
route pins, so this must never fire during one. A pan is a movement;
a pinch is a second finger; both cancel before the 500 ms is up. */
const CORRIDOR_SHEET = 'gridatlas-corridor-sheet';
let corridorSheetInstalled = false;
function corridorTargets() {
const rows = [];
if (currentDeclared && currentDeclared.kind !== 'circuit'
&& Number.isFinite(currentDeclared.km)) {
rows.push({ name: currentDeclared.poc, km: currentDeclared.km,
note: 'declared point of connection, from the public record' });
}
if (currentNearest400) {
rows.push({ name: currentNearest400.name, km: currentNearest400.km,
note: 'nearest mapped substation at 400 kV or above' });
if (currentNearest400.named && currentNearest400.named.name !== currentNearest400.name) {
rows.push({ name: currentNearest400.named.name, km: currentNearest400.named.km,
note: 'nearest NAMED substation at 400 kV or above' });
}
}
return rows;
}
function corridorAction() {
if (!corridorTargets().length) return '';
/* The card can render before the map is wired, and the button is
useless without the delegated listener. Installing here as well is
idempotent and removes the ordering dependency entirely. */
installCorridorSheet();
return `<button type="button" class="gridatlas-corridor-open" `
+ `data-gridatlas-corridor="1" `
+ `aria-haspopup="dialog">Explore route corridors \u203a</button>`;
}
function installCorridorSheet() {
if (corridorSheetInstalled) return;
corridorSheetInstalled = true;
const style = document.createElement('style');
style.textContent =