In this section
- Block Build transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-build.mjs lines 1–255
- Block MV transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-mv.mjs lines 1–139
- Bng geodesy · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/bng.mjs lines 1–214
- Bs7671 Checks transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/bs7671-checks.mjs lines 1–41
Block Build
A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, transformers, overhead lines (OHL) and substations.
transformglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-build.mjs · lines 1–255 of 255 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern pileTotals (shared by 3 files)
- What it does
- It calculates cables, transformers, overhead lines (OHL) and substations. Defines 25 functions or classes, including group, put, seg, poly, mark.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, transformers, overhead lines (OHL), substations, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV.
- What it achieves
- It builds block (`buildBlock`) and is built from the group step (`group`) and the put step (`put`). The owner's 10MVA solar block (`station.mjs`, ported from his explorer) placed on the measured ground, with the 33kV rings to the grid (`block-mv.mjs`), as line groups ordered for the build sequence. Its code works with 10 MVA, 33 kV and 5 MVA.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- Station (import), Block MV (import), Cable Rating (import), MV Network (import), Piles (import), Pile Rules (import), Block Trenches (import)
- Used by
- none found
- Produces
- padEarthworks, buildBlock, overheadClearance, blockCounts
- Defines here
- group, put, seg, poly, mark, box, median, pileTotals, padEarthworks, buildBlock, g, zLocal, baseOf, onTable, gq, at, edge, at, padOf, buried, lift, odMv, overheadClearance, blockCounts, inside
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/block-build.mjs:1-255 · blob c7a3ec963c02f85ebf017a6c1b0d2f41f50a86ae · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 block-build.mjs at v12 commit 3adcee9 (file last changed 604729d). Modular star family: public #146332 padEarthworks.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// block-build.mjs: the owner's 10 MVA solar block (station.mjs, ported from his explorer) placed on the measured
// ground, with the 33 kV rings to the grid (block-mv.mjs), as line groups ordered for the build sequence.
//
// Station 1 is drawn in full: 23 paired tables whose frames follow the ground (the frame height is the ground
// averaged across the table at every pile line, so it rides the terrain gently), piles from the frame down to the
// ground measured at each pile, every string's 30 modules in series, 28 pole inverters, the 1,344 DC home cables and
// 84 AC phase cables along his routes, lowered into the trenches at his depths, and the two 5 MVA transformers on a
// levelled pad. Stations 2 to N are the same block, drawn as table outlines, pad and transformers.
// Positions are national-grid metres (e, n, height); each group keeps them relative to its own base point.
// marks[i] is the vertex count once item i is drawn, so the sequence shows a prefix without copying anything.
// Pure: no DOM. ground(e, n) is the measured ground (NaN where none); fallback(e, n) answers there instead.
import { station, tableShape, tableOrigin, dcHomeRoutes, STATION_DEFAULTS as SD } from './station.mjs';
import { mvChain } from './block-mv.mjs';
import { build as cableBuild } from './cable-rating.mjs';
import { EQUIPMENT } from './mv-network.mjs';
import { planPiles } from './piles.mjs';
import { PILE_RULES as PR, revealBand } from './pile-rules.mjs';
import { blockTrenches, BLOCK_DC_ISC_A } from './block-trenches.mjs';
export { BLOCK_DC_ISC_A };
const PILE_LINES = 19; // pile lines along a table, every 5 modules
const PAD_MARGIN = 12; // station pad: 12 m round the transformers (the explorer's compound)
function group() { return { base: null, v: [], marks: [] }; }
const put = (G, p) => { if (!G.base) G.base = [p[0], p[1], p[2]]; G.v.push(p[0] - G.base[0], p[1] - G.base[1], p[2] - G.base[2]); };
const seg = (G, a, b) => { put(G, a); put(G, b); };
const poly = (G, pts) => { for (let i = 1; i < pts.length; i++) seg(G, pts[i - 1], pts[i]); };
const mark = G => G.marks.push(G.v.length / 3);
const box = (G, [x, y, z], w, d, h) => {
const c = [[x - w / 2, y - d / 2], [x + w / 2, y - d / 2], [x + w / 2, y + d / 2], [x - w / 2, y + d / 2]];
for (let i = 0; i < 4; i++) { const a = c[i], b = c[(i + 1) % 4]; seg(G, [...a, z], [...b, z]); seg(G, [...a, z + h], [...b, z + h]); seg(G, [...a, z], [...a, z + h]); }
};
const median = a => { const s = a.filter(Number.isFinite).sort((p, q) => p - q); return s.length ? s[Math.floor(s.length / 2)] : NaN; };
// The block's pile totals for the readout and the bill (embedment provisional).
const pileTotals = P => ({ revealAdjust: P.summary.revealAdjust, outsideBand: P.summary.revealHigh + P.summary.revealLow,
twistTables: P.summary.twistTables, gradingTables: P.summary.tablesNeedingGrading, cutM3: P.summary.cutM3, fillM3: P.summary.fillM3,
totalPileLengthM: P.summary.totalPileLengthM, embeddedM: P.piles.reduce((t, p) => t + p.embed, 0), embedM: P.assumed.embedMin,
revealAdjustM: P.assumed.revealAdjust, twistTolDeg: P.assumed.twistTolDeg });
/** Level pad over a rectangle: the median ground, and cut and fill on a 1 m grid (bank m3). */
export function padEarthworks(g, e0, n0, e1, n1, level = null) {
const hs = [];
for (let n = n0 + 0.5; n < n1; n += 1) for (let e = e0 + 0.5; e < e1; e += 1) hs.push(g(e, n));
const z = level ?? median(hs);
let cut = 0, fill = 0, unmeasured = 0;
for (const h of hs) { if (!Number.isFinite(h)) { unmeasured++; continue; } if (h > z) cut += h - z; else fill += z - h; }
return { level: z, cut, fill, unmeasured, area: (e1 - e0) * (n1 - n0) };
}
/**
* buildBlock({ anchor: [e, n], ground, fallback, stations, pocKv, towers, gpuPads, trench }) -> { groups, cables, trenches, summary }
* towers: [{ e, n, kv }] grid towers to connect to; gpuPads: [{ poly: [[e, n]...], level, cut, fill }] optional.
* trench: { soilKmW, load, split: { dc, branch, collector, mv }, cover: { dc, lv, mv }, drumM, ring } for sizing the trenches by rating
* (block-trenches.mjs); defaults when left out.
*/
export function buildBlock({ anchor, ground, fallback = () => NaN, stations = 4, pocKv = 400, towers = [], gpuPads = [], topology = 'radial',
connection = 'cable', modulesPerString = SD.modulesPerString, trench = {} }) {
const [E, N] = anchor;
let unmeasured = 0;
const g = (e, n) => { const h = ground(e, n); if (Number.isFinite(h)) return h; unmeasured++; const f = fallback(e, n); return Number.isFinite(f) ? f : 0; };
// Modules in series are the owner's to change: each table row keeps its three strings, so the table is 3 strings long.
const mps = Math.round(modulesPerString) || SD.modulesPerString, s = { ...SD, modulesPerString: mps, columns: mps * SD.columns / SD.modulesPerString };
const st = station(s, { corners: false }), T = tableShape(s), t = s.tilt * Math.PI / 180;
const mv = mvChain({ stations, stationMVA: st.inventory.aggregateInverterMVA, pocKv, topology });
const G = {}; for (const k of ['outline', 'tables', 'strings', 'inverters', 'station', 'others', 'rmu', 'grid', 'open']) G[k] = group();
// ---- tables: frame height per pile line from the ground across the table, piles to the ground at each pile ----
const zLocal = x => { const d = Math.abs(x) - T.halfRidgeGap; return s.height + Math.max(0, T.depth - d) * Math.tan(t); };
const frames = [], piles = { count: 0, min: Infinity, max: -Infinity }, lowEdge = { min: Infinity };
for (let n = 0; n < s.tables; n++) {
const [x0, y0] = tableOrigin(n, s), ys = Array.from({ length: PILE_LINES }, (_, k) => y0 + k * T.span / (PILE_LINES - 1));
// The frame sits on the highest ground under either low edge or the ridge, so the lowest module edge keeps its
// height at every pile line; smoothing may only raise it, never drop an edge towards the ground.
const edge = T.halfRidgeGap + T.depth, raw = ys.map(y => Math.max(g(E + x0 - edge, N + y), g(E + x0 + edge, N + y), g(E + x0, N + y)));
const sm = raw.map((_, k) => Math.max(raw[k], (raw[Math.max(0, k - 1)] + raw[k] + raw[Math.min(raw.length - 1, k + 1)]) / 3));
frames.push({ x0, y0, ys, sm });
}
const baseOf = (n, y) => {
const F = frames[n], u = Math.min(Math.max((y - F.y0) / T.span, 0), 1) * (PILE_LINES - 1), k = Math.min(PILE_LINES - 2, Math.floor(u));
return F.sm[k] + (F.sm[k + 1] - F.sm[k]) * (u - k);
};
const onTable = (n, x, y) => [E + x, N + y, baseOf(n, y) + zLocal(x - frames[n].x0)];
// Piles, automatic, on the shared rules (pile-rules.mjs): each post line under the owner's frame, its tops where the
// frame puts them, checked for reveal (band and head adjustment), grading, embedment and twist by piles.mjs.
const gq = (e, n) => { const h = ground(e, n); if (Number.isFinite(h)) return h; const f = fallback(e, n); return Number.isFinite(f) ? f : 0; };
const pileRows = [];
frames.forEach((F, n) => { for (const side of [-1, 1]) [0.2, 0.8].forEach((k, j) => {
const x = side * (T.halfRidgeGap + T.depth * k), top = y => baseOf(n, y) + zLocal(x) - 0.12, id = `${n}:${side}:${j}`;
pileRows.push({ id, line: [[E + F.x0 + x, N + F.ys[0]], [E + F.x0 + x, N + F.ys[PILE_LINES - 1]]], tops: F.ys.map(top),
reveal: revealBand(zLocal(x) - 0.12), ...(j ? {} : { pair: { with: `${n}:${side}:1`, depth: T.depth * 0.6 } }) });
}); });
const plan = planPiles({ rows: pileRows, groundAt: gq, system: 'fixed', tableLength: T.span, tableGap: 0, pileSpacing: T.span / (PILE_LINES - 1) * (1 - 1e-12),
embedMin: PR.embedM, embedToReveal: PR.embedToReveal, gradingWidth: PR.gradingWidthM, revealAdjust: PR.revealAdjustM, twistTolDeg: PR.twistTolDeg, limits: { along: 'ns' } });
frames.forEach((F, n) => {
const at = (x, y, z) => [E + F.x0 + x, N + y, baseOf(n, y) + z];
for (const side of [-1, 1]) {
const edge = (off, dz) => F.ys.map(y => at(side * off, y, dz)), g2 = T.halfRidgeGap;
for (let r = 0; r <= s.rows; r++) { // outer low edge, row joints, ridge edge
const v = r * (s.moduleLength + s.moduleGap) - (r ? s.moduleGap / 2 : 0), off = g2 + T.depth - v * Math.cos(t);
poly(G.tables, edge(off, s.height + v * Math.sin(t)));
}
for (let c = 0; c <= s.columns; c++) { // module joints across the face
const y = F.y0 + Math.min(T.span, c * (s.moduleWidth + s.moduleGap));
seg(G.tables, at(side * (g2 + T.depth), y, s.height), at(side * g2, y, T.ridge));
}
for (const j of [0, 1]) for (const p of plan.rows.find(r => r.id === `${n}:${side}:${j}`).tables[0].piles) { // front, rear posts
g(p.x, p.y); seg(G.tables, [p.x, p.y, Math.min(p.ground, p.finishedGround)], [p.x, p.y, p.top]);
piles.count++; piles.min = Math.min(piles.min, p.reveal); piles.max = Math.max(piles.max, p.reveal);
}
for (const y of F.ys) { const p = at(side * (g2 + T.depth), y, s.height); lowEdge.min = Math.min(lowEdge.min, p[2] - g(p[0], p[1])); }
}
mark(G.tables);
});
// ---- strings: 30 modules in series through their terminals, in build order (table by table) ----
for (const x of st.strings) { poly(G.strings, x.modules.map(m => onTable(x.table, m.terminal[0], m.terminal[1]))); mark(G.strings); }
// ---- inverters on poles: box, pole to the ground ----
const invBase = st.inverters.map(i => g(E + i.point[0], N + i.point[1]));
st.inverters.forEach((inv, i) => {
const [x, y, z] = inv.point, b = invBase[i];
box(G.inverters, [E + x, N + y, b + z - 1], 1, 0.5, 1); seg(G.inverters, [E + x, N + y + 0.3, b], [E + x, N + y + 0.3, b + z]); mark(G.inverters);
});
// ---- station pads (level, cut and fill), transformers and RMUs; stations 2..N as outlines ----
const txs = s.transformers, px0 = Math.min(...txs.map(p => p[0])) - PAD_MARGIN, px1 = Math.max(...txs.map(p => p[0])) + PAD_MARGIN;
const py0 = Math.min(...txs.map(p => p[1])) - PAD_MARGIN, py1 = Math.max(...txs.map(p => p[1])) + PAD_MARGIN;
const pads = mv.stations.map(S => {
const [ox, oy] = S.offset, pad = padEarthworks(g, E + ox + px0, N + oy + py0, E + ox + px1, N + oy + py1);
const L = S.index ? G.others : G.station, z = pad.level;
const q = [[px0, py0], [px1, py0], [px1, py1], [px0, py1]].map(([x, y]) => [E + ox + x, N + oy + y, z]);
for (let i = 0; i < 4; i++) { seg(L, q[i], q[(i + 1) % 4]); seg(L, [q[i][0], q[i][1], z + 2.4], [q[(i + 1) % 4][0], q[(i + 1) % 4][1], z + 2.4]); }
for (const p of txs) box(L, [E + ox + p[0], N + oy + p[1], z], 4, 4, 3);
box(G.rmu, [E + S.rmu[0], N + S.rmu[1], z], EQUIPMENT.rmu.w, EQUIPMENT.rmu.d, EQUIPMENT.rmu.h); mark(G.rmu);
if (S.index) for (const F of frames) for (const side of [-1, 1]) {
const a = [F.x0 + side * (T.halfRidgeGap + T.depth), F.x0 + side * T.halfRidgeGap], yy = [F.y0, F.y0 + T.span / 2, F.y0 + T.span];
const at = (x, y, h) => [E + ox + x, N + oy + y, g(E + ox + x, N + oy + y) + h];
poly(L, yy.map(y => at(a[0], y, s.height))); poly(L, yy.map(y => at(a[1], y, T.ridge)));
seg(L, at(a[0], yy[0], s.height), at(a[1], yy[0], T.ridge)); seg(L, at(a[0], yy[2], s.height), at(a[1], yy[2], T.ridge));
}
if (!S.index) mark(G.station);
return { id: S.id, ...pad };
});
const padOf = S => pads[S.index].level;
// ---- cables: his routes, lifted onto the tables, into the trench (depth below the ground) and up the poles ----
// Along a trench the cable follows the ground at its depth: a point every 5 m.
const buried = (a, b) => { const k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 5)), out = [];
for (let j = 1; j < k; j++) { const x = a[0] + (b[0] - a[0]) * j / k, y = a[1] + (b[1] - a[1]) * j / k; out.push([E + x, N + y, g(E + x, N + y) + a[2]]); }
return out; };
const lift = (pts, table, inv, endZ) => pts.flatMap((p, i) => {
const pre = i && p[2] < 0 && pts[i - 1][2] < 0 ? buried(pts[i - 1], p) : [];
if (p[2] < 0) return [...pre, [E + p[0], N + p[1], g(E + p[0], N + p[1]) + p[2]]];
if (inv != null && (i >= pts.length - 2 || Math.hypot(p[0] - st.inverters[inv].point[0], p[1] - st.inverters[inv].point[1]) < 0.8))
return [[E + p[0], N + p[1], invBase[inv] + p[2]]];
if (table != null) return [[E + p[0], N + p[1], baseOf(table, p[1]) + p[2]]];
return [[E + p[0], N + p[1], endZ + p[2]]];
});
const byIndex = new Map(st.strings.map(x => [x.index, x]));
const dc = dcHomeRoutes(st.strings, st.inverters.map(i => i.point), s).map(r => ({ id: r.id, inverter: r.inverter,
points: lift(r.points, byIndex.get(r.string).table, r.inverter) }));
const ac = st.acCables.map((c, i) => { const inv = Math.floor(i / 3), p = c.points, first = [E + p[0][0], N + p[0][1], invBase[inv] + p[0][2]];
return { id: c.id, inverter: inv, points: [first, ...lift(p.slice(1), null, null, padOf(mv.stations[0]))] }; });
const odMv = a => cableBuild(a).od;
const mvCables = mv.circuits.map(cc => {
const pts = [];
for (let i = 1; i < cc.plan.length; i++) {
const [a, b] = [cc.plan[i - 1], cc.plan[i]], k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 10));
for (let j = i === 1 ? 0 : 1; j <= k; j++) { const x = a[0] + (b[0] - a[0]) * j / k, y = a[1] + (b[1] - a[1]) * j / k; pts.push([E + x, N + y, g(E + x, N + y) - 0.85]); }
}
return { id: cc.id, ring: cc.ring, normallyOpen: cc.normallyOpen, areaMm2: cc.areaMm2, points: pts };
});
// Normally-open points: a ring on the RMU switch that is left open.
for (const r of mv.rings.filter(x => x.openAt)) { const S = mv.stations.find(x => x.id === r.openAt), z = padOf(S) + EQUIPMENT.rmu.h;
for (const h of [2.5, 4]) box(G.open, [E + S.rmu[0], N + S.rmu[1], z + h - 0.75], 0.8, 0.8, 0.75); mark(G.open); }
// ---- substation compound: switchroom, grid transformer(s) in bunds, connection structure (line tee as an option) ----
const C = mv.compound, cE = E + C.x, cN = N + C.y;
const gpu = gpuPads.find(p => inside(p.poly, cE, cN));
const cpad = padEarthworks(g, cE - C.w / 2, cN - C.d / 2, cE + C.w / 2, cN + C.d / 2, gpu ? gpu.level : null);
if (gpu) Object.assign(cpad, { cut: gpu.cut, fill: gpu.fill, source: 'GPU pad run (read-only)' });
const cz = cpad.level, fence = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => [cE + a * C.w / 2, cN + b * C.d / 2, cz]);
for (let i = 0; i < 4; i++) { seg(G.grid, fence[i], fence[(i + 1) % 4]); seg(G.grid, [...fence[i].slice(0, 2), cz + 2.4], [...fence[(i + 1) % 4].slice(0, 2), cz + 2.4]); }
const sw = EQUIPMENT.switchboard; box(G.grid, [E + mv.board[0], N + mv.board[1], cz], sw.d, sw.w, sw.h);
const gt = EQUIPMENT['grid-transformer'];
for (const [x, y] of mv.grid.at) { box(G.grid, [E + x, N + y, cz], gt.w, gt.d, gt.h); box(G.grid, [E + x, N + y, cz], gt.bund.w, gt.bund.d, gt.bund.h); }
const P = [E + mv.poc.at[0], N + mv.poc.at[1]], poc = EQUIPMENT.poc; box(G.grid, [...P, cz], poc.w, poc.d, poc.h);
// The HV connection runs as a fully ducted cable: down from the transformer, buried, and up the connection structure.
for (const [x, y] of mv.grid.at) poly(G.grid, [[E + x + gt.w / 2, N + y, cz + gt.h - 1], [E + x + gt.w / 2, N + y, cz - 1.1], [P[0], P[1], cz - 1.1], [P[0], P[1], cz + poc.h]]);
const line = towers.filter(w => w.kv >= pocKv).map(w => ({ ...w, d: Math.hypot(w.e - P[0], w.n - P[1]) })).sort((a, b) => a.d - b.d)[0] || null;
// The default landing is a ducted HV cable to the substation's bay (drawn by the single-line diagram, sld-symbols.mjs);
// the overhead tee into the nearest tower is an option, off by default.
if (connection === 'ohl-tee' && line && line.d <= 3000) for (const o of [-3, 0, 3]) seg(G.grid, [P[0] + o, P[1], cz + poc.h], [line.e + o, line.n, g(line.e, line.n) + 28]);
mark(G.grid);
// ---- outline of the whole plant (pegged out before the build starts) ----
const W = Math.max(...frames.map(F => F.x0)) + T.depth + 1, H = Math.max(...frames.map(F => F.y0)) + T.span + 1;
for (const S of mv.stations) {
const [ox, oy] = S.offset, q = [[-T.depth - 1, -3], [W, -3], [W, H], [-T.depth - 1, H]].map(([x, y]) => [E + ox + x, N + oy + y]);
for (let i = 0; i < 4; i++) { const a = q[i], b = q[(i + 1) % 4]; seg(G.outline, [...a, g(...a) + 0.3], [...b, g(...b) + 0.3]); }
}
mark(G.outline);
const ohl = overheadClearance(anchor, mv.stations, towers);
const works = blockTrenches(st, mv, E, N, odMv, trench, s), trenches = works.items;
const groups = {};
for (const [k, L] of Object.entries(G)) groups[k] = { base: L.base || [E, N, 0], v: new Float32Array(L.v), marks: L.marks };
const inv = st.inventory;
return { groups, cables: { dc, ac, mv: mvCables }, trenches, trenchPlan: works.plan, mv, station: st, pads, compoundPad: cpad, connection: line, onTable, // onTable: module detail
summary: { inventory: inv, blockKwp: inv.installedModules * s.moduleW / 1000, piles: { ...piles, ...pileTotals(plan) }, lowEdgeMin: lowEdge.min,
unmeasured, pads, compoundPad: cpad, connection: line ? { kv: line.kv, distanceM: line.d } : null, overhead: ohl } };
}
/**
* Overhead lines over the field: the closest any table corner of any station comes to a span (consecutive towers
* of one voltage, under 600 m apart). stations: mvChain(...).stations or a count. Null when no span is loaded.
*/
export function overheadClearance([E, N], stations, towers) {
const T = tableShape(SD), list = typeof stations === 'number' ? mvChain({ stations }).stations : stations;
const spans = towers.slice(1).map((w, i) => [towers[i], w]).filter(([a, b]) => a.kv === b.kv && Math.hypot(b.e - a.e, b.n - a.n) < 600);
let best = null;
for (const S of list) for (let n = 0; n < SD.tables; n++) for (const [x, y] of [[-1, 0], [1, 0], [-1, 1], [1, 1]]) {
const [x0, y0] = tableOrigin(n, SD), pe = E + S.offset[0] + x0 + x * (T.depth + T.halfRidgeGap), pn = N + S.offset[1] + y0 + y * T.span;
for (const [a, b] of spans) {
const dx = b.e - a.e, dy = b.n - a.n, k = Math.min(1, Math.max(0, ((pe - a.e) * dx + (pn - a.n) * dy) / (dx * dx + dy * dy)));
const d = Math.hypot(pe - a.e - k * dx, pn - a.n - k * dy);
if (!best || d < best.distanceM) best = { kv: a.kv, distanceM: d };
}
}
return best;
}
/** The counts readout for one block, as the owner's explorer states them, plus the MV chain. */
export function blockCounts(b) {
const i = b.summary.inventory;
return { tables: i.tables, tableKwp: i.tableKwp, blockKwp: b.summary.blockKwp, strings: i.totalStrings, connectedStrings: i.connectedStrings,
spareStrings: i.spareStrings, inverters: i.inverters, stringsPerInverter: [...new Set(i.stringsPerInverter)], inverterKVA: i.inverterKVA,
transformers: i.transformers, transformerMVA: i.transformerMVA, stationMVA: i.aggregateTransformerMVA, acPhaseCables: i.acPhaseCables,
dcHomeCables: i.dcHomeCables, dcRoutes: b.cables.dc.length, acRoutes: b.cables.ac.length, stations: b.mv.stations.length,
rings: b.mv.rings.length, gridTransformers: b.mv.grid.units, gridMVA: b.mv.grid.mva, pocKv: b.mv.poc.kv };
}
const inside = (poly, x, y) => {
let c = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const [xi, yi] = poly[i], [xj, yj] = poly[j];
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
}
return c;
};Block MV
A JavaScript module in the engine folder of GlobalGrid2050 that works with transformers, solar and cables, using IEC 60287 and IEC 60949.
Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609271552-site-world/world/block-mv.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Block MV; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9833 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/block-mv.mjs:1-137 6284ee02b77ded0ed6310420eede0bfcc7655201
- sha256 2260f10550bfcc5a178e4fa4f2e080ae6b3315f403b60b68a33fa1eacc9653d4
- target sha256 77dbdded292674617c48d7542de515b7f59b3f735fd54af1f6638dcd857f0232
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-mv.mjs · lines 1–139 of 139 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern dropWith (shared by 4 files)
- What it does
- It calculates transformers, solar and cables. Defines 12 functions or classes, including mvChain, colX, up, path, groupOf.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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, solar, cables, 400kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 33kV.
- Downstream impact
- Used directly by 2 files: Cmd Trench (globalgrid2050); Block Build (globalgrid2050).
- What it achieves
- It is built from the MV chain helper (`mvChain`), the col x helper (`colX`) and the path step (`path`). Stations of the solar block chained on 33kV feeders to the MV board, the grid transformer(s) and the connection, laid out and sized from the load. Its code works with 33 kV and 400 kV.
- Why it matters
- Imported by Cmd Trench and Block Build.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- Cable Rating (import), Plant Template (import), Plant Feeders (import), Single-Line Diagram (SLD) Rules (import)
- Used by
- imported by Cmd Trench (import), imported by Block Build (import)
- Produces
- MV_LAYOUT, mvChain
- Defines here
- mvChain, colX, up, path, groupOf, size, drop, dropWith, side, lineOf, off, xy
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/block-mv.mjs:1-139 · blob b592b0a795b7ca1ce5712ae1ec603299d4fce641 · 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: duplicate_candidate
// COPIED UNCHANGED from world/v12 block-mv.mjs at v12 commit 3adcee9 (file last changed 256ecf8). Modular star family: public #146351 mvChain.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// block-mv.mjs: stations of the solar block chained on 33 kV feeders to the MV board, the grid transformer(s) and the
// connection, laid out and sized from the load. Plant frame: metres east (x) and north (y) of station 1's own
// origin (station.mjs coordinates), heading 0.
//
// Layout: stations in columns of up to `rows` (2 by default) and up to 5 across; a spine trench runs along the south
// edge to the substation compound east of the field, and a feeder trench runs north up the east side of each
// column, beside a track, past each station's ring main unit (RMU) in its transformer compound. By default each
// feeder is a radial chain: it leaves one board section and runs station to station. With topology 'ring' it returns
// to the board, with one normally-open point in the middle so each half runs radially. Circuits sharing a stretch
// share a trench, trefoils 450 mm apart (as the two-circuit section in data/trench-sections.json), so the trench
// widens with the circuits in it, and each hop is rated with the group factor of the circuits it shares a line with.
// Sizing (plant-template.mjs rules): stations per feeder from the feeder limit; radial segments from the load they
// carry; a ring's segments carry the whole ring load when the open point is moved to one end (IEC 60287 rating,
// cable-rating.mjs), not below the fault minimum (adiabatic, IEC 60949); upsized until the normal-running drop is within 0.5 %; grid transformers from the packed
// load (gridChoice). Illustrative, not a design for any site.
import { sizeFor, dropPercent, SIZES } from './cable-rating.mjs';
import { gridChoice, faultMinArea, TEMPLATE_DEFAULTS } from './plant-template.mjs';
import { coverage } from './plant-feeders.mjs';
import { groupFactor } from './sld-rules.mjs';
export const MV_LAYOUT = Object.freeze({ pitchX: 200, pitchY: 800, maxCols: 5, rows: 2, rmu: [162, 332.5], columnX: 172, spineY: -20,
laneM: 0.45, compound: { w: 90, d: 60, gap: 25 } });
// Load per station: the block's inverters at their rating (MVA).
export function mvChain({ stations = 4, stationMVA = 9.856, pocKv = 400, topology = 'radial', layout = MV_LAYOUT, ...opts } = {}) {
const p = { ...TEMPLATE_DEFAULTS, ...opts }, L = layout, n = Math.round(stations);
if (!(n >= 1 && n <= 10)) throw Error('solar block: 1 to 10 stations');
if (![132, 275, 400].includes(pocKv)) throw Error('solar block: connection at 132, 275 or 400 kV');
const rows = n <= 3 ? 1 : Math.min(L.rows, Math.ceil(n / L.maxCols)), cols = Math.ceil(n / rows);
const st = Array.from({ length: n }, (_, s) => {
const col = Math.floor(s / rows), row = s % rows, off = [col * L.pitchX, row * L.pitchY];
return { id: `S${s + 1}`, index: s, col, row, offset: off, rmu: [off[0] + L.rmu[0], off[1] + L.rmu[1]], mva: stationMVA };
});
const fieldE = (cols - 1) * L.pitchX + L.columnX + 8;
const c = { x: fieldE + L.compound.gap + L.compound.w / 2, y: L.spineY - 5, w: L.compound.w, d: L.compound.d };
const board = [c.x - c.w / 2 + 12, c.y], gt0 = [c.x + 4, c.y + 12], poc = [c.x + c.w / 2 - 10, c.y];
// Network lines: 's' the spine (coordinate x), 'c<col>' a column (coordinate y), 'r<s>' a station's stub (x).
const colX = col => col * L.pitchX + L.columnX;
const up = s => [{ key: 'c' + s.col, a: L.spineY, b: s.rmu[1] }, { key: 'r' + s.index, a: colX(s.col), b: s.rmu[0] }];
const path = (A, B) => { // A, B: 'board' or a station
if (A === 'board') return [{ key: 's', a: board[0], b: colX(B.col) }, ...up(B)];
if (B === 'board') return path('board', A).map(q => ({ ...q, a: q.b, b: q.a })).reverse();
const out = [{ key: 'r' + A.index, a: A.rmu[0], b: colX(A.col) }];
if (A.col === B.col) out.push({ key: 'c' + A.col, a: A.rmu[1], b: B.rmu[1] });
else out.push({ key: 'c' + A.col, a: A.rmu[1], b: L.spineY }, { key: 's', a: colX(A.col), b: colX(B.col) }, { key: 'c' + B.col, a: L.spineY, b: B.rmu[1] });
out.push({ key: 'r' + B.index, a: colX(B.col), b: B.rmu[0] });
return out;
};
// Feeders: as many stations as the feeder limit allows (at most 4), in column order. Radial chains by default
// (board, then station to station); topology 'ring' returns each chain to the board with one normally-open hop.
const per = Math.max(1, Math.min(p.stationsPerFeederMax, Math.floor(p.feederLimitMVA / stationMVA)));
const nRings = Math.ceil(n / per), rings = [], ring = topology === 'ring';
const opt = { soilKmW: p.soilKmW, kv: 33, pf: p.powerFactor }, minArea = faultMinArea(p.faultKA, p.faultS);
const plans = [];
for (let k = 0, s0 = 0; k < nRings; k++) {
const m = Math.floor(n / nRings) + (k < n % nRings ? 1 : 0), chain = st.slice(s0, s0 + m); s0 += m;
const ends = ['board', ...chain, ...(ring ? ['board'] : [])], hops = [];
for (let h = 0; h + 1 < ends.length; h++) {
const parts = path(ends[h], ends[h + 1]).filter(q => Math.abs(q.b - q.a) > 1e-9);
hops.push({ from: ends[h] === 'board' ? 'board' : ends[h].id, to: ends[h + 1] === 'board' ? 'board' : ends[h + 1].id, parts,
lengthM: parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0) });
}
plans.push({ chain, hops, m });
}
// Shared-trench heating: a hop is rated with the group factor of the most circuits it shares a line with.
const onLine = new Map();
for (const { hops } of plans) for (const h of hops) for (const key of new Set(h.parts.map(q => q.key))) onLine.set(key, (onLine.get(key) || 0) + 1);
const groupOf = h => groupFactor(Math.max(1, ...h.parts.map(q => onLine.get(q.key) || 1)));
plans.forEach(({ chain, hops, m }, k) => {
const load = chain.reduce((t, s) => t + s.mva, 0);
const size = (mva, h) => (sizeFor(mva / p.maxUtilisation, { ...opt, minArea, groupFactor: groupOf(h) }) || { area: SIZES.at(-1) });
if (!ring) { // radial: each segment sized from the load it carries
hops.forEach((h, i) => { h.loadMVA = chain.slice(i).reduce((u, s) => u + s.mva, 0); h.areaMm2 = size(h.loadMVA, h).area; h.group = groupOf(h); });
const drop = () => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opt), 0);
for (let guard = 0; drop() > p.vdropLimitPct && guard < 60; guard++) {
const can = hops.filter(h => h.areaMm2 < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
if (!can) break;
can.areaMm2 = SIZES[SIZES.indexOf(can.areaMm2) + 1];
}
rings.push({ id: `F${k + 1}`, topology: 'radial', stations: chain.map(s => s.id), hops, open: -1, openAt: null, loadMVA: load,
areaMm2: Math.max(...hops.map(h => h.areaMm2)), carries: null, dropPct: drop(), outageDropPct: null });
return;
}
const open = Math.ceil(m / 2); // the hop left open: the middle of the ring
const pick = size(load, hops.reduce((a, b) => (groupOf(b) < groupOf(a) ? b : a)));
let area = pick.area;
// Normal running: stations before the open hop from leg A, the rest from leg B (each half radial).
const dropWith = a => {
const side = (hs, sts) => hs.reduce((t, h, i) => t + dropPercent(a, h.lengthM, sts.slice(i).reduce((u, s) => u + s.mva, 0), opt), 0);
const A = side(hops.slice(0, open), chain.slice(0, open)), B = side(hops.slice(open + 1).reverse(), chain.slice(open).reverse());
const outage = side(hops.slice(0, m), chain); // leg B out: the whole ring from leg A
return { normal: Math.max(A, B), outage };
};
while (dropWith(area).normal > p.vdropLimitPct && area < SIZES.at(-1)) area = SIZES[SIZES.indexOf(area) + 1];
const d = dropWith(area);
for (const h of hops) { h.areaMm2 = area; h.group = groupOf(h); }
rings.push({ id: `F${k + 1}`, topology: 'ring', stations: chain.map(s => s.id), hops, open, openAt: hops[open].to === 'board' ? hops[open].from : hops[open].to,
loadMVA: load, areaMm2: area, carries: pick.amps ?? null, dropPct: d.normal, outageDropPct: d.outage });
});
// Board sections: at most 6 ways each, one per grid transformer at least; the two ends of a ring on different sections.
const exportMW = n * stationMVA * p.powerFactor;
const grid = gridChoice(exportMW, exportMW * p.gridFactor, null, rings.map(r => ({ loadMVA: r.loadMVA })));
const sections = Math.max(1, grid.units, Math.ceil(2 * rings.length / p.feedersPerBoardMax));
rings.forEach((r, k) => { r.boardA = `MVB${(k % sections) + 1}`; r.boardB = r.topology === 'ring' ? `MVB${((k + (sections > 1 ? 1 : 0)) % sections) + 1}` : r.boardA; });
// Circuits: each hop is one three-core circuit; lanes on each line in the order circuits first use it.
const lanes = new Map(), laneOf = (key, id) => { if (!lanes.has(key)) lanes.set(key, []); const l = lanes.get(key); if (!l.includes(id)) l.push(id); return l.indexOf(id); };
const circuits = rings.flatMap(r => r.hops.map((h, i) => ({ id: `${r.id}-${i + 1}`, ring: r.id, from: h.from, to: h.to, parts: h.parts,
lengthM: h.lengthM, areaMm2: h.areaMm2, normallyOpen: i === r.open })));
for (const cc of circuits) for (const q of cc.parts) q.lane = laneOf(q.key, cc.id);
const lineOf = key => (key === 's' ? { along: 'x', at: L.spineY } : key[0] === 'c' ? { along: 'y', at: colX(Number(key.slice(1))) }
: { along: 'x', at: st[Number(key.slice(1))].rmu[1] });
const off = (key, lane) => (lane - ((lanes.get(key).length - 1) / 2)) * L.laneM;
const xy = (key, v, lane) => { const g = lineOf(key), o = off(key, lane); return g.along === 'x' ? [v, g.at + o] : [g.at + o, v]; };
for (const cc of circuits) cc.plan = cc.parts.flatMap(q => [xy(q.key, q.a, q.lane), xy(q.key, q.b, q.lane)])
.filter((pt, i, a) => !i || Math.hypot(pt[0] - a[i - 1][0], pt[1] - a[i - 1][1]) > 1e-6);
const trenches = [];
for (const key of lanes.keys()) {
const list = circuits.flatMap(cc => cc.parts.filter(q => q.key === key).map(q => ({ a: Math.min(q.a, q.b), b: Math.max(q.a, q.b), lane: q.lane })));
for (const s of coverage(list)) {
const inside = list.filter(q => q.a < s.b - 1e-9 && q.b > s.a + 1e-9).map(q => off(key, q.lane));
const lo = Math.min(...inside), hi = Math.max(...inside), w = hi - lo + L.laneM, mid = (lo + hi) / 2, g = lineOf(key);
const plan = g.along === 'x' ? [[s.a, g.at + mid], [s.b, g.at + mid]] : [[g.at + mid, s.a], [g.at + mid, s.b]];
trenches.push({ key, circuits: s.c, width: Math.max(0.45, w), plan, lengthM: s.b - s.a });
}
}
const trenchM = trenches.reduce((t, x) => t + x.lengthM, 0);
const cableM = circuits.reduce((t, cc) => t + 3 * (cc.lengthM * 1.03 + 10), 0);
return { stations: st, rows, cols, rings, circuits, trenches, trenchM, cableM, compound: c, board, sections,
grid: { units: grid.units, mva: grid.mva, smallest: grid.smallest, at: Array.from({ length: grid.units }, (_, g) => [gt0[0] + g * 16, gt0[1]]) },
poc: { kv: pocKv, at: poc }, exportMW, perRing: per, minAreaMm2: minArea,
note: 'Illustrative, not a design for any site: ring sizes from generic rating rules, routes along assumed tracks.' };
}Bng
A JavaScript module in the engine folder of GlobalGrid2050 that converts to cartesian (`toCartesian`), parses grid ref (`parseGridRef`) and calculates planar distances and angles, using Helmert and OSTN15.
Set aside from the main view: 99% of its lines are the same as prototype/world/bng.mjs (energy-transition-simulator), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Bng; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9882 to energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/world/bng.mjs:1-212 b7164628503b1e80df26257dc62ecebfa77a4d34
- sha256 d0a0954b54f81591ead2441675988e273b22708b3bceb262b8695256887d2383
- target sha256 999f8363ee1d9c06b6169c0f59803d9a2ac5e2701becd596e29d74550e06971f
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesyglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/bng.mjs · lines 1–214 of 214 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern fromCartesian (shared by 3 files)
- What it does
- It calculates its inputs. Defines 14 functions or classes, including invert3, apply, toCartesian, fromCartesian, meridional.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 1 file: Journey (globalgrid2050).
- What it achieves
- It parses grid ref (`parseGridRef`) and is built from the invert3 step (`invert3`) and the apply step (`apply`). `bngToWgs84` mirrors `osgb36_to_wgs84` in GlobalGrid2050 `uk_renewables_pipeline/v9.7/scripts/data/build_v7_2_spine.py` term for term (one deliberate difference: the meridian-arc loop, see `tmInverse`).
- Why it matters
- Imported by Journey.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- none found
- Used by
- imported by Journey (import)
- Produces
- tmForward, tmInverse, bngToWgs84, wgs84ToBng, parseGridRef, gridRef
- Defines here
- invert3, apply, toCartesian, fromCartesian, meridional, tmForward, tmInverse, offset, bngToWgs84, wgs84ToBng, parseGridRef, pad, gridRef, fmt
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/bng.mjs:1-214 · blob 7916204d5e4e0a6a6813fe63edc026b42d74ee75 · 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: duplicate_candidate
// COPIED UNCHANGED from world/v12 bng.mjs at v12 commit 3adcee9 (file last changed 04b1c72). Modular star family: public #144675 tmForward.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// British National Grid <-> WGS84, pure functions, no imports, no DOM.
//
// WHAT THIS IS
// bngToWgs84 mirrors osgb36_to_wgs84() in globalgrid2050
// uk_renewables_pipeline/v9.7/scripts/data/build_v7_2_spine.py term for term (one
// deliberate difference: the meridian-arc loop, see tmInverse):
// Transverse Mercator inverse on Airy 1830 with the OS National Grid constants
// (F0 0.9996012717, true origin 49N 2W, false origin E 400000 N -100000), then a
// 7-parameter Helmert OSGB36 -> WGS84 with heights taken as zero on Airy.
// wgs84ToBng is its exact algebraic inverse: the Helmert matrix inverted (not the
// usual sign-flipped approximation, which is out by about 1 cm) and the WGS84 height
// chosen so the Airy height is zero, then the TM forward series, then one fixed-point
// step against tmInverse (the OS forward and inverse series are truncations and part
// by up to 2 mm 400 km from the central meridian). So a round trip through both
// functions closes to well under a millimetre anywhere on the grid.
//
// HOW ACCURATE IT IS, AND IS NOT
// Closing a round trip proves consistency, not truth. The Helmert transformation is
// accurate to about 3.5 m against the real National Grid (Ordnance Survey, "A guide to
// coordinate systems in Great Britain", section 6.6; the OS says 3-5 m and does not
// recommend it where better is needed). The definitive transformation is OSTN15, a
// grid of offsets not held here. Where a site has a known OSTN15 offset it can be
// passed as { de, dn } in metres: wgs84ToBng adds it to the result and bngToWgs84
// removes it before converting, so the pair stays inverses of each other.
//
// Sources: Ordnance Survey, "A guide to coordinate systems in Great Britain" (v3.6),
// Annex B (Helmert), Annex C (Transverse Mercator), Annex C.1 worked example.
const AIRY_A = 6377563.396, AIRY_B = 6356256.909;
const WGS_A = 6378137.0, WGS_B = 6356752.3141;
const F0 = 0.9996012717;
const LAT0 = 49 * Math.PI / 180, LON0 = -2 * Math.PI / 180;
const E0 = 400000, N0 = -100000;
const AIRY_E2 = 1 - (AIRY_B * AIRY_B) / (AIRY_A * AIRY_A);
const WGS_E2 = 1 - (WGS_B * WGS_B) / (WGS_A * WGS_A);
const N_ = (AIRY_A - AIRY_B) / (AIRY_A + AIRY_B);
const RAD = Math.PI / 180, SEC = RAD / 3600;
// OSGB36 -> WGS84, exactly as the Python: x2 = t + M x1
const T = [446.448, -125.157, 542.060];
const RX = 0.1502 * SEC, RY = 0.2470 * SEC, RZ = 0.8421 * SEC;
const S = 1 - 20.4894e-6;
const M = [[S, -RZ, RY], [RZ, S, -RX], [-RY, RX, S]];
function invert3(m) {
const [[a, b, c], [d, e, f], [g, h, i]] = m;
const A = e * i - f * h, B = -(d * i - f * g), C = d * h - e * g;
const det = a * A + b * B + c * C;
return [
[A / det, -(b * i - c * h) / det, (b * f - c * e) / det],
[B / det, (a * i - c * g) / det, -(a * f - c * d) / det],
[C / det, -(a * h - b * g) / det, (a * e - b * d) / det],
];
}
const MI = invert3(M);
const apply = (m, v) => [
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
];
function toCartesian(lat, lon, h, a, e2) {
const s = Math.sin(lat), c = Math.cos(lat);
const nu = a / Math.sqrt(1 - e2 * s * s);
return [(nu + h) * c * Math.cos(lon), (nu + h) * c * Math.sin(lon), (nu * (1 - e2) + h) * s];
}
// Cartesian -> geodetic, the same fixed-point iteration as the Python (12 steps max).
function fromCartesian(x, y, z, a, e2) {
const p = Math.hypot(x, y);
let lat = Math.atan2(z, p * (1 - e2));
for (let k = 0; k < 12; k++) {
const nu = a / Math.sqrt(1 - e2 * Math.sin(lat) ** 2);
const next = Math.atan2(z + e2 * nu * Math.sin(lat), p);
const done = Math.abs(next - lat) < 1e-12;
lat = next;
if (done) break;
}
const nu = a / Math.sqrt(1 - e2 * Math.sin(lat) ** 2);
const h = Math.abs(Math.cos(lat)) > 1e-9 ? p / Math.cos(lat) - nu : Math.abs(z) - nu * (1 - e2);
return { lat, lon: Math.atan2(y, x), h };
}
function meridional(lat) {
const n = N_, dl = lat - LAT0, sl = lat + LAT0;
const ma = (1 + n + 5 / 4 * n ** 2 + 5 / 4 * n ** 3) * dl;
const mb = (3 * n + 3 * n ** 2 + 21 / 8 * n ** 3) * Math.sin(dl) * Math.cos(sl);
const mc = (15 / 8 * n ** 2 + 15 / 8 * n ** 3) * Math.sin(2 * dl) * Math.cos(2 * sl);
const md = 35 / 24 * n ** 3 * Math.sin(3 * dl) * Math.cos(3 * sl);
return AIRY_B * F0 * (ma - mb + mc - md);
}
/** OSGB36 latitude/longitude (radians, Airy 1830) -> National Grid { e, n }. OS Annex C. */
export function tmForward(lat, lon) {
const s = Math.sin(lat), c = Math.cos(lat), t = Math.tan(lat);
const nu = AIRY_A * F0 / Math.sqrt(1 - AIRY_E2 * s * s);
const rho = AIRY_A * F0 * (1 - AIRY_E2) / (1 - AIRY_E2 * s * s) ** 1.5;
const eta2 = nu / rho - 1;
const I = meridional(lat) + N0;
const II = nu / 2 * s * c;
const III = nu / 24 * s * c ** 3 * (5 - t ** 2 + 9 * eta2);
const IIIA = nu / 720 * s * c ** 5 * (61 - 58 * t ** 2 + t ** 4);
const IV = nu * c;
const V = nu / 6 * c ** 3 * (nu / rho - t ** 2);
const VI = nu / 120 * c ** 5 * (5 - 18 * t ** 2 + t ** 4 + 14 * eta2 - 58 * t ** 2 * eta2);
const dl = lon - LON0;
return {
e: E0 + IV * dl + V * dl ** 3 + VI * dl ** 5,
n: I + II * dl ** 2 + III * dl ** 4 + IIIA * dl ** 6,
};
}
/** National Grid (e, n) -> OSGB36 { lat, lon } in radians on Airy 1830. Mirrors the Python. */
export function tmInverse(easting, northing) {
let lat = LAT0, m = 0;
// OS Annex C.6 repeats while |N - N0 - M| >= 0.01 mm. The Python tests the signed value,
// so north of about 55N, where a step overshoots, it stops early: 3-11 cm out in Scotland
// and up to 46 m north of N 1,210,000. Here the absolute value, as the OS writes it.
for (let k = 0; k < 100 && Math.abs(northing - N0 - m) >= 0.00001; k++) {
lat += (northing - N0 - m) / (AIRY_A * F0);
m = meridional(lat);
}
const s = Math.sin(lat), c = Math.cos(lat), t = Math.tan(lat);
const nu = AIRY_A * F0 / Math.sqrt(1 - AIRY_E2 * s * s);
const rho = AIRY_A * F0 * (1 - AIRY_E2) / (1 - AIRY_E2 * s * s) ** 1.5;
const eta2 = nu / rho - 1;
const de = easting - E0;
const VII = t / (2 * rho * nu);
const VIII = t / (24 * rho * nu ** 3) * (5 + 3 * t ** 2 + eta2 - 9 * t ** 2 * eta2);
const IX = t / (720 * rho * nu ** 5) * (61 + 90 * t ** 2 + 45 * t ** 4);
const X = 1 / (c * nu);
const XI = 1 / (c * 6 * nu ** 3) * (nu / rho + 2 * t ** 2);
const XII = 1 / (c * 120 * nu ** 5) * (5 + 28 * t ** 2 + 24 * t ** 4);
const XIIA = 1 / (c * 5040 * nu ** 7) * (61 + 662 * t ** 2 + 1320 * t ** 4 + 720 * t ** 6);
return {
lat: lat - VII * de ** 2 + VIII * de ** 4 - IX * de ** 6,
lon: LON0 + X * de - XI * de ** 3 + XII * de ** 5 - XIIA * de ** 7,
};
}
const offset = (o) => ({ de: (o && Number.isFinite(o.de)) ? o.de : 0, dn: (o && Number.isFinite(o.dn)) ? o.dn : 0 });
/** National Grid easting/northing (m) -> WGS84 { lat, lon } in degrees. */
export function bngToWgs84(e, n, ostn) {
const { de, dn } = offset(ostn);
const g = tmInverse(e - de, n - dn);
const p = toCartesian(g.lat, g.lon, 0, AIRY_A, AIRY_E2);
const q = apply(M, p);
const w = fromCartesian(q[0] + T[0], q[1] + T[1], q[2] + T[2], WGS_A, WGS_E2);
return { lat: w.lat / RAD, lon: w.lon / RAD };
}
/** WGS84 { lat, lon } in degrees -> National Grid { e, n } in metres. Exact inverse of bngToWgs84. */
export function wgs84ToBng(lat, lon, ostn) {
const { de, dn } = offset(ostn);
const la = lat * RAD, lo = lon * RAD;
let h = 0, g = null;
// bngToWgs84 puts the point at height zero on Airy; find the WGS84 height that does too.
for (let k = 0; k < 4; k++) {
const w = toCartesian(la, lo, h, WGS_A, WGS_E2);
const p = apply(MI, [w[0] - T[0], w[1] - T[1], w[2] - T[2]]);
g = fromCartesian(p[0], p[1], p[2], AIRY_A, AIRY_E2);
if (Math.abs(g.h) < 1e-6) break;
h -= g.h;
}
const r0 = tmForward(g.lat, g.lon);
let r = r0;
for (let k = 0; k < 3; k++) { // make it the inverse of tmInverse, not just the OS series
const back = tmInverse(r.e, r.n), b = tmForward(back.lat, back.lon);
r = { e: r.e + (r0.e - b.e), n: r.n + (r0.n - b.n) };
}
return { e: r.e + de, n: r.n + dn };
}
// ---- grid references: two letters for the 100 km square, then digits ----
const LETTERS = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'; // 25 letters, no I
/** 'TQ 30 80' / 'TQ3080' / 'tq 3000 8000' -> { e, n } of the square's south-west corner. */
export function parseGridRef(ref) {
const s = String(ref ?? '').toUpperCase().replace(/[\s,]+/g, ' ').trim();
const m = /^([A-HJ-Z])([A-HJ-Z])\s*(\d*)\s*(\d*)$/.exec(s);
if (!m) throw new Error(`not a grid reference: ${ref}`);
const l1 = LETTERS.indexOf(m[1]), l2 = LETTERS.indexOf(m[2]);
const e100 = ((l1 - 2) % 5) * 5 + (l2 % 5);
const n100 = (19 - Math.floor(l1 / 5) * 5) - Math.floor(l2 / 5);
let de = m[3], dn = m[4];
if (!dn) { // run together: split in half
if (de.length % 2) throw new Error(`odd number of digits: ${ref}`);
dn = de.slice(de.length / 2); de = de.slice(0, de.length / 2);
}
if (de.length !== dn.length || de.length > 5) throw new Error(`unbalanced digits: ${ref}`);
const pad = (d) => (d ? Number((d + '00000').slice(0, 5)) : 0);
const e = e100 * 100000 + pad(de), n = n100 * 100000 + pad(dn);
if (e100 < 0 || e100 > 6 || n100 < 0 || n100 > 12) throw new Error(`square outside the grid: ${ref}`);
return { e, n };
}
/** { e, n } -> 'TQ 30 80' with `digits` digits in all (0, 2, 4, ... 10). Truncates, as the OS does. */
export function gridRef(e, n, digits = 10) {
if (!(digits >= 0 && digits <= 10 && digits % 2 === 0)) throw new Error(`digits must be 0..10 and even: ${digits}`);
if (!(e >= 0 && e < 700000 && n >= 0 && n < 1300000)) throw new Error(`outside the grid: ${e}, ${n}`);
const e100 = Math.floor(e / 100000), n100 = Math.floor(n / 100000);
const l1 = (19 - n100) - ((19 - n100) % 5) + Math.floor((e100 + 10) / 5);
const l2 = ((19 - n100) * 5) % 25 + (e100 % 5);
const sq = LETTERS[l1] + LETTERS[l2];
if (digits === 0) return sq;
const k = digits / 2, div = 10 ** (5 - k);
const fmt = (v) => String(Math.floor((v % 100000) / div)).padStart(k, '0');
return `${sq} ${fmt(e)} ${fmt(n)}`;
}Bs7671 Checks
A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, using BS 7671.
Set aside from the main view: 94% of its lines are the same as solar-design-studio/202609271853-site-world/world/bs7671-checks.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Bs7671 Checks; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9394 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/bs7671-checks.mjs:1-39 14883fb8cb01c646cfbdbc8703e73db195aa9c2c
- sha256 df50e2256dccb77338764f70a9809188c9eefc39ca9ec63e059bcf182121a856
- target sha256 5972d408caa0b02b50953e8e97046ada7333b5f4fc721a7a890a4cf12d5959b0
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/bs7671-checks.mjs · lines 1–41 of 41 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern buriedProtection (shared by 3 files)
- What it does
- It calculates cables. Defines buriedOverload, buriedProtection, disconnection.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: cables.
- Downstream impact
- Used directly by 1 file: LV DC Sizing (globalgrid2050).
- What it achieves
- It is built from the buried overload helper (`buriedOverload`), the buried protection helper (`buriedProtection`) and the disconnection step (`disconnection`). Checks on the LV cable engines from a cross-check against the national wiring rules.
- Why it matters
- Imported by LV DC Sizing.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- none found
- Used by
- imported by LV DC Sizing (import)
- Produces
- SOIL_SENSITIVITY, BURIED, buriedOverload, buriedProtection, DISCONNECT_S, disconnection
- Defines here
- buriedOverload, buriedProtection, disconnection
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/bs7671-checks.mjs:1-41 · blob 719fa6bf41270243a9c8ca55b415c32d29be193c · 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: duplicate_candidate
// COPIED UNCHANGED from world/v12 bs7671-checks.mjs at v12 commit 3adcee9 (file last changed 9b1ffad). Modular star family: not known to star-find.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// bs7671-checks.mjs: checks on the LV cable engines from a cross-check against the national wiring rules. Clauses are
// cited by number only; no table, figure or wording of the rules is held here. Every value below is ours, an input,
// and editable. Illustrative, early design, no warranty: confirm with a qualified engineer.
// ---- overload of buried cables (BS 7671 433.1.203) ----
// The general condition (433.1.1) is kept; for a cable in the ground the check is also made with the soil thermal
// resistivity raised by this factor (our sensitivity margin, not a figure from the rules), because a buried cable's
// rating falls as the ground dries. The verdict at the stated soil and at the raised soil are both reported.
export const SOIL_SENSITIVITY = 1.25;
export const BURIED = new Set(['buried', 'ducts', 'direct', 'duct']);
/** buriedOverload({ In, izAt(soilKmW), soilKmW, factor }) -> { name, ok, value, limit, soilKmW } (value In, limit Iz there). */
export function buriedOverload({ In, izAt, soilKmW, factor = SOIL_SENSITIVITY }) {
const soil = soilKmW * factor, Iz = izAt(soil);
return { name: `buried cable: In <= Iz at soil +${Math.round((factor - 1) * 100)} % (BS 7671 433.1.203)`, ok: In <= Iz + 1e-9,
value: In, limit: Iz, soilKmW: soil };
}
// ---- protection of buried LV and DC cable (BS 7671 522.8.10) ----
/** buriedProtection({ armoured, ducted, kind }) -> a check: a cable in the ground needs an earthed armour or metal sheath,
* or a duct giving like protection. Unarmoured cable laid direct fails. */
export function buriedProtection({ armoured = false, ducted = false, kind = 'LV' } = {}) {
const ok = !!armoured || !!ducted;
return { name: `${kind} cable in the ground: armoured and earthed, or in a duct (BS 7671 522.8.10)`, ok,
value: armoured ? 'armoured' : ducted ? 'ducted' : 'unarmoured, laid direct', limit: 'armour or duct' };
}
// ---- disconnection time by circuit type (BS 7671 411.3.2) ----
// Distribution circuits (411.3.2.3) are allowed longer than small final circuits (411.3.2.2). The times are inputs:
// the distribution time follows 411.3.2.3; the final-circuit time is an input to set from 411.3.2.2 for the circuit.
export const DISCONNECT_S = Object.freeze({ distribution: 5, final: 0.4 });
/** disconnection(p) -> { circuit, permittedS, ia, fastIa }: Ia is the device's current at the permitted time (from its curve,
* as a multiple of In: p.iaMultipleAtPermitted, assumed); fastIa is its instantaneous pick-up (p.tripMultiple). */
export function disconnection(p) {
const circuit = p.circuit === 'final' ? 'final' : 'distribution', permittedS = p.permittedS ?? DISCONNECT_S[circuit];
const mult = circuit === 'final' ? p.tripMultiple : (p.iaMultipleAtPermitted ?? p.tripMultiple);
return { circuit, permittedS, ia: p.inA * mult, fastIa: p.inA * p.tripMultiple };
}