In this section
- Substations interaction · energy-transition-simulator / prototype/mod/substations.js lines 1–198
- Cells ingest · faraday / apparatus/cells.mjs lines 1–125
- Cells Test test · faraday / apparatus/cells.test.mjs lines 1–121
- Grid Finder geodesy · faraday / apparatus/grid_finder.py lines 1–253
Substations
A JavaScript file in the prototype folder of Energy Transition Simulator that draws grid substations and substations footprints odbl, and uses data from the GridAtlas repository.
Set aside from the main view: 93% of its lines are the same as energy-transition-simulator/202609280014/mod/substations.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Substations; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9337 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/substations.js:1-189 576b2bdebdae893f821c4809e0f827bb63359e3e
- sha256 992fe82c09af7419178c4078679f310589990820e2704a61e226f56ebf4cecf1
- target sha256 7d8e22dba7d2c1f7166342bf4e46e2b6ebaa93a1fb308e38cadf52bb419548ca
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
interactionenergy-transition-simulator / prototype/mod/substations.js · lines 1–198 of 198 · Not reached from any entry point (candidate for review) · pattern labelBlock (shared by 2 files)
- What it does
- It draws grid substations and substations footprints odbl. Defines 25 functions or classes, including ecef, PFm, localFn, kvList, load. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: data source: gridatlas data; GeoJSON file grid_substations.geojson; JSON file substations-footprints.odbl.json. Coordinate systems named: WGS84 / EPSG:4326.
- What it achieves
- It labels block (`labelBlock`) and syncs btn (`syncBtn`). Substations as 3D wireframe compounds, in real coordinates (plain script; attaches to window.SIM). It responds to keydown and keyup events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- ecef, PFm, localFn, kvList, load, seg, box, fence, frameOf, place, EST_HALF, label
- Defines here
- ecef, PFm, localFn, kvList, load, seg, box, fence, frameOf, place, EST_HALF, label, kvText, compound, labelBlock, dist, nearby, refresh, go, command, syncBtn, ui, toggle, check, start
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/substations.js:1-198 · blob 69763c8d81eedeafdfba4e42a2f61993a9cdf231 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
// Substations as 3D wireframe compounds, in real coordinates (plain script; attaches to window.SIM).
// Points: GridAtlas grid_substations (atlas-v9). Fences: OpenStreetMap substation footprints (ODbL), pre-matched
// to the GridAtlas points by feature index in mod/substations-footprints.odbl.json. Where no footprint exists the
// fence is DASHED and sized by voltage: an estimate. Plinths are estimates (count from voltage and area).
// Labels show the voltage only, drawn as wire strokes standing over the compound. No names are ever read or shown.
// Command: type "go substation 132" (or "go sub 400", "go sub") to fly to the nearest one with that voltage.
(function () {
'use strict';
var GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson';
var ATLAS = '202608300453-atlas-v9';
var here = (document.currentScript && document.currentScript.src) || location.href;
var FP_URL = new URL('substations-footprints.odbl.json', here).href;
var CREDIT = 'Substations: mapped positions (GridAtlas points). Fences: OpenStreetMap footprints, © OpenStreetMap contributors (ODbL); a dashed fence and all plinths are estimates.';
var RADIUS = 2500, MAX = 60, MINZ = 12.5;
// ---- WGS84 local east/north metres around a reference (same ellipsoid as place-frame.mjs) ----
var A = 6378137, F = 1 / 298.257223563, E2 = F * (2 - F), D = Math.PI / 180;
function ecef(lat, lon) { var s = Math.sin(lat * D), c = Math.cos(lat * D), N = A / Math.sqrt(1 - E2 * s * s);
return [N * c * Math.cos(lon * D), N * c * Math.sin(lon * D), N * (1 - E2) * s]; }
function PFm() { return window.__pf && window.__pf.PF; }
function localFn(lat0, lon0) {
var PF = PFm();
if (PF) { var an = PF.placeKey(lat0, lon0), o = PF.toLocal(an, lat0, lon0, 0); // the overlay's own tangent plane
return function (lat, lon) { var q = PF.toLocal(an, lat, lon, 0); return [q.x - o.x, q.y - o.y]; }; }
var o = ecef(lat0, lon0), sl = Math.sin(lat0 * D), cl = Math.cos(lat0 * D), so = Math.sin(lon0 * D), co = Math.cos(lon0 * D);
return function (lat, lon) { var g = ecef(lat, lon), d = [g[0] - o[0], g[1] - o[1], g[2] - o[2]];
return [-so * d[0] + co * d[1], -sl * co * d[0] - sl * so * d[1] + cl * d[2]]; };
}
// ---- data ----
var pts = null, fps = null, loading = null;
function kvList(v) { return String(v || '').split(/[;:,]/).map(function (s) { return Math.round(Number(s) / 1000); })
.filter(function (k) { return k >= 1; }).sort(function (a, b) { return b - a; }); }
function load() {
if (loading) return loading;
loading = Promise.all([
fetch(GA).then(function (r) { return r.json(); }),
fetch(FP_URL).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; })
]).then(function (res) {
pts = res[0].features.map(function (f, i) { var c = f.geometry.coordinates;
return { i: i, lon: c[0], lat: c[1], kv: kvList(f.properties && f.properties.voltage) }; }); // voltage only
fps = {};
if (res[1] && res[1].f && (!res[1].atlas || res[1].atlas === ATLAS)) res[1].f.forEach(function (r) { fps[r[0]] = { how: r[1], ring: r[2] }; });
});
return loading;
}
// ---- geometry helpers (all metres, z up) ----
function seg(L, a, b, za, zb) { L.push([a[0], a[1], za, b[0], b[1], zb === undefined ? za : zb]); }
function box(L, cx, cy, ux, uy, hw, hd, h) { // oriented box: centre, axis u, half width/depth, height
var vx = -uy, vy = ux, P = [[-hw, -hd], [hw, -hd], [hw, hd], [-hw, hd]].map(function (p) { return [cx + p[0] * ux + p[1] * vx, cy + p[0] * uy + p[1] * vy]; });
for (var i = 0; i < 4; i++) { var a = P[i], b = P[(i + 1) % 4]; seg(L, a, b, 0); seg(L, a, b, h); seg(L, a, a, 0, h); }
}
function fence(L, ring, dashed) { // posts every ~8 m, bottom rail, 2.4 m top wire
for (var i = 0; i + 1 < ring.length; i++) {
var a = ring[i], b = ring[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], len = Math.hypot(dx, dy), n = Math.max(1, Math.round(len / 8));
for (var k = 0; k < n; k++) {
var p = [a[0] + dx * k / n, a[1] + dy * k / n], q = [a[0] + dx * (k + 1) / n, a[1] + dy * (k + 1) / n];
seg(L, p, p, 0, 2.4);
if (dashed) { var m = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2]; seg(L, p, m, 2.4); seg(L, p, m, 0.1); }
else { seg(L, p, q, 2.4); seg(L, p, q, 0.1); seg(L, p, q, 1.2); }
}
}
}
function frameOf(ring) { // centroid and the principal (longest-edge) axis
var cx = 0, cy = 0, n = ring.length - 1; for (var i = 0; i < n; i++) { cx += ring[i][0]; cy += ring[i][1]; } cx /= n; cy /= n;
var best = 0, ux = 1, uy = 0;
for (i = 0; i < n; i++) { var dx = ring[i + 1][0] - ring[i][0], dy = ring[i + 1][1] - ring[i][1], l = Math.hypot(dx, dy); if (l > best) { best = l; ux = dx / l; uy = dy / l; } }
var w = 0, d = 0; for (i = 0; i < n; i++) { var x = ring[i][0] - cx, y = ring[i][1] - cy; w = Math.max(w, Math.abs(x * ux + y * uy)); d = Math.max(d, Math.abs(-x * uy + y * ux)); }
var area = 0; for (i = 0; i < n; i++) area += ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1];
return { cx: cx, cy: cy, ux: ux, uy: uy, hw: w, hd: d, area: Math.abs(area) / 2 };
}
// Put a { lon, lat, lines } block on the overlay's 100 m place lattice and pack its buffer once (as connect-here does).
function place(b) {
var PF = PFm(); if (!PF) return b;
var an = PF.placeKey(b.lat, b.lon), o = PF.toLocal(an, b.lat, b.lon, 0);
var L = b.lines.map(function (l) { return [l[0] + o.x, l[1] + o.y, l[2], l[3] + o.x, l[4] + o.y, l[5]]; });
b.anchor = an; b.lines = L; b.buf = PF.wireBuffer(an, L); return b;
}
var EST_HALF = function (kv) { return kv >= 275 ? 90 : kv >= 132 ? 40 : kv >= 66 ? 25 : 15; };
// ---- stroke font for the voltage label: 0-9, k, V, / on a 1 x 2 cell ----
var G = {
'0': [[0,0,1,0],[1,0,1,2],[1,2,0,2],[0,2,0,0],[0,0,1,2]], '1': [[0.5,0,0.5,2],[0.2,1.7,0.5,2],[0.2,0,0.8,0]],
'2': [[1,0,0,0],[0,0,0,1],[0,1,1,1],[1,1,1,2],[1,2,0,2]], '3': [[0,0,1,0],[1,0,1,2],[1,2,0,2],[0.2,1,1,1]],
'4': [[0,2,0,1],[0,1,1,1],[1,2,1,0]], '5': [[1,2,0,2],[0,2,0,1],[0,1,1,1],[1,1,1,0],[1,0,0,0]],
'6': [[1,2,0,2],[0,2,0,0],[0,0,1,0],[1,0,1,1],[1,1,0,1]], '7': [[0,2,1,2],[1,2,0.3,0]],
'8': [[0,0,1,0],[1,0,1,2],[1,2,0,2],[0,2,0,0],[0,1,1,1]], '9': [[0,0,1,0],[1,0,1,2],[1,2,0,2],[0,2,0,1],[0,1,1,1]],
'k': [[0,0,0,2],[0,0.5,0.8,1.2],[0.3,0.8,0.9,0]], 'V': [[0,2,0.5,0],[0.5,0,1,2]], '/': [[0,0,1,2]], ' ': []
};
function label(L, text, cx, cy, z0, size, bearing) { // vertical text facing the camera bearing at build time
var b = bearing * D, rx = Math.cos(b), ry = -Math.sin(b), adv = size * 1.5, x0 = -adv * text.length / 2;
for (var c = 0; c < text.length; c++) (G[text[c]] || []).forEach(function (s) {
var ax = x0 + c * adv + s[0] * size, bx = x0 + c * adv + s[2] * size;
L.push([cx + ax * rx, cy + ax * ry, z0 + s[1] * size, cx + bx * rx, cy + bx * ry, z0 + s[3] * size]); });
}
function kvText(kv) { return kv.length ? kv.slice(0, 2).join('/') + ' kV' : ''; }
// ---- one compound = one block (built once); its label = a second small block, rebuilt only when bearing swings ----
function compound(s) {
var loc = localFn(s.lat, s.lon), fp = fps[s.i], top = s.kv[0] || 33, ring, dashed = false;
if (fp) ring = fp.ring.map(function (p) { return loc(p[1], p[0]); });
else { var h = EST_HALF(top); ring = [[-h, -h], [h, -h], [h, h], [-h, h], [-h, -h]]; dashed = true; }
var L = [], f = frameOf(ring);
fence(L, ring, dashed);
// plinths (estimate): count from voltage and area, laid on a row along the compound's long axis, 60% inset
var n = Math.max(1, Math.min(8, Math.round(f.area / (top >= 275 ? 9000 : top >= 132 ? 3500 : 1500)))),
pw = Math.min(6, f.hw * 0.6 / n + 1), pd = Math.min(4, f.hd * 0.35), ph = top >= 275 ? 5 : top >= 132 ? 4 : 2.5;
for (var k = 0; k < n; k++) {
var t = n === 1 ? 0 : (k / (n - 1) - 0.5) * 1.2 * f.hw;
box(L, f.cx + t * f.ux, f.cy + t * f.uy, f.ux, f.uy, pw, pd, ph);
var gx = f.cx + t * f.ux - f.uy * pd * 2.2, gy = f.cy + t * f.uy + f.ux * pd * 2.2; // busbar gantry leg pair
seg(L, [gx, gy], [gx, gy], 0, ph * 2); seg(L, [gx, gy], [f.cx + t * f.ux, f.cy + t * f.uy], ph * 2, ph);
}
if (n > 1) seg(L, [f.cx - 0.6 * f.hw * f.ux - f.uy * pd * 2.2, f.cy - 0.6 * f.hw * f.uy + f.ux * pd * 2.2],
[f.cx + 0.6 * f.hw * f.ux - f.uy * pd * 2.2, f.cy + 0.6 * f.hw * f.uy + f.ux * pd * 2.2], ph * 2); // busbar
return place({ lon: s.lon, lat: s.lat, lines: L, substation: s.i, est: dashed, top: Math.max(f.hw, f.hd), f: f });
}
function labelBlock(s, c, bearing) {
var L = [], t = kvText(s.kv), size = Math.max(2.5, Math.min(7, 1.6 * c.top / (1.5 * t.length))); // text no wider than the compound
label(L, t, c.f.cx, c.f.cy, Math.max(9, Math.min(20, c.top * 0.25)), size, bearing);
return place({ lon: s.lon, lat: s.lat, lines: L, substationLabel: s.i });
}
var on = false, built = {}, lastC = null, lastB = null;
function dist(a, b) { var x = (b.lon - a.lon) * 111320 * Math.cos(a.lat * D), y = (b.lat - a.lat) * 110574; return Math.hypot(x, y); }
function nearby(c, r, want) {
return pts.filter(function (s) { return (!want || s.kv.indexOf(want) >= 0); })
.map(function (s) { return { s: s, d: dist(c, s) }; }).filter(function (o) { return o.d < r; })
.sort(function (a, b) { return a.d - b.d; });
}
function refresh(force) {
var map = SIM.map;
if (!on || !pts || map.getZoom() < MINZ) { if (Object.keys(built).length) { SIM.removeWhere(function (b) { return b.substation !== undefined || b.substationLabel !== undefined; }); built = {}; SIM.repaint(); } return; }
var cc = map.getCenter(), c = { lon: cc.lng, lat: cc.lat }, br = map.getBearing();
var moved = !lastC || dist(lastC, c) > RADIUS / 3, turned = lastB === null || Math.abs(((br - lastB + 540) % 360) - 180) > 30;
if (!force && !moved && !turned) return;
var keep = {}; nearby(c, RADIUS, 0).slice(0, MAX).forEach(function (o) { keep[o.s.i] = o.s; });
SIM.removeWhere(function (b) { return (b.substation !== undefined && !keep[b.substation]) || (b.substationLabel !== undefined && (turned || !keep[b.substationLabel])); });
var nb = {}; for (var i in keep) {
var s = keep[i], cb = built[i] || compound(s);
if (!built[i]) SIM.addBlock(cb);
nb[i] = cb; if (turned || !built[i]) SIM.addBlock(labelBlock(s, cb, br));
}
built = nb; lastC = c; if (turned) lastB = br; SIM.repaint();
}
// ---- "go substation 132": fly to the nearest, then circle it once (the animation) ----
function go(kv) {
return load().then(function () {
var map = SIM.map, cc = map.getCenter(), c = { lon: cc.lng, lat: cc.lat };
var best = nearby(c, 1e7, kv || 0)[0];
if (!best) { SIM.info('No substation with ' + kv + ' kV in the GridAtlas points.'); return null; }
on = true; syncBtn(); var s = best.s, fp = fps[s.i];
SIM.info('Nearest ' + (kv ? kv + ' kV ' : '') + 'substation: ' + (best.d / 1000).toFixed(1) + ' km, ' + kvText(s.kv) + ', ' +
s.lat.toFixed(5) + ', ' + s.lon.toFixed(5) + (fp ? '. Fence from mapped footprint.' : '. Fence dashed: size estimated.') + ' ' + CREDIT);
map.flyTo({ center: [s.lon, s.lat], zoom: 17.2, pitch: 62, bearing: map.getBearing(), speed: 1.6, curve: 1.4 });
map.once('moveend', function () { refresh(true);
var b0 = map.getBearing(); map.rotateTo(b0 + 120, { duration: 6000, easing: function (t) { return t; } }); });
return { lat: s.lat, lon: s.lon, kv: s.kv, km: +(best.d / 1000).toFixed(2), footprint: fp ? fp.how : 'estimate' };
});
}
function command(text) {
var m = /^\s*go\s+sub(?:station)?s?\s*(\d+)?\s*(?:kv)?\s*$/i.exec(text || ''); if (!m) return null;
return go(m[1] ? Number(m[1]) : 0);
}
// ---- UI: a Substations toggle in the bar and a small command box (type, Enter) ----
var btn = null;
function syncBtn() { if (btn) btn.classList.toggle('on', on); }
function ui() {
var bar = document.getElementById('bar');
var toggle = function () { on = !on; syncBtn(); if (on) { SIM.info(CREDIT); load().then(function () { refresh(true); }); } else refresh(true); };
if (SIM.addButton) btn = SIM.addButton('Substations', toggle); else { btn = document.createElement('button'); btn.textContent = 'Substations'; btn.onclick = toggle; if (bar) bar.appendChild(btn); }
var inp = document.createElement('input'); inp.placeholder = 'go substation 132'; inp.setAttribute('aria-label', 'Substation command');
inp.style.cssText = 'font:14px monospace;padding:10px;border-radius:6px;border:1px solid #456;background:#0b1220;color:#dfe;min-height:44px;width:12em;box-sizing:border-box';
inp.addEventListener('keydown', function (e) { e.stopPropagation(); if (e.key === 'Enter') { if (!command(inp.value)) SIM.info('Try: go substation 132'); inp.blur(); } });
inp.addEventListener('keyup', function (e) { e.stopPropagation(); });
(bar || document.body).appendChild(inp);
}
// Exact check: each compound sits at its GridAtlas point (===), and says whether its fence is a mapped footprint.
function check() {
var exact = 0, bad = [], mapped = 0, est = 0;
for (var i in built) { var b = built[i], s = pts[b.substation];
if (s && b.lon === s.lon && b.lat === s.lat) exact++; else bad.push(b.substation);
if (b.est) est++; else mapped++; }
return { live: Object.keys(built).length, exact: exact, bad: bad, footprint: mapped, estimated: est, credit: CREDIT };
}
function start() {
ui();
SIM.map.on('moveend', function () { if (on) refresh(false); });
window.SUBS = { go: go, command: command, show: function (v) { on = v !== false; syncBtn(); return load().then(function () { refresh(true); }); },
count: function () { return Object.keys(built).length; }, credit: CREDIT, check: check };
}
(function wait() { if (window.SIM && SIM.map) start(); else setTimeout(wait, 100); })();
})();Cells
A JavaScript module in the apparatus folder of Faraday that works with half adder (`halfAdder`).
ingestfaraday / apparatus/cells.mjs · lines 1–125 of 125 · Not reached from any entry point (candidate for review) · pattern inputOn (shared by 2 files)
- What it does
- Defines 16 functions or classes, including place, inputOn, compile, state, read.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): 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 3 files: Cells Test (faraday); E099 (faraday); Faraday — Experiments (faraday).
- What it achieves
- It resets keys (`resetKeys`) and is built from the place step (`place`) and the input on helper (`inputOn`). The apparatus for experiments 16 to 19: can the dots compute?
- Why it matters
- Imported by E099 and Faraday — Experiments. Checked by Cells Test.
- Application
- faraday · apparatus · JavaScript module
- Uses
- none found
- Used by
- imported by Cells Test (import), imported by E099 (import), imported by Faraday — Experiments (import), mentioned in Standalone (comment link)
- Produces
- GOLDEN_ANGLE, place, compile, state, read, settles, resetKeys, halfAdder, adder4, latch
- Defines here
- place, inputOn, compile, state, read, settles, fresh, resetKeys, nand, not, and, or, xor, halfAdder, adder4, latch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 apparatus/cells.mjs:1-125 · blob f674be8f5908089232fec37681f55bc1fe382e50 · 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
// cells.mjs - the apparatus for experiments 16 to 19: can the dots compute?
//
// A CELL is one dot. It has a permanent key and nothing else of its own. Its state is HOME (dark, 0) or AWAY (lit, 1).
// A PROGRAM is a list of rules. There are only two kinds of rule:
//
// { key, input: 'a' } an INPUT cell: lit when the visitor's schedule says input 'a' is on at that tick
// { key, gate: [k1, k2] } a GATE cell: lit UNLESS both cells k1 and k2 were lit one tick earlier
//
// The second rule is the whole machine. It is the NAND gate, the one gate from which every other can be made, and it
// is "select the cells that another rule lit, and answer to them": one cell's OUTPUT drives another cell's GATE.
// The one tick of delay is the pulse: a change travels from cell to cell at a finite speed and never faster.
//
// NOTHING IS STORED PER CELL. state() is a pure function of (key, program, schedule, tick). It works backwards from
// the tick asked for to tick 0, when every cell is HOME. Ask twice, on any machine, and the answer is the same.
// (A cache inside one call only saves time; experiment 16 runs with it off and with it on and compares.)
//
// Place is also a pure function of the key, by the law the Kuiper draws with: r = sqrt(key), angle = key x golden angle.
// It plays no part in the logic. It is here so that a cell in this file is the same thing as a dot on the screen.
export const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
export function place(key) {
const r = Math.sqrt(key), a = key * GOLDEN_ANGLE;
return [r * Math.cos(a), r * Math.sin(a)];
}
// schedule: { a: [[from, to], ...] } input 'a' is on for ticks from <= t < to. A plain 0 or 1 means always.
function inputOn(schedule, name, t) {
const s = schedule[name];
if (s === 0 || s === 1) return s;
if (!s) return 0;
for (const [from, to] of s) if (t >= from && t < to) return 1;
return 0;
}
export function compile(program) {
const rules = new Map();
for (const r of program) {
if (rules.has(r.key)) throw new Error('two rules for key ' + r.key + ': a cell answers to one rule');
rules.set(r.key, r);
}
for (const r of program) if (r.gate) for (const k of r.gate)
if (!rules.has(k)) throw new Error('key ' + r.key + ' is gated by key ' + k + ', which has no rule');
return rules;
}
// The state of one cell at one tick. 1 = AWAY (lit), 0 = HOME (dark).
export function state(rules, schedule, key, t, cache) {
const r = rules.get(key);
if (r.input !== undefined) return inputOn(schedule, r.input, t);
if (t <= 0) return 0; // at tick 0 every gate cell is HOME
const id = cache ? key + ':' + t : null;
if (cache && cache.has(id)) return cache.get(id);
const a = state(rules, schedule, r.gate[0], t - 1, cache);
const b = state(rules, schedule, r.gate[1], t - 1, cache);
const out = (a && b) ? 0 : 1; // lit UNLESS both of its gate cells were lit
if (cache) cache.set(id, out);
return out;
}
// Read a set of cells at a tick, as the test does: it looks at the dots, not at the wiring.
export function read(rules, schedule, keys, t, useCache = true) {
const cache = useCache ? new Map() : null;
return keys.map(k => state(rules, schedule, k, t, cache));
}
// The first tick after which none of the named cells changes again for `hold` ticks, or -1 if they never settle.
export function settles(rules, schedule, keys, limit = 200, hold = 8) {
const cache = new Map();
let last = null, since = 0;
for (let t = 0; t <= limit; t++) {
const now = keys.map(k => state(rules, schedule, k, t, cache)).join('');
if (now === last) { if (t - since >= hold) return since; } else { last = now; since = t; }
}
return -1;
}
// ---- the circuits, written as programs. Every key is a real integer; nothing about a key is special. ----
let next = 0;
const fresh = () => ++next;
export function resetKeys(from = 0) { next = from; }
const nand = (p, a, b) => { const k = fresh(); p.push({ key: k, gate: [a, b] }); return k; };
const not = (p, a) => nand(p, a, a);
const and = (p, a, b) => not(p, nand(p, a, b));
const or = (p, a, b) => nand(p, not(p, a), not(p, b));
function xor(p, a, b) { const n = nand(p, a, b); return nand(p, nand(p, a, n), nand(p, b, n)); }
// HALF ADDER: two inputs, two outputs. sum = one of them but not both; carry = both.
export function halfAdder() {
resetKeys(1000);
const p = [];
const A = fresh(), B = fresh();
p.push({ key: A, input: 'a' }, { key: B, input: 'b' });
const sum = xor(p, A, B), carry = and(p, A, B);
return { program: p, A, B, sum, carry };
}
// FOUR BIT ADDER: adds any two numbers from 0 to 15. Made of the same cells and nothing else.
export function adder4() {
resetKeys(5000);
const p = [], a = [], b = [], s = [];
for (let i = 0; i < 4; i++) { a.push(fresh()); p.push({ key: a[i], input: 'a' + i }); }
for (let i = 0; i < 4; i++) { b.push(fresh()); p.push({ key: b[i], input: 'b' + i }); }
const zero = fresh(); p.push({ key: zero, input: 'zero' });
let c = zero;
for (let i = 0; i < 4; i++) {
const x = xor(p, a[i], b[i]);
s.push(xor(p, x, c));
c = or(p, and(p, a[i], b[i]), and(p, x, c));
}
return { program: p, a, b, sum: s, carry: c };
}
// LATCH: two gate cells, each gated by the other. setN and resetN are "active low": OFF means "do it".
export function latch() {
resetKeys(9000);
const p = [];
const S = fresh(), R = fresh();
p.push({ key: S, input: 'setN' }, { key: R, input: 'resetN' });
const Q = fresh(), Qn = fresh();
p.push({ key: Q, gate: [S, Qn] }, { key: Qn, gate: [R, Q] });
return { program: p, S, R, Q, Qn };
}Cells Test
A test in the apparatus folder of Faraday that checks Cells. It is built from the check step (`check`) and the count step (`count`).
testfaraday / apparatus/cells.test.mjs · lines 1–121 of 121 · Not reached from any entry point (candidate for review) · pattern count (shared by 27 files)
- What it does
- It tests its inputs. Defines check, q, count. Uses libraries node:fs, node:url, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): 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.
- Inputs & outputs
- Out: JSON file cells.result.json.
- What it achieves
- Every check READS THE CELLS (their lit or dark state at a tick).
- Why it matters
- Guards the behaviour of Cells.
- Application
- faraday · apparatus · test
- Uses
- Cells (import), node:fs, node:url, node:path
- Used by
- none found
- Produces
- check, q, count
- Defines here
- check, q, count
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 apparatus/cells.test.mjs:1-121 · blob db552202958cd3d8cd191a49db3dda6cdbedb37a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// cells.test.mjs - run with: node apparatus/cells.test.mjs
// Every check READS THE CELLS (their lit or dark state at a tick). None of them looks at how the program is wired.
// The results are written to apparatus/cells.result.json so an experiment entry can quote them exactly.
import { compile, read, settles, state, place, halfAdder, adder4, latch } from './cells.mjs';
import { writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const out = { ran: new Date().toISOString(), checks: [] };
let failed = 0;
function check(name, pass, detail) {
out.checks.push({ name, pass: !!pass, detail });
if (!pass) failed++;
console.log((pass ? 'PASS ' : 'FAIL ') + name + (detail ? ' ' + detail : ''));
}
// ---- 16. the half adder, from one kind of gate ----
{
const h = halfAdder(), rules = compile(h.program);
const gates = h.program.filter(r => r.gate).length;
const rows = [];
let ok = true, okNoCache = true, worst = 0;
for (const a of [0, 1]) for (const b of [0, 1]) {
const sched = { a, b };
const t = settles(rules, sched, [h.sum, h.carry]);
worst = Math.max(worst, t);
const [s, c] = read(rules, sched, [h.sum, h.carry], t + 8);
const [s2, c2] = read(rules, sched, [h.sum, h.carry], t + 8, false); // no cache at all: pure recursion
rows.push({ a, b, sum: s, carry: c, settled_at_tick: t });
if (s !== (a ^ b) || c !== (a & b)) ok = false;
if (s2 !== s || c2 !== c) okNoCache = false;
}
out.halfAdder = { cells: h.program.length, gate_cells: gates, rows, slowest_settle_tick: worst };
check('16 half adder: all four rows of the truth table, read from the cells', ok, JSON.stringify(rows));
check('16 the same answers with no cache (nothing kept between questions)', okNoCache);
check('16 it is made of one kind of gate cell only', h.program.every(r => r.input !== undefined || r.gate.length === 2), gates + ' gate cells, 2 input cells');
}
// ---- 16b. a planted fault must be caught: the test is able to fail ----
{
const h = halfAdder();
const bad = h.program.map(r => r.key === h.carry ? { key: r.key, gate: [h.A, h.A] } : r); // carry rewired to "not A"
const rules = compile(bad);
let ok = true;
for (const a of [0, 1]) for (const b of [0, 1]) {
const [s, c] = read(rules, { a, b }, [h.sum, h.carry], 40);
if (s !== (a ^ b) || c !== (a & b)) ok = false;
}
check('16 planted fault (carry rewired) is CAUGHT by the same check', ok === false);
}
// ---- 17. the four bit adder: every one of the 256 sums ----
{
const d = adder4(), rules = compile(d.program);
let wrong = 0, worst = 0;
const examples = [];
for (let x = 0; x < 16; x++) for (let y = 0; y < 16; y++) {
const sched = { zero: 0 };
for (let i = 0; i < 4; i++) { sched['a' + i] = (x >> i) & 1; sched['b' + i] = (y >> i) & 1; }
const keys = [...d.sum, d.carry];
const t = settles(rules, sched, keys, 300, 8);
worst = Math.max(worst, t);
const bits = read(rules, sched, keys, t + 8);
const got = bits.reduce((n, bit, i) => n + (bit << i), 0);
if (got !== x + y) wrong++;
if ((x === 7 && y === 9) || (x === 15 && y === 15) || (x === 6 && y === 3)) examples.push({ x, y, cells_say: got, settled_at_tick: t });
}
out.adder4 = { cells: d.program.length, gate_cells: d.program.filter(r => r.gate).length, sums_checked: 256, wrong, slowest_settle_tick: worst, examples };
check('17 four bit adder: 256 of 256 sums right, read from the cells', wrong === 0, 'wrong=' + wrong + ', slowest settles at tick ' + worst);
}
// ---- 18. the pulse has a finite speed: an answer is never there before the change could have reached it ----
{
const h = halfAdder(), rules = compile(h.program);
// a and b both switch on at tick 10. carry is two gate cells away from the inputs.
const sched = { a: [[10, 1e9]], b: [[10, 1e9]] };
const trace = [];
for (let t = 8; t <= 16; t++) trace.push({ t, carry: state(rules, sched, h.carry, t, new Map()) });
const first = trace.find(r => r.carry === 1)?.t;
out.pulse = { inputs_switch_at: 10, carry_first_lit_at: first, trace };
check('18 carry lights exactly two ticks after the inputs, never sooner', first === 12, 'first lit at tick ' + first);
}
// ---- 19. memory: does a latch remember, with nothing stored per cell? ----
{
const L = latch(), rules = compile(L.program);
// A. start it properly: hold reset for ticks 0 to 5, then SET for ticks 10 to 13, then leave both inputs idle (on).
const sched = { resetN: [[5, 40], [44, 1e9]], setN: [[0, 10], [13, 1e9]] };
const q = t => state(rules, sched, L.Q, t, new Map());
const afterReset = q(9), duringSet = q(13), longAfterSet = q(39), afterSecondReset = q(60);
out.latch = { afterReset, duringSet, longAfterSet, afterSecondReset };
check('19 after reset the latch is dark', afterReset === 0);
check('19 it is lit by a three tick SET pulse', duringSet === 1);
check('19 it is STILL lit 26 ticks after the pulse ended: it remembers', longAfterSet === 1);
check('19 a later reset pulse (ticks 40 to 43) makes it dark again', afterSecondReset === 0);
// B. what happens if it is never reset: both inputs idle from tick 0.
const idle = { resetN: 1, setN: 1 };
const flick = [];
for (let t = 1; t <= 8; t++) flick.push(state(rules, idle, L.Q, t, new Map()));
out.latch.never_reset = flick;
const oscillates = flick.join('') === '10101010';
check('19 OBSERVED: never reset, it flickers lit, dark, lit, dark for ever (recorded, not hidden)', oscillates, flick.join(''));
// C. the cost of remembering without storing: the question at tick t works back through t ticks.
let calls = 0;
const count = (key, t) => { calls++; const r = rules.get(key); if (r.input !== undefined || t <= 0) return; count(r.gate[0], t - 1); count(r.gate[1], t - 1); };
calls = 0; count(L.Q, 12); const c12 = calls; calls = 0; count(L.Q, 24); const c24 = calls;
out.latch.cost = { questions_at_tick_12: c12, questions_at_tick_24: c24 };
check('19 remembering costs TIME not storage: with no cache the work grows with the tick asked for', c24 > c12, c12 + ' then ' + c24 + ' questions');
}
// ---- place: a cell here is a dot there ----
{
const [x, y] = place(1002);
check('place is a pure function of the key, the Kuiper law', Math.abs(Math.hypot(x, y) - Math.sqrt(1002)) < 1e-9);
}
out.failed = failed;
const here = dirname(fileURLToPath(import.meta.url));
writeFileSync(join(here, 'cells.result.json'), JSON.stringify(out, null, 1));
console.log(failed === 0 ? '\nALL PASS' : '\n' + failed + ' FAILED');
process.exit(failed === 0 ? 0 : 1);Grid Finder
A Python command-line tool in the apparatus folder of Faraday that reads connection points, GB transmission network and transformers, using SHA-256.
geodesyfaraday / apparatus/grid_finder.py · lines 1–253 of 253 · Entry point · pattern distance_km (shared by 2 files)
- What it does
- It loads connection points, GB transmission network and transformers. Defines 8 functions or classes, including distance_km, _number, compare_published_path_ratings, GridFinder, __init__. Uses libraries argparse, collections, hashlib, json, math. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): 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.
- Inputs & outputs
- In: JSON file grid-finder-data.json; JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Test Grid Finder (faraday); Faraday — Index Page (faraday). Reached from 116 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/).
- What it achieves
- It compares published path ratings (`compare_published_path_ratings`) and is built from the distance km helper (`distance_km`) and the grid finder class (`GridFinder`). Offline, evidence-bound candidate search. No headroom inferred from a map. It accepts `--build-data`, `--lat` and `--lon`.
- Why it matters
- Loaded by the Faraday page. Checked by Test Grid Finder.
- Application
- faraday · apparatus · Python CLI
- Uses
- argparse, collections, hashlib, json, math, pathlib
- Used by
- imported by Test Grid Finder (import), linked from Faraday — Index Page (link)
- Produces
- distance_km, compare_published_path_ratings, GridFinder, build_data
- Defines here
- distance_km, _number, compare_published_path_ratings, GridFinder, __init__, path_to_voltage, query, build_data
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 apparatus/grid_finder.py:1-253 · blob 474f697400988334f14ce31c5b60eae93f8cb0f1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""Offline, evidence-bound candidate search. No headroom inferred from a map.
CLI: python grid_finder.py --lat 53.3 --lon -0.8 --mw 100 --voltage-kv 132
API: GridFinder().query(latitude=..., longitude=..., mw=..., voltage_kv=...)
"""
import argparse
from collections import defaultdict, deque
import hashlib
import json
import math
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATA_PATH = HERE / 'grid-finder-data.json'
EARTH_RADIUS_KM = 6378.137
LIMITATION = ('Candidate screening over a dated published graph, not a connection offer, '
'available capacity, power-flow result or engineering approval.')
def distance_km(lon1, lat1, lon2, lat2):
"""Atlas spherical radius; clamp protects antipodal rounding."""
dlat, dlon = math.radians(lat2-lat1), math.radians(lon2-lon1)
a = math.sin(dlat/2)**2 + math.cos(math.radians(lat1))*math.cos(math.radians(lat2))*math.sin(dlon/2)**2
a = min(1., max(0., a))
return 2*EARTH_RADIUS_KM*math.atan2(math.sqrt(a), math.sqrt(1-a))
def _number(name, value, minimum=None, maximum=None):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValueError(name+' must be a finite number')
if minimum is not None and value < minimum or maximum is not None and value > maximum:
raise ValueError(name+' outside supported range')
return value
def compare_published_path_ratings(path, mw, power_factor, season='winter'):
"""Compare entered demand against each published nameplate, never spare capacity."""
_number('mw', mw, 0)
_number('power_factor', power_factor, .000001, 1)
if season not in ('winter', 'spring', 'summer', 'autumn'):
raise ValueError('season must be winter, spring, summer or autumn')
apparent_mva = mw/power_factor
rows = []
for edge in path:
field = 'rating_mva' if edge['kind'] == 'transformer' else season+'_mva'
rating = edge.get('published_ratings_mva', {}).get(field)
known = isinstance(rating, (int, float)) and math.isfinite(rating) and rating > 0
rows.append({'edge_id': edge['edge_id'], 'source_row': edge['source_row'],
'rating_field': field, 'published_rating_mva': rating if known else None,
'entered_apparent_mva': apparent_mva,
'ratio_to_nameplate': apparent_mva/rating if known else None,
'exceeds_nameplate': apparent_mva > rating if known else None})
return {'schema': 'globalgrid.published-rating-comparison.v1', 'mw': mw,
'power_factor': power_factor, 'season': season, 'edges': rows,
'available_headroom_mw': None,
'basis': 'Entered apparent demand compared separately with published edge ratings. Existing flows, power sharing, contingencies and connection headroom are not solved.'}
class GridFinder:
def __init__(self, data_path=DATA_PATH, data=None):
self.data = data if data is not None else json.loads(Path(data_path).read_text(encoding='utf-8'))
if self.data.get('schema') != 'globalgrid.grid-finder-data.v1':
raise ValueError('Unsupported graph schema')
self.sites = {s['code']: s for s in self.data['sites']}
self.nodes = {n['id']: n for n in self.data['nodes']}
self.site_nodes = defaultdict(list)
for n in self.nodes.values():
self.site_nodes[n['site_code']].append(n['id'])
self.adj = defaultdict(list)
self.refused_edges = defaultdict(list)
for edge in self.data['edges']:
a, b = self.nodes.get(edge['from']), self.nodes.get(edge['to'])
reason = None
if not a or not b:
reason = 'MISSING_PUBLISHED_NODE'
elif a.get('voltage_kv') is None or b.get('voltage_kv') is None:
reason = 'UNDECLARED_NODE_VOLTAGE'
elif a['voltage_kv'] != b['voltage_kv'] and edge['kind'] != 'transformer':
reason = 'CIRCUIT_CHANGES_VOLTAGE'
for near, far in [(edge['from'], edge['to']), (edge['to'], edge['from'])]:
if reason:
self.refused_edges[near].append({'edge': edge['id'], 'reason': reason})
else:
self.adj[near].append((far, edge))
for edges in self.adj.values():
edges.sort(key=lambda x: (x[0], x[1]['id']))
def path_to_voltage(self, site_code, voltage_kv, target_kv=400, max_hops=12):
starts = sorted(n for n in self.site_nodes[site_code]
if self.nodes[n].get('voltage_kv') == voltage_kv)
if not starts:
return {'status': 'NO_VALIDATED_NODE_AT_REQUESTED_VOLTAGE', 'hops': None, 'path': [],
'explored_nodes': 0, 'refused_edge_count': 0}
queue = deque(starts)
parent = {n: None for n in starts}
depth = {n: 0 for n in starts}
refused, cutoff = set(), False
while queue:
node = queue.popleft()
if self.nodes[node]['voltage_kv'] >= target_kv:
path = []
at = node
while parent[at] is not None:
near, edge = parent[at]
path.append({'from_node': near, 'to_node': at, 'edge_id': edge['id'],
'kind': edge['kind'], 'from_kv': self.nodes[near]['voltage_kv'],
'to_kv': self.nodes[at]['voltage_kv'],
'published_ratings_mva': edge.get('ratings_mva', {}),
'source_row': edge['source_row']})
at = near
return {'status': 'PUBLISHED_PATH_FOUND', 'hops': len(path), 'path': path[::-1],
'target_node': node, 'target_site': self.nodes[node]['site_code'],
'target_voltage_kv': self.nodes[node]['voltage_kv'],
'explored_nodes': len(parent), 'refused_edge_count': len(refused)}
refused.update(e['edge'] for e in self.refused_edges[node])
if depth[node] >= max_hops:
cutoff = cutoff or any(far not in parent for far, _ in self.adj[node])
continue
for far, edge in self.adj[node]:
if far not in parent:
parent[far] = (node, edge)
depth[far] = depth[node]+1
queue.append(far)
return {'status': 'HOP_LIMIT_REACHED' if cutoff else 'NO_PATH_IN_VALIDATED_PUBLISHED_GRAPH',
'hops': None, 'path': [], 'explored_nodes': len(parent),
'refused_edge_count': len(refused)}
def query(self, latitude, longitude, mw, voltage_kv=None, target_kv=400,
headroom_mw_by_site=None, limit=12, max_hops=12, radius_km=None):
_number('latitude', latitude, -90, 90)
_number('longitude', longitude, -180, 180)
_number('mw', mw, 0)
_number('target_kv', target_kv, .001)
if voltage_kv is not None:
_number('voltage_kv', voltage_kv, .001)
if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 886:
raise ValueError('limit must be an integer in [1,886]')
if not isinstance(max_hops, int) or isinstance(max_hops, bool) or not 0 <= max_hops <= 100:
raise ValueError('max_hops must be an integer in [0,100]')
if radius_km is not None:
_number('radius_km', radius_km, 0)
headroom = {} if headroom_mw_by_site is None else headroom_mw_by_site
if not isinstance(headroom, dict):
raise ValueError('headroom_mw_by_site must be a mapping of site code to entered MW')
for code, value in headroom.items():
if code not in self.sites:
raise ValueError('Unknown headroom site code: '+str(code))
_number('entered headroom '+code, value, 0)
candidates = []
for code, site in sorted(self.sites.items()):
if voltage_kv is not None and voltage_kv not in site['voltages_kv']:
continue
point = site.get('location')
if not point:
continue
km = distance_km(longitude, latitude, point['lon'], point['lat'])
if radius_km is not None and km > radius_km:
continue
if voltage_kv is None:
topology = {'status': 'CONNECTION_VOLTAGE_NOT_ENTERED', 'hops': None, 'path': []}
else:
topology = self.path_to_voltage(code, voltage_kv, target_kv, max_hops)
capacity = {'status': 'UNKNOWN', 'entered_headroom_mw': None, 'margin_mw': None,
'within_entered_headroom': None}
if code in headroom:
capacity.update(status='USER_ENTERED_SCENARIO', entered_headroom_mw=headroom[code],
margin_mw=headroom[code]-mw, within_entered_headroom=mw <= headroom[code])
candidates.append({'site_code': code, 'name': site['name'], 'location': point,
'transmission_owner': site.get('transmission_owner'),
'voltages_kv': site['voltages_kv'], 'distance_km': km,
'topology': topology, 'capacity': capacity, 'pareto_tier': None})
# Incomparable unknown paths remain ungraded. Do not treat unknown as failure or infinity.
remaining = [c for c in candidates if c['topology']['hops'] is not None]
tier = 1
while remaining:
front = [a for a in remaining if not any(
b['distance_km'] <= a['distance_km'] and b['topology']['hops'] <= a['topology']['hops']
and (b['distance_km'] < a['distance_km'] or b['topology']['hops'] < a['topology']['hops'])
for b in remaining)]
for c in front:
c['pareto_tier'] = tier
remaining = [c for c in remaining if c['pareto_tier'] is None]
tier += 1
# Distance order keeps nearby unknown cases visible; Pareto is an explicit separate annotation.
candidates.sort(key=lambda c: (c['distance_km'], c['site_code']))
result = {'schema': 'globalgrid.grid-finder-result.v1', 'limitation': LIMITATION,
'query': {'latitude': latitude, 'longitude': longitude, 'mw': mw,
'voltage_kv': voltage_kv, 'target_kv': target_kv, 'max_hops': max_hops,
'radius_km': radius_km},
'counts': self.data.get('counts', {}), 'matching_located_sites': len(candidates),
'ordering': 'geographic_distance_then_site_code',
'pareto_basis': 'distance_km and validated published hop count; fewer of each; unknown paths ungraded; tiers computed across all matching located sites',
'distance_basis': 'Spherical separation on Atlas radius 6378.137 km, not cable route length',
'topology_basis': 'Existing published circuits and transformers only; no invented same-site bus ties; unknown voltage edges excluded; fewest edges, not impedance or available capacity',
'source_publication': self.data.get('source_publication'),
'geometry_attribution': self.data.get('geometry_attribution'),
'sources': self.data.get('sources', []), 'candidates': candidates[:limit]}
return result
def build_data(source_root):
"""Compact public products; preserve precise provenance, not inferred connections."""
root = Path(source_root)
paths = [root/'connection-points.v3.json', root/'gb-transmission-network.v1.json']
points, network = [json.loads(p.read_text(encoding='utf-8')) for p in paths]
assert points['schema'] == 'data-grid-gb.connection-points.v3'
assert network['schema'] == 'data-grid-gb.transmission-network.v1'
sites = []
for p in points['connection_points']:
sites.append({'code': p['site_code'], 'name': p['name'], 'voltages_kv': p['voltages_kv'],
'transmission_owner': p.get('transmission_owner'), 'location': p.get('location')})
nodes = [{'id': n['node'], 'site_code': n['site_code'],
'voltage_kv': n.get('voltage_kv') if n.get('voltage_consistent_with_site') is True else None}
for n in network['nodes']]
edges = []
for field, kind in [('circuits', 'circuit'), ('transformers', 'transformer')]:
for i, row in enumerate(network[field]):
ratings = {k: v for k, v in row.items() if k.endswith('_mva') and isinstance(v, (int, float))}
edges.append({'id': kind+':'+str(i), 'from': row['node_1'], 'to': row['node_2'],
'kind': kind, 'ratings_mva': ratings, 'source_row': field+'['+str(i)+']'})
data = {'schema': 'globalgrid.grid-finder-data.v1', 'source_publication': network['source'],
'geometry_attribution': points['join']['geometry_source'],
'voltage_basis': 'Only voltage_consistent_with_site=true retained; undocumented node digits never decoded',
'sources': [{'repository': 'Ventusltd/data-grid-gb', 'path': 'derived/'+p.name,
'sha256': hashlib.sha256(p.read_bytes()).hexdigest(), 'bytes': p.stat().st_size}
for p in paths],
'counts': {'sites': len(sites), 'located_sites': sum(bool(s['location']) for s in sites),
'unlocated_sites': sum(not s['location'] for s in sites), 'nodes': len(nodes),
'circuits': len(network['circuits']), 'transformers': len(network['transformers']),
'unknown_voltage_nodes': sum(n['voltage_kv'] is None for n in nodes)},
'sites': sites, 'nodes': nodes, 'edges': edges}
DATA_PATH.write_text(json.dumps(data, separators=(',', ':')), encoding='utf-8')
return data
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--build-data', metavar='DERIVED_DIRECTORY')
p.add_argument('--lat', type=float)
p.add_argument('--lon', type=float)
p.add_argument('--mw', type=float, default=100)
p.add_argument('--voltage-kv', type=float)
p.add_argument('--target-kv', type=float, default=400)
p.add_argument('--limit', type=int, default=12)
p.add_argument('--headroom-json', default='{}')
args = p.parse_args()
if args.build_data:
print(json.dumps(build_data(args.build_data)['counts'], indent=2))
else:
if args.lat is None or args.lon is None:
p.error('--lat and --lon are required')
print(json.dumps(GridFinder().query(args.lat, args.lon, args.mw, args.voltage_kv,
args.target_kv, json.loads(args.headroom_json), args.limit), indent=2, allow_nan=False))