In this section
- Pilot UKPN energy-data · cosmic / tools/explore/theme/pilot-ukpn.css lines 1–30
- Pilot UKPN energy-data · cosmic / tools/explore/theme/pilot-ukpn.js lines 1–543
- Distribution Network Operator (DNO) Ecr energy-data · data-grid-gb / datacentres/fetchers/dno_ecr.py lines 1–20
Pilot UKPN
A style sheet in the theme folder of Cosmic.
energy-datacosmic / tools/explore/theme/pilot-ukpn.css · lines 1–30 of 30 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'ukpn'): 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.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- Pilot module W04 (TAPCHANGER-58): UKPN secondary substations panel + card.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · style sheet
- Uses
- none found
- Used by
- loaded by Pilot (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-ukpn.css:1-30 · blob 56e99f45d4b088fdea84f3f4ac74b3c1a744052d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
/* Pilot module W04 (TAPCHANGER-58): UKPN secondary substations panel + card. All selectors prefixed p-ukpn-. */
.p-ukpn-panel { display: flex; flex-direction: column; gap: 8px; min-width: 0; max-width: 100%; }
.p-ukpn-status { margin: 0; color: #a6adbb; overflow-wrap: anywhere; }
.p-ukpn-form { margin: 0; }
.p-ukpn-q { box-sizing: border-box; width: 100%; min-height: 44px; padding: 0 10px; font: 16px ui-monospace, Menlo, monospace; color: #fff;
background: #05080c; border: 1px solid #2f343d; border-radius: 6px; }
.p-ukpn-q:focus { border-color: #35e6bb; outline: none; }
.p-ukpn-chips, .p-ukpn-acts { display: flex; flex-wrap: wrap; gap: 6px; }
.p-ukpn-btn { font: 12px ui-monospace, Menlo, monospace; color: #9cdbff; background: rgba(11, 14, 20, .86); border: 1px solid #2f343d; border-radius: 6px;
min-height: 44px; min-width: 44px; padding: 0 12px; cursor: pointer; }
.p-ukpn-btn[aria-pressed="true"] { color: #04271f; background: #35e6bb; border-color: #35e6bb; }
.p-ukpn-btn:hover, .p-ukpn-item:hover { border-color: #35e6bb; color: #fff; }
.p-ukpn-head { margin: 4px 0 0; color: #35e6bb; letter-spacing: .08em; text-transform: uppercase; font-size: 11px; }
.p-ukpn-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
.p-ukpn-item { display: flex; flex-direction: column; align-items: flex-start; justify-content: center; gap: 2px; box-sizing: border-box; width: 100%;
min-height: 48px; padding: 4px 10px; text-align: left; font: 12px ui-monospace, Menlo, monospace; color: #fff;
background: rgba(11, 14, 20, .86); border: 1px solid #2f343d; border-radius: 6px; cursor: pointer; }
.p-ukpn-id { color: #35e6bb; overflow-wrap: anywhere; }
.p-ukpn-sub, .p-ukpn-dim { color: #a6adbb; font-size: 11px; overflow-wrap: anywhere; }
.p-ukpn-dim { margin: 4px 0; }
.p-ukpn-credit { color: #7eead0; overflow-wrap: anywhere; display: inline-block; min-height: 24px; }
.p-ukpn-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; margin: 0; }
.p-ukpn-dl { margin: 0 0 6px; display: grid; gap: 2px; }
.p-ukpn-dl div { display: flex; gap: 8px; min-width: 0; }
.p-ukpn-dl dt { color: #a6adbb; flex: 0 0 auto; }
.p-ukpn-dl dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
.p-ukpn-tx { max-height: min(32vh, 180px); overflow: auto; overflow-wrap: anywhere; }
.p-ukpn-txrow { border-top: 1px solid #2f343d; padding: 4px 0; }
.p-ukpn-hudbtn { color: #35e6bb; }
@media (prefers-reduced-motion: reduce) { .p-ukpn-btn, .p-ukpn-item { transition: none; } }Pilot UKPN
A JavaScript file in the theme folder of Cosmic that maps transformers and substations, using SHA-256, and uses data from UK Power Networks open data and the data-grid-GB repository.
energy-datacosmic / tools/explore/theme/pilot-ukpn.js · lines 1–543 of 543 · Entry point · pattern refreshNear (shared by 2 files)
- What it does
- It maps transformers and substations. Defines 44 functions or classes, including kernel, hex, scalar, normalize, unpack. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'ukpn'): 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: transformers, substations.
- Inputs & outputs
- In: data source: UK Power Networks open data; data source: data-grid-gb data; DuckDB queries.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- It loads main (`loadMain`), shows card (`showCard`) and refreshes near (`refreshNear`). Pilot module W04 (TAPCHANGER-58): UK Power Networks secondary substations + instant jump list. It responds to click, input and submit events.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · script
- Uses
- none found
- Used by
- loaded by Pilot (script src)
- Produces
- kernel, hex, scalar, normalize, unpack, verify, acquire, index, pack, workerSource, adopt, byId
- Defines here
- kernel, hex, scalar, normalize, unpack, verify, acquire, index, pack, workerSource, adopt, byId, loadMain, load, details, hav, brg, near, cells, search, fmtN, fmtD, compass, site, creditHTML, cardHTML, row, detailsHTML, nv, showCard
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-ukpn.js:1-543 · blob df2768f8610a44a542e8f6040ad27b8207678b16 · 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: supporting_data
/* Pilot module W04 (TAPCHANGER-58): UK Power Networks secondary substations + instant jump list.
*
* Real data only. Source is the pinned, sha-checked UKPN archive that GridAtlas keeps as its independent oracle
* (data-grid-gb@2502549f ukpn-secondary-site-transformers.zip, as gridatlas tools/secondary/import_ukpn.py). GridAtlas's
* live load() now reads pinned Parquet derivatives through its shared DuckDB-WASM runtime; Pilot keeps the ZIP because
* that runtime is several MB. normalize() and unpack() are ported from Ventusltd/gridatlas@f944f8dcbc09cd09c0895f0126682ec241cd576f
* atlas/modules/202612010912-ukpn-secondary-substations.js (Apache-2.0; Modular Star families 179801 / 179802).
* This file: Apache-2.0.
* UK Power Networks Secondary Site Transformers, 27 November 2025, CC BY 4.0
* https://ukpowernetworks.opendatasoft.com/explore/assets/ukpn-secondary-site-transformers/
* 74,719 transformer rows -> 56,309 sites -> 54,558 sites with a published point (1,751 have none
* and cannot be flown to). The GridAtlas closure counts are asserted exactly; nothing is inferred.
* Photon rule: nothing is bundled. The 2 MB ZIP streams on first use only and is unpacked off the
* main thread. Installed ratings are not available capacity.
* Contract: /tmp/vk/pilot200/CONTRACT.md v1 (window.PILOT only).
*/
(function () {
'use strict';
var W = typeof window !== 'undefined' ? window : null;
if (!W || !W.PILOT) return;
var P = W.PILOT, D = W.document;
var ARCHIVE = 'https://raw.githubusercontent.com/Ventusltd/data-grid-gb/2502549fed826106c70865047a540a170dd68919/ukpn-secondary/ukpn-secondary-site-transformers.zip';
var BYTES = 2068796, SHA = 'c75933d86f4872a5f54712c0a945c283bb9038323a2ae9567df51ba3ce1b75c5';
var SOURCE_URL = 'https://ukpowernetworks.opendatasoft.com/explore/assets/ukpn-secondary-site-transformers/';
var CREDIT = 'UK Power Networks · 27 Nov 2025 · CC BY 4.0'; // exactly as GridAtlas's UKPN card gives it
var COLOR = '#35e6bb'; // GridAtlas layer colour
var DNO = ['EPN', 'LPN', 'SPN'];
var DNO_NAME = { EPN: 'Eastern Power Networks', LPN: 'London Power Networks', SPN: 'South Eastern Power Networks' };
// Bounding box of the 54,558 published points (computed from the archive), padded ~5 km; used only to decide when to load.
var COVER = { s: 50.70, w: -1.15, n: 53.01, e: 1.83 };
var CELL = 0.02; // spatial index cell, degrees
if (P.module) P.module('ukpn', { version: '1', owner: 'W04' });
/* ---------- kernel: pure, runs in the Worker, on the main thread (fallback) and in node tests ---------- */
function kernel(G) {
function hex(buf) { var a = new Uint8Array(buf), s = ''; for (var i = 0; i < a.length; i++) s += (a[i] < 16 ? '0' : '') + a[i].toString(16); return s; }
function scalar(v) { return (typeof v === 'number' && isFinite(v)) || (typeof v === 'string' && v.trim()) ? v : null; }
// Port of GridAtlas normalize(): identity checks, conflicting points, exact closure counts.
function normalize(raw) {
if (!raw || raw.type !== 'FeatureCollection' || !raw.features || raw.features.length !== 74719) throw Error('UKPN source row count mismatch');
var sites = new Map(), transformers = new Set(), points = 0;
for (var k = 0; k < raw.features.length; k++) {
var f = raw.features[k], p = f.properties || {}, site = p.secondarysitefunctionallocation;
if (typeof site !== 'string' || !site || typeof p.transformerfunctionallocation !== 'string' || ['EPN', 'SPN', 'LPN'].indexOf(p.dno) < 0) throw Error('UKPN identity invalid');
transformers.add(p.transformerfunctionallocation);
var s = sites.get(site);
if (!s) { s = { site: site, dno: p.dno, coords: null, ids: new Set(), volts: new Set(), details: new Map() }; sites.set(site, s); }
if (s.dno !== p.dno) throw Error('UKPN conflicting network');
s.ids.add(p.transformerfunctionallocation);
var det = [p.transformerfunctionallocation, scalar(p.primarywinding), scalar(p.secondarywinding), scalar(p.onanrating), scalar(p.opvolts)];
s.details.set(JSON.stringify(det), det);
if (typeof p.primarywinding === 'number' && p.primarywinding > 0) s.volts.add(p.primarywinding);
if (f.geometry === null) continue;
var c = f.geometry && f.geometry.coordinates;
if (!f.geometry || f.geometry.type !== 'Point' || !Array.isArray(c) || c.length !== 2 || !isFinite(c[0]) || !isFinite(c[1]) ||
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;
}
var all = Array.from(sites.values());
var placed = all.filter(function (x) { return x.coords; }).sort(function (a, b) { return a.site < b.site ? -1 : a.site > b.site ? 1 : 0; });
if (sites.size !== 56309 || placed.length !== 54558 || points !== 56685 || transformers.size !== 74712) throw Error('UKPN source closure mismatch');
var n = placed.length, lat = new Float64Array(n), lon = new Float64Array(n), dno = new Uint8Array(n), tc = new Uint16Array(n), kvi = new Uint16Array(n);
var ids = new Array(n), kvTab = [], kvMap = new Map(), details = new Map();
for (var i = 0; i < n; i++) {
var q = placed[i];
ids[i] = q.site; lon[i] = q.coords[0]; lat[i] = q.coords[1]; dno[i] = ['EPN', 'LPN', 'SPN'].indexOf(q.dno); tc[i] = q.ids.size;
var kv = Array.from(q.volts).sort(function (a, b) { return a - b; }).map(function (v) { return v + ' kV primary'; }).join(', ');
if (!kvMap.has(kv)) { kvMap.set(kv, kvTab.length); kvTab.push(kv); }
kvi[i] = kvMap.get(kv);
}
all.forEach(function (x) { details.set(x.site, Array.from(x.details.values())); });
return { n: n, ids: ids, lat: lat, lon: lon, dno: dno, tc: tc, kvi: kvi, kvTab: kvTab, details: details,
sites: sites.size, unplaced: sites.size - n, transformers: transformers.size };
}
// Port of GridAtlas unpack(): structure checks, then raw-deflate inflate of the single member.
function unpack(bytes) {
var 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) return Promise.reject(Error('UKPN archive structure mismatch'));
if (typeof G.DecompressionStream !== 'function') return Promise.reject(Error('This browser cannot unpack the UKPN archive (no DecompressionStream)'));
var start = 30 + v.getUint16(26, true) + v.getUint16(28, true);
var stream = new G.Blob([bytes.slice(start, start + 2068618)]).stream().pipeThrough(new G.DecompressionStream('deflate-raw'));
return new G.Response(stream).arrayBuffer().then(function (raw) {
if (raw.byteLength !== 33070781) throw Error('UKPN unpacked size mismatch');
return normalize(JSON.parse(new G.TextDecoder().decode(raw)));
});
}
function verify(bytes, sha) {
if (bytes.byteLength !== 2068796) return Promise.reject(Error('UKPN archive integrity mismatch (size)'));
return G.crypto.subtle.digest('SHA-256', bytes).then(function (d) {
if (hex(d) !== sha) throw Error('UKPN archive integrity mismatch (sha256)');
return bytes;
});
}
function acquire(url, sha) {
return G.fetch(url, { cache: 'force-cache', credentials: 'omit', redirect: 'error' }).then(function (r) {
if (!r.ok) throw Error('UKPN archive HTTP ' + r.status + ' (raw.githubusercontent.com)');
return r.arrayBuffer();
}).then(function (b) { return verify(b, sha); }).then(unpack);
}
// CSR grid index over the placed sites (cell degrees), built here so the main thread only adopts arrays.
function index(lat, lon, n, cell) {
var s = Infinity, w = Infinity, no = -Infinity, e = -Infinity, i;
for (i = 0; i < n; i++) { if (lat[i] < s) s = lat[i]; if (lat[i] > no) no = lat[i]; if (lon[i] < w) w = lon[i]; if (lon[i] > e) e = lon[i]; }
// Near-square cells in metres: cy degrees of latitude, cx = cy / cos(mid latitude) degrees of longitude.
var rad = Math.PI / 180, cy = cell, cx = cell / Math.cos((s + no) / 2 * rad);
var cols = Math.floor((e - w) / cx) + 1, rows = Math.floor((no - s) / cy) + 1, cnt = new Int32Array(cols * rows + 1), cellOf = new Int32Array(n);
for (i = 0; i < n; i++) { var c = Math.floor((lat[i] - s) / cy) * cols + Math.floor((lon[i] - w) / cx); cellOf[i] = c; cnt[c + 1]++; }
for (i = 0; i < cols * rows; i++) cnt[i + 1] += cnt[i];
var fill = cnt.slice(0, cols * rows), order = new Int32Array(n);
for (i = 0; i < n; i++) order[fill[cellOf[i]]++] = i;
return { s: s, w: w, n: no, e: e, cy: cy, cx: cx, cols: cols, rows: rows, start: cnt, order: order,
dmin: Math.min(cy * 111320, cx * 111320 * Math.cos(Math.min(89, Math.max(Math.abs(s), Math.abs(no))) * rad)) };
}
// Transferable bundle for the main thread: ids and search keys as joined strings, typed arrays moved not copied.
function pack(r, cell) {
var ix = index(r.lat, r.lon, r.n, cell);
var o = { n: r.n, ids: r.ids.join('\n'), upper: r.ids.map(function (x) { return x.toUpperCase().replace(/[\s-]/g, ''); }).join('\n'),
lat: r.lat, lon: r.lon, dno: r.dno, tc: r.tc, kvi: r.kvi, kvTab: r.kvTab, ix: ix, sites: r.sites, unplaced: r.unplaced, transformers: r.transformers };
return { o: o, transfer: [o.lat.buffer, o.lon.buffer, o.dno.buffer, o.tc.buffer, o.kvi.buffer, ix.start.buffer, ix.order.buffer] };
}
return { normalize: normalize, unpack: unpack, verify: verify, acquire: acquire, hex: hex, index: index, pack: pack };
}
/* ---------- worker host ---------- */
var DATA = null, loading = null, worker = null, mainDetails = null, reqSeq = 0, reqs = {};
function workerSource() {
return 'var K=(' + kernel.toString() + ')(self),DET=null;' +
'self.onmessage=function(e){var m=e.data;' +
'if(m.op==="load"){K.acquire(m.url,m.sha).then(function(r){DET=r.details;var p=K.pack(r,m.cell);' +
'self.postMessage({op:"loaded",data:p.o},p.transfer);' +
'},function(err){self.postMessage({op:"error",msg:String(err&&err.message||err)});});}' +
'else if(m.op==="details"){self.postMessage({op:"details",seq:m.seq,rows:DET&&DET.get(m.id)||null});}};';
}
function adopt(o) {
DATA = { n: o.n, ids: o.ids.split('\n'), upper: o.upper.split('\n'), lat: o.lat, lon: o.lon, dno: o.dno, tc: o.tc, kvi: o.kvi, kvTab: o.kvTab,
ix: o.ix, sites: o.sites, unplaced: o.unplaced, transformers: o.transformers, byIdMap: null };
return DATA;
}
function byId(id) {
if (!DATA) return -1;
if (!DATA.byIdMap) { DATA.byIdMap = new Map(); for (var i = 0; i < DATA.n; i++) DATA.byIdMap.set(DATA.ids[i], i); }
var i2 = DATA.byIdMap.get(String(id).trim().toUpperCase());
return i2 == null ? -1 : i2;
}
function loadMain() {
var K = kernel(W);
return K.acquire(ARCHIVE, SHA).then(function (r) { mainDetails = r.details; return adopt(K.pack(r, CELL).o); });
}
function load() {
if (DATA) return Promise.resolve(DATA);
if (loading) return loading;
if (P.offline) return Promise.reject(Error('Offline mode: UKPN secondary substations are not loaded'));
status('Loading UKPN secondary substations (2 MB, once)…');
loading = new Promise(function (resolve, reject) {
var url = null;
try {
url = URL.createObjectURL(new Blob([workerSource()], { type: 'text/javascript' }));
worker = new Worker(url);
} catch (e) { worker = null; }
if (url) setTimeout(function () { URL.revokeObjectURL(url); }, 5000);
if (!worker) { loadMain().then(resolve, reject); return; }
worker.onmessage = function (e) {
var m = e.data;
if (m.op === 'loaded') resolve(adopt(m.data));
else if (m.op === 'error') reject(Error(m.msg));
else if (m.op === 'details' && reqs[m.seq]) { reqs[m.seq](m.rows); delete reqs[m.seq]; }
};
worker.onerror = function () { worker = null; loadMain().then(resolve, reject); };
worker.postMessage({ op: 'load', url: ARCHIVE, sha: SHA, cell: CELL });
}).then(function (d) {
status(fmtN(d.n) + ' UKPN secondary substations loaded (' + fmtN(d.unplaced) + ' have no published location)');
P.emit && P.emit('ukpn:loaded', { count: d.n, sites: d.sites, unplaced: d.unplaced });
refreshNear(true); renderList();
return d;
}, function (err) {
loading = null;
status('UKPN secondaries unavailable: ' + (err && err.message || err));
throw err;
});
return loading;
}
function details(id) {
if (mainDetails) return Promise.resolve(mainDetails.get(id) || null);
if (!worker) return Promise.resolve(null);
return new Promise(function (res) { var s = ++reqSeq; reqs[s] = res; worker.postMessage({ op: 'details', id: id, seq: s }); });
}
/* ---------- spatial queries over the CSR grid built in kernel.index ---------- */
// one geodesy for every module: PILOT.dist / PILOT.bearing (pilot-estate.js, R 6378.137 km)
function hav(a1, o1, a2, o2) { return P.dist(a1, o1, a2, o2); }
function brg(a1, o1, a2, o2) {
return P.bearing(a1, o1, a2, o2);
}
// n nearest placed sites to (lat, lon) within maxM metres, optional filter(i). Returns [{i, m}] sorted.
function near(lat, lon, n, maxM, filter) {
var d = DATA; if (!d || !n) return [];
var ix = d.ix, cr = Math.floor((lat - ix.s) / ix.cy), cc = Math.floor((lon - ix.w) / ix.cx), out = [], within = 0;
var maxR = Math.ceil((maxM || 2e6) / ix.dmin) + 1;
// Rings that cannot touch the grid are empty: start at the first ring that can, stop after the last.
var r0 = Math.max(0, -cr, cr - (ix.rows - 1), -cc, cc - (ix.cols - 1));
var lim = Math.max(cr, ix.rows - 1 - cr, cc, ix.cols - 1 - cc);
for (var r = r0; r <= Math.min(maxR, lim); r++) {
for (var y = Math.max(0, cr - r); y <= Math.min(ix.rows - 1, cr + r); y++) {
var edge = y === cr - r || y === cr + r;
for (var x = cc - r; x <= cc + r; x += edge ? 1 : 2 * r || 1) {
if (x < 0 || x >= ix.cols) continue;
var c = y * ix.cols + x;
for (var k = ix.start[c]; k < ix.start[c + 1]; k++) {
var i = ix.order[k]; if (filter && !filter(i)) continue;
var m = hav(lat, lon, d.lat[i], d.lon[i]); if (maxM && m > maxM) continue;
out.push({ i: i, m: m });
}
}
}
// Everything outside ring r is at least r * dmin away: stop once n candidates are inside that radius.
if (out.length >= n) { var bound = r * ix.dmin; within = 0; for (var q = 0; q < out.length; q++) if (out[q].m <= bound) within++; if (within >= n) break; }
}
out.sort(function (a, b) { return a.m - b.m; });
return out.slice(0, n);
}
// Count of sites per cell block inside a bbox; stride s merges s x s cells. Returns [{lat, lon, c}].
function cells(b, maxCells) {
var d = DATA; if (!d) return [];
var ix = d.ix, r0 = Math.max(0, Math.floor((b.s - ix.s) / ix.cy)), r1 = Math.min(ix.rows - 1, Math.floor((b.n - ix.s) / ix.cy)),
c0 = Math.max(0, Math.floor((b.w - ix.w) / ix.cx)), c1 = Math.min(ix.cols - 1, Math.floor((b.e - ix.w) / ix.cx));
if (r1 < r0 || c1 < c0) return [];
var st = Math.max(1, Math.ceil(Math.sqrt((r1 - r0 + 1) * (c1 - c0 + 1) / (maxCells || 400)))), out = [];
for (var y = r0; y <= r1; y += st) for (var x = c0; x <= c1; x += st) {
var c = 0, la = 0, lo = 0;
for (var yy = y; yy < Math.min(y + st, r1 + 1); yy++) for (var xx = x; xx < Math.min(x + st, c1 + 1); xx++) {
var q = yy * ix.cols + xx;
for (var k = ix.start[q]; k < ix.start[q + 1]; k++) { var i = ix.order[k]; la += d.lat[i]; lo += d.lon[i]; c++; }
}
if (c) out.push({ lat: la / c, lon: lo / c, c: c, st: st });
}
return out;
}
function search(q, dnoFilter, limit) {
var d = DATA; if (!d) return [];
var s = String(q || '').toUpperCase().replace(/[\s-]/g, ''); limit = limit || 40;
if (!s) return [];
var pre = [], sub = [];
for (var i = 0; i < d.n; i++) {
if (dnoFilter != null && d.dno[i] !== dnoFilter) continue;
var at = d.upper[i].indexOf(s);
if (at < 0) continue;
// Prefix of the whole id, or of the part after the network code, ranks first.
if (at === 0 || at === 3) { pre.push(i); if (pre.length >= limit) break; } else if (sub.length < limit) sub.push(i);
}
return pre.concat(sub).slice(0, limit);
}
/* ---------- formatting / card ---------- */
var esc = P.esc || function (s) { return String(s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); };
function fmtN(n) { return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
function fmtD(m) { return m < 1000 ? Math.round(m) + ' m' : (m < 10000 ? (m / 1000).toFixed(1) : Math.round(m / 1000)) + ' km'; }
function compass(b) { return ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.round(b / 45) % 8]; }
function site(i) {
var d = DATA; if (!d || i == null || i < 0 || i >= d.n) return null;
var net = DNO[d.dno[i]];
return { i: i, id: d.ids[i], lat: d.lat[i], lon: d.lon[i], dno: net, network: DNO_NAME[net], transformers: d.tc[i], voltage: d.kvTab[d.kvi[i]] };
}
function creditHTML() { return '<a class="p-ukpn-credit" href="' + SOURCE_URL + '" target="_blank" rel="noopener noreferrer">' + esc(CREDIT) + '</a>'; }
function cardHTML(i) {
var s = site(i); if (!s) return '';
var row = function (k, v) { return '<div><dt>' + esc(k) + '</dt><dd>' + esc(v == null || v === '' ? 'Not supplied' : v) + '</dd></div>'; };
return '<dl class="p-ukpn-dl">' +
row('Network', 'UK Power Networks (' + s.dno + ') · ' + s.network) +
row('Transformer count', s.transformers) +
row('Voltage', s.voltage) +
row('Location', s.lat.toFixed(6) + ', ' + s.lon.toFixed(6) + ' (latitude, longitude)') +
'</dl>' +
'<button type="button" class="p-ukpn-btn p-ukpn-txbtn" data-p-ukpn-site="' + esc(s.id) + '">Transformer records</button>' +
'<div class="p-ukpn-tx" data-p-ukpn-for="' + esc(s.id) + '" aria-live="polite"></div>' +
'<p class="p-ukpn-dim">Installed ratings are not available capacity.</p>' + creditHTML();
}
function detailsHTML(rows) {
if (!rows || !rows.length) return '<p class="p-ukpn-dim">Transformer details unavailable.</p>';
var groups = new Map(), h = '';
rows.forEach(function (r) { if (!groups.has(r[0])) groups.set(r[0], []); groups.get(r[0]).push(r); });
var nv = function (v) { return esc(v == null ? 'Not supplied' : v); };
groups.forEach(function (rs, id) {
h += '<div class="p-ukpn-txrow"><b>' + esc(id) + '</b>';
if (rs.length > 1) h += '<div>Source records: conflicting published values retained</div>';
rs.forEach(function (r) {
h += '<div>Primary winding (source value): ' + nv(r[1]) + '</div><div>Secondary winding (source value): ' + nv(r[2]) +
'</div><div>ONAN rating (source value): ' + nv(r[3]) + '</div><div>Operating voltage (source value): ' + nv(r[4]) + '</div>';
});
h += '</div>';
});
return h;
}
function showCard(i) {
var s = site(i); if (!s || !P.card) return;
P.card({ title: s.id, html: cardHTML(i), lat: s.lat, lon: s.lon, cap: 'UKPN SECONDARY SUBSTATION' });
}
if (D && D.addEventListener) D.addEventListener('click', function (e) {
var b = e.target && e.target.closest && e.target.closest('.p-ukpn-txbtn'); if (!b) return;
var id = b.getAttribute('data-p-ukpn-site'), box = null;
Array.prototype.forEach.call(D.querySelectorAll('.p-ukpn-tx'), function (el) { if (el.getAttribute('data-p-ukpn-for') === id) box = el; });
if (!box) return;
box.textContent = 'Loading transformer records…';
details(id).then(function (rows) { if (box.isConnected) box.innerHTML = detailsHTML(rows); });
});
/* ---------- flight ---------- */
var selected = -1;
function jump(i) {
var s = site(i); if (!s) return Promise.resolve(null);
selected = i;
if (P.emit) P.emit('ukpn:select', { id: s.id, lat: s.lat, lon: s.lon });
if (P.hash) P.hash('ukpn', s.id);
if (!P.flyTo) { showCard(i); return Promise.resolve(s); }
var pr = P.flyTo(s.lat, s.lon, { alt: 140, dist: 260, label: s.id, source: 'ukpn', id: s.id });
return Promise.resolve(pr).then(function () { if (selected === i) showCard(i); return s; }, function () { return null; });
}
function camLL() { var c = P.camLL ? P.camLL() : null; return c && isFinite(c.lat) ? c : null; }
function nextNearest() {
return load().then(function () {
var c = camLL(); if (!c) return null;
var cur = selected >= 0 ? DATA.ids[selected] : null;
var list = near(c.lat, c.lon, 2, 0, function (i) { return DATA.ids[i] !== cur; });
return list.length ? jump(list[0].i) : null;
}, function (e) { note(e.message); });
}
function randomSite() { return load().then(function () { return jump(Math.floor(Math.random() * DATA.n)); }, function (e) { note(e.message); }); }
/* ---------- drawing layer ---------- */
var drawn = [], cache = { at: 0, lat: 0, lon: 0, r: 0, list: [] };
function refreshNear(force, v) {
var c = v ? v.cam : camLL(); if (!c || !DATA) return;
var r = v ? Math.max(500, Math.min(v.radius || 4000, 25000)) : 4000, now = Date.now();
if (!force && now - cache.at < 250 && hav(c.lat, c.lon, cache.lat, cache.lon) < 0.05 * r && Math.abs(r - cache.r) < 0.2 * r) return;
cache = { at: now, lat: c.lat, lon: c.lon, r: r, list: near(c.lat, c.lon, 1500, r) };
}
function overlaps(b, boxes) { for (var k = 0; k < boxes.length; k++) { var o = boxes[k]; if (b[0] < o[2] && b[2] > o[0] && b[1] < o[3] && b[3] > o[1]) return true; } return false; }
var layer = {
id: 'ukpn', title: 'UKPN secondary substations', order: 50, visible: true,
credit: 'UKPN secondary substations: ' + CREDIT,
draw: function (g, v) {
drawn = [];
if (!DATA || !v || !v.cam) return;
var agl = v.cam.agl != null ? v.cam.agl : v.cam.alt;
g.save();
if ((v.lod || 0) >= 2 || agl > 6000) {
if ((v.lod || 0) >= 3 && (v.radius || 0) > 60000) { g.restore(); return; }
var b = v.bbox || { s: v.cam.lat - 0.5, n: v.cam.lat + 0.5, w: v.cam.lon - 0.8, e: v.cam.lon + 0.8 };
var cs = cells(b, 400), maxc = 1;
cs.forEach(function (c) { if (c.c > maxc) maxc = c.c; });
g.fillStyle = COLOR;
cs.forEach(function (c) {
var p = v.project(c.lat, c.lon, null); if (!p || p.x < -20 || p.y < -20 || p.x > v.w + 20 || p.y > v.h + 20) return;
var sz = Math.max(3, Math.min(18, 0.5 * DATA.ix.dmin * c.st * (v.f || v.h) / p.d)); // ~half the cell's projected size
g.globalAlpha = 0.35 + 0.6 * Math.sqrt(c.c / maxc);
g.fillRect(p.x - sz / 2, p.y - sz / 2, sz, sz);
});
g.restore(); return;
}
refreshNear(false, v);
var list = cache.list, boxes = [], labels = 0;
g.lineWidth = 1.5;
for (var k = 0; k < list.length; k++) {
var i = list[k].i, p = v.project(DATA.lat[i], DATA.lon[i], null);
if (!p || p.x < -10 || p.y < -10 || p.x > v.w + 10 || p.y > v.h + 10) continue;
var r = Math.max(1.6, Math.min(8, 1400 / p.d));
g.globalAlpha = p.d < 8000 ? 1 : 0.6;
g.fillStyle = i === selected ? '#ffffff' : COLOR;
g.beginPath(); g.arc(p.x, p.y, r, 0, 6.2832); g.fill();
if (r > 4) { g.strokeStyle = '#04271f'; g.stroke(); }
drawn.push([p.x, p.y, i]);
}
// FLOC labels on the 6 nearest within 700 m, de-overlapped.
g.globalAlpha = 1; g.font = '600 11px ui-monospace, Menlo, monospace'; g.textBaseline = 'bottom';
for (k = 0; k < list.length && labels < 6 && list[k].m <= 700; k++) {
var j = list[k].i, q = v.project(DATA.lat[j], DATA.lon[j], null); if (!q || q.x < 0 || q.y < 16 || q.x > v.w || q.y > v.h) continue;
var t = DATA.ids[j], tw = g.measureText(t).width, bx = [q.x - tw / 2 - 3, q.y - 22, q.x + tw / 2 + 3, q.y - 7];
if (overlaps(bx, boxes)) continue;
boxes.push(bx); labels++;
g.fillStyle = 'rgba(0,20,16,.72)'; g.fillRect(bx[0], bx[1], bx[2] - bx[0], bx[3] - bx[1]);
g.fillStyle = COLOR; g.textAlign = 'center'; g.fillText(t, q.x, q.y - 8);
}
g.restore();
},
pick: function (sx, sy) {
var best = null, bd = 22;
for (var k = 0; k < drawn.length; k++) { var d = Math.hypot(drawn[k][0] - sx, drawn[k][1] - sy); if (d <= bd) { bd = d; best = drawn[k][2]; } }
if (best == null) return null;
var s = site(best); selected = best;
if (P.emit) P.emit('ukpn:select', { id: s.id, lat: s.lat, lon: s.lon });
return { title: s.id, html: cardHTML(best), lat: s.lat, lon: s.lon, id: s.id, cap: 'UKPN SECONDARY SUBSTATION' };
},
onOrigin: function () { cache.at = 0; }
};
/* ---------- panel: instant jump list ---------- */
var ui = null, dnoSel = null;
function el(tag, cls, text) { var e = D.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
function status(t) {
if (ui) ui.status.textContent = t;
if (P.hud && /unavailable|Offline|cannot/.test(t)) P.hud('status:ukpn', esc(t));
}
function note(t) { if (P.note) P.note(t, 4000); status(t); }
function buildPanel() {
if (ui || !P.panel || !D) return ui;
var body = P.panel('ukpn', '', { title: 'UKPN secondaries', icon: 'SS', open: false });
if (!body) return null;
var root = el('div', 'p-ukpn-panel');
var st = el('p', 'p-ukpn-status', DATA ? fmtN(DATA.n) + ' sites' : 'Not loaded yet. 2 MB from UK Power Networks open data on first use.');
st.setAttribute('role', 'status');
var form = el('form', 'p-ukpn-form'); form.setAttribute('role', 'search');
var lab = el('label', 'p-ukpn-sr', 'Search UKPN secondary site ID'); lab.htmlFor = 'p-ukpn-q';
var inp = el('input', 'p-ukpn-q'); inp.id = 'p-ukpn-q'; inp.type = 'search'; inp.autocomplete = 'off'; inp.spellcheck = false;
inp.placeholder = 'Site ID, e.g. LPN-S0000000'; inp.setAttribute('enterkeyhint', 'search');
form.appendChild(lab); form.appendChild(inp);
var chips = el('div', 'p-ukpn-chips'); chips.setAttribute('role', 'group'); chips.setAttribute('aria-label', 'Network filter');
[['All', null], ['EPN', 0], ['LPN', 1], ['SPN', 2]].forEach(function (c) {
var b = el('button', 'p-ukpn-btn p-ukpn-chip', c[0]); b.type = 'button'; b.setAttribute('aria-pressed', c[1] === dnoSel ? 'true' : 'false');
if (c[1] != null) b.title = DNO_NAME[DNO[c[1]]];
b.addEventListener('click', function () {
dnoSel = c[1];
Array.prototype.forEach.call(chips.children, function (x) { x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); });
load().then(renderList, function () {});
});
chips.appendChild(b);
});
var acts = el('div', 'p-ukpn-acts');
var bNext = el('button', 'p-ukpn-btn', 'Next nearest'); bNext.type = 'button'; bNext.addEventListener('click', nextNearest);
var bRand = el('button', 'p-ukpn-btn', 'Random site'); bRand.type = 'button'; bRand.addEventListener('click', randomSite);
var bShow = el('button', 'p-ukpn-btn', 'On map'); bShow.type = 'button'; bShow.setAttribute('aria-pressed', 'true');
bShow.addEventListener('click', function () {
var on = bShow.getAttribute('aria-pressed') !== 'true';
bShow.setAttribute('aria-pressed', on ? 'true' : 'false');
if (P.setLayerVisible) P.setLayerVisible('ukpn', on); else layer.visible = on;
if (on) load().catch(function () {});
});
acts.appendChild(bNext); acts.appendChild(bRand); acts.appendChild(bShow);
var head = el('p', 'p-ukpn-head', 'Nearest to you');
var count = el('p', 'p-ukpn-sr'); count.setAttribute('aria-live', 'polite');
var list = el('ol', 'p-ukpn-list');
var foot = el('p', 'p-ukpn-dim');
foot.innerHTML = 'Secondary site transformer register; 1,751 sites have no published location and cannot be flown to. Installed ratings are not available capacity. ' + creditHTML();
[st, form, chips, acts, head, count, list, foot].forEach(function (x) { root.appendChild(x); });
body.appendChild(root);
var t = null;
inp.addEventListener('input', function () { clearTimeout(t); t = setTimeout(function () { load().then(renderList, function () {}); }, 60); });
form.addEventListener('submit', function (e) { e.preventDefault(); load().then(function () { var r = search(inp.value, dnoSel, 1); if (r.length) jump(r[0]); else renderList(); }, function () {}); });
inp.addEventListener('keydown', function (e) { e.stopPropagation(); });
ui = { body: body, status: st, input: inp, list: list, head: head, count: count };
return ui;
}
function renderList() {
if (!ui || !DATA) return;
var q = ui.input.value.trim(), c = camLL(), items;
if (q) {
items = search(q, dnoSel, 40).map(function (i) { return { i: i, m: c ? hav(c.lat, c.lon, DATA.lat[i], DATA.lon[i]) : null }; });
ui.head.textContent = items.length ? 'Matching site IDs' : 'No site ID matches "' + q + '"';
} else {
items = c ? near(c.lat, c.lon, 20, 0, dnoSel == null ? null : function (i) { return DATA.dno[i] === dnoSel; }) : [];
ui.head.textContent = c ? 'Nearest to you' : 'Search by site ID';
}
ui.count.textContent = items.length + ' results';
ui.list.textContent = '';
items.forEach(function (it) {
var s = site(it.i), li = el('li'), b = el('button', 'p-ukpn-item'); b.type = 'button';
b.appendChild(el('span', 'p-ukpn-id', s.id));
var sub = s.dno + ' · ' + s.transformers + ' transformer' + (s.transformers === 1 ? '' : 's');
if (it.m != null && c) sub += ' · ' + fmtD(it.m) + ' ' + compass(brg(c.lat, c.lon, s.lat, s.lon));
b.appendChild(el('span', 'p-ukpn-sub', sub));
b.setAttribute('aria-label', 'Fly to ' + s.id + ', ' + sub);
b.addEventListener('click', function () { jump(it.i); if (P.closePanel && W.innerWidth < 900) P.closePanel(); });
li.appendChild(b); ui.list.appendChild(li);
});
}
function openPanel() { buildPanel(); if (P.openPanel) P.openPanel('ukpn'); load().then(renderList, function () {}); }
/* ---------- HUD, keys, triggers, events ---------- */
var hudAt = 0, triggerAt = 0;
function tick() {
var now = Date.now();
if (!DATA) {
if (now - triggerAt < 1000 || loading || P.offline) return;
triggerAt = now;
var c0 = camLL();
if (c0 && layer.visible !== false && (c0.agl == null || c0.agl < 5000) && c0.lat > COVER.s && c0.lat < COVER.n && c0.lon > COVER.w && c0.lon < COVER.e) load().catch(function () {});
return;
}
if (now - hudAt < 500) return; hudAt = now;
var c = camLL(); if (!c || !P.hud) return;
var nn = near(c.lat, c.lon, 1, 50000);
P.hud('status:ukpn', nn.length ? 'Nearest UKPN secondary <b>' + esc(DATA.ids[nn[0].i]) + '</b> ' + fmtD(nn[0].m) : '');
}
if (D && D.addEventListener) D.addEventListener('keydown', function (e) {
var t = e.target, tag = t && t.tagName;
if (e.ctrlKey || e.metaKey || e.altKey || tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable)) return;
var k = (e.key || '').toLowerCase();
if (k === 'u') { openPanel(); e.preventDefault(); } else if (k === 'j') { nextNearest(); e.preventDefault(); }
});
if (P.on) {
// Other modules (vicinity, nav) ask for nearest secondaries without touching our internals.
P.on('ukpn:query', function (q) {
if (!q || typeof q.reply !== 'function') return;
// query contract v2: radius in metres as q.radiusM (q.maxM accepted); failures reply with meta.state 'error'
if (P.offline) { q.reply([], { loaded: false, state: 'error', error: 'offline' }); return; }
var n = Math.min(200, q.n || 10), rM = +q.radiusM || +q.maxM || 0;
load().then(function () {
var got = near(+q.lat, +q.lon, n, rM);
q.reply(got.map(function (r) { var s = site(r.i); s.m = r.m; delete s.i; return s; }), { loaded: true, state: 'ok', capped: got.length >= n, radiusM: rM });
}, function (err) { q.reply([], { loaded: false, state: 'error', error: String(err && err.message || err) }); });
});
P.on('arrive', function () { refreshNear(true); if (ui && ui.input && !ui.input.value) renderList(); });
P.on('panel', function (p) { if (p && p.name === 'ukpn' && p.open) load().then(renderList, function () {}); });
P.on('origin', function () { cache.at = 0; });
}
function start() {
if (P.addLayer) P.addLayer(layer);
buildPanel();
if (P.hud) {
var hb = P.hud('right:ukpn', '<button type="button" class="pbtn p-ukpn-hudbtn" aria-label="UKPN secondary substations jump list (U)">SS</button>');
var btn = hb && hb.querySelector && hb.querySelector('button');
if (btn) btn.addEventListener('click', openPanel);
}
if (P.onFrame) P.onFrame(tick);
var want = P.hash ? P.hash('ukpn') : null;
if (want) {
if (P.offline) { note('Offline mode: UKPN secondary substations are not loaded'); return; }
load().then(function () {
var i = byId(want);
if (i < 0) note('No UKPN secondary site with a published location has the ID ' + want); else jump(i);
}, function (e) { note(e.message); });
}
}
if (P.ready) P.ready(start); else start();
P.ukpn = { version: '1', load: load, loaded: function () { return !!DATA; }, count: function () { return DATA ? DATA.n : 0; },
near: near, cells: cells, search: search, site: site, find: byId,
jump: jump, details: details, cardHTML: cardHTML, detailsHTML: detailsHTML, open: openPanel, layer: layer,
kernel: kernel, _adopt: adopt, source: { archive: ARCHIVE, sha256: SHA, url: SOURCE_URL, credit: CREDIT } };
})();Distribution Network Operator (DNO) Ecr
A Python module in the fetchers folder of Data Grid GB. It is built from the raw requests helper (`raw_requests`) and the normalise step (`normalise`).
energy-datadata-grid-gb / datacentres/fetchers/dno_ecr.py · lines 1–20 of 20 · Not reached from any entry point (candidate for review) · pattern raw_requests (shared by 11 files)
- What it does
- It calculates its inputs. Defines raw_requests, normalise.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentres'): 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.
- What it achieves
- DNO embedded capacity registers (demand >= 1MW where published). Its code works with 1 MW.
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · datacentres/fetchers · Python module
- Uses
- none found
- Used by
- none found
- Produces
- raw_requests, normalise
- Defines here
- raw_requests, normalise
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 datacentres/fetchers/dno_ecr.py:1-20 · blob f82df74287d7bb5146d9c7bdf1c473b279ee2ec4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""DNO embedded capacity registers (demand >= 1 MW where published).
PLACEHOLDER. Lane TBC (DC-A1..A6) owns this source; its fetcher replaces this file when it
lands, keeping the contract in assetpipe/pipeline.py (FETCHER_CONTRACT). Until then the
pipeline skips it and never fails because of it.
Registry entry: datacentres/sources.json id "dno-ecr" (open: unverified, licence: unverified: varies by DNO).
"""
SOURCE_ID = "dno-ecr"
LANE = "TBC (DC-A1..A6)"
STATUS = "placeholder"
def raw_requests():
return []
def normalise(raw):
raise NotImplementedError("dno-ecr: fetcher not yet delivered by lane TBC (DC-A1..A6)")