GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / energy-transition-simulator/202609280014/mod/engine

Substations and 5 more files

A JavaScript file in GlobalGrid2050 that draws grid substations and substations footprints odbl, and uses data from the GridAtlas repository. It labels block (`labelBlock`) and syncs btn (`syncBtn`).

652 lines of JavaScript and YAML from globalgrid2050, in 6 files. Topic: Grid network and substations. Section 326 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. MV Network ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/mv-network.mjs lines 1–127
  2. Plant Feeders transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/plant-feeders.mjs lines 1–142
  3. Single-Line Diagram (SLD) Connect electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/sld-connect.mjs lines 1–57
  4. Single-Line Diagram (SLD) Rules electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/sld-rules.mjs lines 1–95
  5. Substations interaction · globalgrid2050 / energy-transition-simulator/202609280014/mod/substations.js lines 1–189
  6. Manifest docs-config · globalgrid2050 / feature_requests/005_extract_v2_substation_data/manifest.yml lines 1–42

MV Network

A JavaScript module in the engine folder of GlobalGrid2050 that reads routes (`readRoutes`) (units: kV, MVA), covering cables and transformers. It reads routes (`readRoutes`) and places network (`placeNetwork`).

ingestglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/mv-network.mjs · lines 1–127 of 127 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern drawingToGround (shared by 3 files)

What it does
Defines 9 functions or classes, including equipmentSolids, box, solidLines, readRoutes, pt.
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: cables, transformers.
Downstream impact
Used directly by 1 file: Block Build (globalgrid2050).
What it achieves
The medium-voltage network from the stations to the grid, as equipment outlines with solids and cable routes, placed on the ground by the user.
Why it matters
Imported by Block Build.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Station (import), Plant Template (import)
Used by
imported by Block Build (import)
Produces
ROUTES_SCHEMA, EQUIPMENT, equipmentSolids, solidLines, readRoutes, drawingToGround, placeNetwork, cableLines
Defines here
equipmentSolids, box, solidLines, readRoutes, pt, drawingToGround, placeNetwork, kindOf, cableLines
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/mv-network.mjs:1-127 · blob e9f525f9bb51d517a255234dec1d9233f900b117 · 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 mv-network.mjs at v12 commit 3adcee9 (file last changed 2c38e15). Modular star family: public #146440 equipmentSolids.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// mv-network.mjs: the medium-voltage network from the stations to the grid, as equipment outlines with solids
// and cable routes, placed on the ground by the user.
//
// Input is a block diagram (plant-template.mjs: nodes and links) and, optionally, a route file in DRAWING
// coordinates (schema mv-routes.v1: node positions and cable polylines in the units of some drawing). This module
// never knows where a real site is: the user places the drawing with a transform (a point on the ground, metres
// per drawing unit, a rotation). Without a route file the diagram is laid out on a plain grid instead.
//
// Equipment sizes are generic and rounded (ring main unit, station skid, switchroom, grid transformer in its bund,
// cable sealing-end structure at the connection); they are outlines for scale, not any maker's product.
// Pure: no DOM. Imports only the placement helper.

import { placer } from './station.mjs';
import { layoutDiagram } from './plant-template.mjs';

export const ROUTES_SCHEMA = 'mv-routes.v1';

// Footprint w (across) x d (along) and height h, metres.
export const EQUIPMENT = Object.freeze({
  rmu: { w: 1.6, d: 0.9, h: 1.8, label: 'ring main unit' },
  station: { w: 6.1, d: 2.5, h: 2.9, label: 'station skid: transformer, LV and MV switchgear' },
  switchboard: { w: 20, d: 8, h: 4.5, label: 'MV switchroom' },
  'grid-transformer': { w: 10, d: 6, h: 7, label: 'grid transformer', bund: { w: 16, d: 12, h: 0.6 } },
  poc: { w: 4, d: 4, h: 9, label: 'connection structure (cable sealing ends)' }
});

/** Solids for one item: the body, plus a bund wall ring where the kind has one. */
export function equipmentSolids(kind, at = [0, 0, 0], heading = 0, id = kind) {
  const e = EQUIPMENT[kind];
  if (!e) throw new Error(`mv-network: unknown equipment kind ${kind}`);
  const P = placer(at, heading), out = [];
  const box = (part, min, max) => out.push(P.box({ kind, part, id, min, max }));
  box('body', [-e.w / 2, -e.d / 2, 0], [e.w / 2, e.d / 2, e.h]);
  if (e.bund) {                                        // four low walls round the transformer, 0.25 m thick
    const { w, d, h } = e.bund, t = 0.25, x = w / 2, y = d / 2;
    box('bund', [-x, -y, 0], [x, -y + t, h]); box('bund', [-x, y - t, 0], [x, y, h]);
    box('bund', [-x, -y, 0], [-x + t, y, h]); box('bund', [x - t, -y, 0], [x, y, h]);
  }
  return out;
}

/** Edge lines (x, y, z pairs) of placed solids: the rotated footprint at the base and the top, and the uprights. */
export function solidLines(solids) {
  const v = [];
  for (const s of solids) {
    const q = s.quad, z0 = s.min[2], z1 = s.max[2];
    for (let i = 0; i < 4; i++) {
      const a = q[i], b = q[(i + 1) % 4];
      v.push(a[0], a[1], z0, b[0], b[1], z0, a[0], a[1], z1, b[0], b[1], z1, a[0], a[1], z0, a[0], a[1], z1);
    }
  }
  return new Float32Array(v);
}

/** Validate a route file. Returns { units, nodes: Map(id -> [x, y]), links: [{ from, to, points }] } or throws. */
export function readRoutes(json) {
  if (!json || json.schema !== ROUTES_SCHEMA) throw new Error(`mv-network: route file schema must be "${ROUTES_SCHEMA}"`);
  const pt = p => Array.isArray(p) && p.length >= 2 && p.every(Number.isFinite);
  const nodes = new Map();
  for (const [id, p] of Object.entries(json.nodes || {})) { if (!pt(p)) throw new Error(`mv-network: node ${id} needs [x, y]`); nodes.set(id, [p[0], p[1]]); }
  const links = (json.links || []).map((l, i) => {
    if (!l || typeof l.from !== 'string' || typeof l.to !== 'string') throw new Error(`mv-network: link ${i + 1} needs from and to`);
    const points = l.points || [];
    if (!points.every(pt)) throw new Error(`mv-network: link ${i + 1} has a bad point`);
    return { from: l.from, to: l.to, points: points.map(p => [p[0], p[1]]) };
  });
  return { units: String(json.units || 'drawing'), yDown: json.y_down === true, nodes, links };
}

/**
 * drawingToGround({ at, metresPerUnit, heading, yDown }) -> (x, y) -> [east, north] local metres.
 * The drawing's first axis runs along the heading's right-hand side; y down (as in PDF sheets) is flipped.
 */
export function drawingToGround({ at = [0, 0], metresPerUnit = 1, heading = 0, yDown = false } = {}) {
  const c = Math.cos(heading), s = Math.sin(heading);
  return (x, y) => {
    const u = x * metresPerUnit, v = (yDown ? -y : y) * metresPerUnit;
    return [at[0] + u * c + v * s, at[1] - u * s + v * c];
  };
}

/**
 * placeNetwork(diagram, { routes, at, heading, metresPerUnit, spacing, groundAt })
 * -> { equipment: [{ id, kind, label, solids }], cables: [{ from, to, kv, mva, normallyOpen, points: [[x, y, z]] }], missing }
 * With routes: node positions and polylines from the file. Without: layoutDiagram on a `spacing` metre grid.
 */
export function placeNetwork(diagram, { routes = null, at = [0, 0], heading = 0, metresPerUnit = 1, spacing = 40, groundAt = () => 0 } = {}) {
  const map = routes
    ? drawingToGround({ at, metresPerUnit, heading, yDown: routes.yDown })
    : drawingToGround({ at, metresPerUnit: spacing, heading, yDown: true });
  const where = new Map(), missing = [];
  if (routes) for (const [id, p] of routes.nodes) where.set(id, map(p[0], p[1]));
  else for (const n of layoutDiagram(diagram)) where.set(n.id, map(n.x, n.y));
  const kindOf = n => (n.kind in EQUIPMENT ? n.kind : null);
  const equipment = [];
  for (const n of diagram.nodes) {
    const k = kindOf(n), p = where.get(n.id);
    if (!k) continue;
    if (!p) { missing.push(n.id); continue; }
    equipment.push({ id: n.id, kind: k, label: n.label, solids: equipmentSolids(k, [p[0], p[1], groundAt(p[0], p[1])], heading, n.id) });
  }
  const drawn = new Map();
  if (routes) for (const l of routes.links) drawn.set(`${l.from}>${l.to}`, l.points);
  const cables = [];
  for (const l of diagram.links) {
    const a = where.get(l.from), b = where.get(l.to);
    if (!a || !b) continue;
    const path = drawn.get(`${l.from}>${l.to}`) || [...(drawn.get(`${l.to}>${l.from}`) || [])].reverse();
    const plan = path.length ? path.map(p => map(p[0], p[1])) : [a, b];
    const depth = l.kv >= 100 ? 1.2 : 0.9;
    cables.push({ from: l.from, to: l.to, kind: l.kind, kv: l.kv, mva: l.mva, normallyOpen: !!l.normallyOpen,
      points: plan.map(([x, y]) => [x, y, groundAt(x, y) - (l.kind === 'mv-bus' || l.kind === 'station-tee' ? 0 : depth)]) });
  }
  return { equipment, cables, missing };
}

/** Line pairs for the cables of a placed network (optionally only one kind). */
export function cableLines(cables, kind = null) {
  const v = [];
  for (const c of cables) {
    if (kind && c.kind !== kind) continue;
    for (let i = 1; i < c.points.length; i++) v.push(...c.points[i - 1], ...c.points[i]);
  }
  return new Float32Array(v);
}

Plant Feeders

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, 33kV and A roads, using IEC 60287.

Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609271740-site-world/world/plant-feeders.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Plant Feeders; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9826 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/plant-feeders.mjs:1-140 41af101dc03f6e5bf650be8182a15e0a326dd9a2
  • sha256 aca831258c997e5fe0362dcf4ec5bf47a3e9d7f6b35dc04cc505112d3aa1af43
  • target sha256 59e090e3caac223ce64f9879162cf7dce312fb3ea05eea32390e7951c1fcdbd0
  • 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/plant-feeders.mjs · lines 1–142 of 142 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern routeFeeders (shared by 4 files)

What it does
It calculates cables, 33kV and A roads. Defines 11 functions or classes, including toSpine, roadPath, side, coverage, trenchFor.
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, 33kV, A roads.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 3 files: Block MV (globalgrid2050); Cmd Model (globalgrid2050); Plant Layout (globalgrid2050).
What it achieves
It routes feeders (`routeFeeders`) and is built from the to spine helper (`toSpine`) and the road path helper (`roadPath`). The 33kV feeders of a laid-out plant, routed along its roads, with their trenches and cables. Its code works with 33 kV.
Why it matters
Imported by Block MV, Cmd Model and Plant Layout.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Cable Rating (import), Trench Plan (import)
Used by
imported by Block MV (import), imported by Cmd Model (import), imported by Plant Layout (import)
Produces
SECTION_FOR, CABLE_ALLOW, roadPath, coverage, trenchFor, routeFeeders, SECTION_WORDS, trenchRows
Defines here
toSpine, roadPath, side, coverage, trenchFor, routeFeeders, onRoad, add, dropOf, trenchRows, k
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/plant-feeders.mjs:1-142 · blob f4a39e62d67281f7ebf64d6055bed8c0a68fa393 · 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 plant-feeders.mjs at v12 commit 3adcee9 (file last changed 604729d). Modular star family: public #146457 roadPath.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// plant-feeders.mjs: the 33 kV feeders of a laid-out plant, routed along its roads, with their trenches and cables.
//
// Each feeder of the plant template runs from its board in the substation compound along the access road, the
// spine and the branch tracks to its first station, then station to station. Routes stay on the road network
// (a comb: one spine, tracks off it), so every route is a set of intervals on a few straight lines. Where several
// circuits share a stretch they share a trench: one circuit in a single trefoil trench, two in a two-circuit
// trench, more in parallel trenches. Where a circuit turns across a road it goes in ducts.
// Cable lengths: route plus 3 % for snaking and 5 m at each end for terminations, three single cores a circuit.
// Voltage drop is worked out on the routed lengths (cable-rating.mjs), replacing the template's placeholder lengths;
// where it passes the limit, the segment that saves most drop per step is upsized, as the template does.
// Trench section ids are those of data/trench-sections.json: farmland cover (0.91 m) for the runs, ducts at crossings.
// The busiest hop's cable is checked by rating (trench-plan.mjs) alone and two circuits side by side as the section
// draws them. Pure: imports only the rating cartridges.

import { dropPercent, SIZES, build } from './cable-rating.mjs';
import { checkAsDrawn } from './trench-plan.mjs';

export const SECTION_FOR = Object.freeze({ one: '33kv-1-agri', two: '33kv-2-agri', crossing: '33kv-1-ducted' });
export const CABLE_ALLOW = Object.freeze({ slack: 0.03, tailM: 5, cores: 3 });

// A point on the road network: on a track (k, u), on the access road (u), or on the spine (v).
function toSpine(pt, net) {
  if (pt.line === 'track') return { parts: [{ key: 't' + pt.k, a: pt.u, b: net.us }], v: net.tracks[pt.k] };
  if (pt.line === 'access') return { parts: [{ key: 'a', a: pt.u, b: net.us }], v: net.cv };
  return { parts: [], v: pt.v };
}

/** Intervals from A to B along the roads, and how many times the route turns across a road. */
export function roadPath(A, B, net) {
  const side = pt => Math.sign(pt.u - net.us);
  if (A.line === 'track' && B.line === 'track' && A.k === B.k && side(A) === side(B)) return { parts: [{ key: 't' + A.k, a: A.u, b: B.u }], turns: 0 };
  const a = toSpine(A, net), b = toSpine(B, net);
  const parts = [...a.parts, ...(a.v !== b.v ? [{ key: 's', a: a.v, b: b.v }] : []), ...b.parts];
  return { parts: parts.filter(q => q.a !== q.b), turns: (a.parts.length ? 1 : 0) + (b.parts.length ? 1 : 0) };
}

/** Sweep a line's intervals into stretches with a constant circuit count: [{ a, b, c }]. */
export function coverage(intervals) {
  const ev = [];
  for (const { a, b } of intervals) { ev.push([Math.min(a, b), 1], [Math.max(a, b), -1]); }
  ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const out = [];
  let c = 0, last = null;
  for (const [x, d] of ev) {
    if (c > 0 && last !== null && x > last) {
      const prev = out[out.length - 1];
      if (prev && prev.c === c && Math.abs(prev.b - last) < 1e-9) prev.b = x; else out.push({ a: last, b: x, c });
    }
    c += d; last = x;
  }
  return out;
}

/** Trench metres by section for a stretch of length L carrying c circuits. */
export function trenchFor(c, L, into) {
  const two = Math.floor(c / 2), one = c % 2;
  if (two) into[SECTION_FOR.two] = (into[SECTION_FOR.two] || 0) + two * L;
  if (one) into[SECTION_FOR.one] = (into[SECTION_FOR.one] || 0) + L;
  return into;
}

/**
 * routeFeeders(template, net, p) -> { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct, crossings }
 * net: { us, cv, spine, access, tracks, stations: [{ id, u, v, k, track }] } in the layout frame.
 */
export function routeFeeders(tpl, net, p) {
  const at = new Map(net.stations.map(s => [s.id, s]));
  const board = net.access ? { line: 'access', u: net.access.u0 } : { line: 'spine', v: net.cv };
  const onRoad = s => ({ line: 'track', k: s.k, u: s.u });
  const byKey = new Map(), stubs = new Map();
  const add = (key, a, b) => { if (!byKey.has(key)) byKey.set(key, []); byKey.get(key).push({ a, b }); };
  const opts = { pf: tpl.params.powerFactor, soilKmW: tpl.params.soilKmW, kv: 33 };
  const cableBySize = {}, trenchByType = {};
  let crossings = 0, cableM = 0, worst = 0, upsized = 0;
  const dropOf = hops => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opts), 0);
  const feeders = tpl.feeders.map((f, fi) => {
    let from = board, fromStub = 0, fromId = null;
    const hops = f.chain.map((st, k) => {
      const s = at.get(st.id), to = onRoad(s), path = roadPath(from, to, net), stub = Math.abs(s.v - s.track);
      for (const q of path.parts) add(q.key, q.a, q.b);
      stubs.set(s.id, (stubs.get(s.id) || 0) + 1);
      if (fromId) stubs.set(fromId, stubs.get(fromId) + 1);
      crossings += path.turns;
      const road = path.parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0), seg = f.segments[k];
      const hop = { from: fromId || f.board, to: s.id, areaMm2: seg.area, loadMVA: seg.loadMVA, lengthM: road + stub + fromStub, parts: path.parts };
      from = to; fromStub = stub; fromId = s.id;
      return hop;
    });
    for (let guard = 0; dropOf(hops) > tpl.params.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]; upsized++;
    }
    for (const h of hops) {
      const cable = CABLE_ALLOW.cores * (h.lengthM * (1 + CABLE_ALLOW.slack) + 2 * CABLE_ALLOW.tailM);
      cableBySize[h.areaMm2] = (cableBySize[h.areaMm2] || 0) + cable; cableM += cable;
    }
    const drop = dropOf(hops);
    worst = Math.max(worst, drop);
    return { id: `F${fi + 1}`, board: f.board, hops, dropPct: drop, stations: f.chain.map(s => s.id) };
  });

  // Shared stretches: one trench per stretch, sized by the circuits in it.
  const pieces = [];
  let trenchM = 0;
  for (const [key, list] of byKey) for (const { a, b, c } of coverage(list)) {
    pieces.push({ key, a, b, c }); trenchFor(c, b - a, trenchByType); trenchM += b - a;
  }
  for (const [id, c] of stubs) {
    const s = at.get(id), L = Math.abs(s.v - s.track);
    if (L > 0) { pieces.push({ key: 'stub:' + id, a: s.track, b: s.v, c, u: s.u }); trenchFor(c, L, trenchByType); trenchM += L; }
  }
  const crossM = crossings * (p.spineWidthM + 2);
  if (crossM) { trenchByType[SECTION_FOR.crossing] = (trenchByType[SECTION_FOR.crossing] || 0) + crossM; trenchM += crossM; }
  // Rating of the shared trenches: the busiest hop's cable alone, and two such circuits at 450 mm centres.
  const busy = feeders.flatMap(f => f.hops).sort((a, b) => b.loadMVA - a.loadMVA)[0];
  let trenchRating = null;
  if (busy) {
    const spec = { loadA: busy.loadMVA * 1e6 / (Math.sqrt(3) * 33000), areaMm2: busy.areaMm2, odMm: build(busy.areaMm2).od };
    const env = { soilKmW: tpl.params.soilKmW || 1.2 }, one = checkAsDrawn('mv', 1, spec, 0.45, env), two = checkAsDrawn('mv', 2, spec, 0.45, env);
    trenchRating = { hop: `${busy.from} to ${busy.to}`, loadA: Math.round(spec.loadA), areaMm2: busy.areaMm2, one: one.utilisation, two: two.utilisation,
      ok: two.utilisation <= 1, basis: 'IEC 60287 method (own code), 0.91 m cover; indicative' };
  }
  return { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct: worst, crossings, upsized, trenchRating,
    dropOk: worst <= tpl.params.vdropLimitPct + 1e-9 };
}

// Readout rows for the MV trenches and cables that add up, in words (user test H3). Each trench is counted: where more
// than two circuits share a stretch the trenches run side by side, so trench-km can exceed the route. Cable is single
// core (three per circuit, with slack and tails); circuit-km is a third of it.
export const SECTION_WORDS = Object.freeze({ [SECTION_FOR.one]: 'one 33 kV circuit, farmland (0.91 m cover)',
  [SECTION_FOR.two]: 'two 33 kV circuits', [SECTION_FOR.crossing]: 'road crossings, ducted' });
export function trenchRows(e, fmt = v => v.toFixed(2)) {
  const k = m => fmt(m / 1000), types = Object.entries(e.trenchByType || {}).filter(([, m]) => m > 0), total = types.reduce((t, [, m]) => t + m, 0);
  const rows = [['MV trenches', `${k(total)} trench-km, along ${k(e.trenchM)} km of route`]];
  for (const [id, m] of types) rows.push(['', `${SECTION_WORDS[id] || 'other trench'}: ${k(m)} trench-km`]);
  rows.push(['MV cable', `${k(e.cableM / CABLE_ALLOW.cores)} circuit-km (${k(e.cableM)} km of single-core cable)`]);
  for (const [a, m] of Object.entries(e.cableBySize || {}).sort((x, y) => x[0] - y[0])) rows.push(['', `${a} mm² aluminium: ${k(m / CABLE_ALLOW.cores)} circuit-km`]);
  return { rows, trenchKm: total / 1000 };
}

Single-Line Diagram (SLD) Connect

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, substations, overhead lines (OHL) and 132kV.

Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271552-site-world/world/sld-connect.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Single-Line Diagram (SLD) Connect; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9565 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/sld-connect.mjs:1-55 6c117c539568a4cdba17bdd8f65174c16f6068a5
  • sha256 189734c2e6f725ae40ca42ed026732cc0517ea714b2ae03577659b02fc82bf84
  • target sha256 d74272f971286be44fdf1d40a767244e53425440c25d75a13e3f7721b27ea4f9
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/sld-connect.mjs · lines 1–57 of 57 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern chooseConnection (shared by 3 files)

What it does
It calculates cables, substations, overhead lines (OHL) and 132kV. Defines nearest, km, kvForMW, chooseConnection.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): 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, substations, overhead lines (OHL), 132kV, 400kV, 275kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 33kV.
Downstream impact
Used directly by 2 files: Cmd Trench (globalgrid2050); Connect Here (globalgrid2050).
What it achieves
It is built from the nearest step (`nearest`), the kV for MW helper (`kvForMW`) and the choose connection helper (`chooseConnection`). Which grid connection a plant gets, from its size and what is near it. Its code works with 132 kV, 400 kV and 275 kV.
Why it matters
Imported by Cmd Trench and Connect Here.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Trench (import), imported by Connect Here (import)
Produces
CONNECT_RULES, CONNECT_LABEL, kvForMW, chooseConnection
Defines here
nearest, km, kvForMW, chooseConnection
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/sld-connect.mjs:1-57 · blob 1547a94d9212241a678ab87ce17bb5985a081f60 · 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 sld-connect.mjs at v12 commit 3adcee9 (file last changed 219d82e). Modular star family: public #148022 kvForMW.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// sld-connect.mjs: which grid connection a plant gets, from its size and what is near it. Editable, illustrative rules;
// the network operator decides the real connection. One connection object serves the solar block, the single-line
// diagram and Follow (user test H4).
//   The voltage follows the plant's size: up to smallMaxMW at 33 kV, up to dnoMaxMW at 132 kV, up to midMaxMW at 275 kV,
//   above that 400 kV (a block with its own grid transformer connects at 132 kV at least).
//   275 and 400 kV: only through a bay at a substation of that voltage (within transSearchM), by fully ducted, unjointed
//   HV cable; never a tee into a transmission line.
//   132 kV and below: a cable to the nearest network operator substation of that voltage (within dnoSearchM); else a
//   tee into a line of that voltage within teeM (teeMaxKv at most); else no nearby connection (an assumed landing that
//   says so).
// Pure.

export const CONNECT_RULES = Object.freeze({ smallMaxMW: 30, dnoMaxMW: 150, midMaxMW: 400, teeM: 3000, teeMaxKv: 132, dnoSearchM: 30000,
  transSearchM: 40000 });
export const CONNECT_LABEL = 'Connection chosen by illustrative rules (size and distance); the network operator decides the real one.';

const nearest = (list, at, ok) => list.filter(x => ok(x) && Number.isFinite(x.e) && Number.isFinite(x.n))
  .map(x => ({ ...x, d: Math.hypot(x.e - at[0], x.n - at[1]) })).sort((a, b) => a.d - b.d)[0] || null;
const km = m => `${(m / 1000).toFixed(1)} km`;

/** The connection voltage for a plant of mw: 33, 132, 275 or 400 kV; minKv raises it (132 for a block with its own grid transformer). */
export function kvForMW(mw, { minKv = 0, rules = {} } = {}) {
  const R = { ...CONNECT_RULES, ...rules };
  const kv = mw <= R.smallMaxMW ? 33 : mw <= R.dnoMaxMW ? 132 : mw <= R.midMaxMW ? 275 : 400;
  return [33, 132, 275, 400].find(v => v >= Math.max(kv, minKv)) || 400;
}

/**
 * chooseConnection({ mw, at: [e, n], subs: [{ e, n, kv }], towers: [{ e, n, kv }], kv?, minKv?, rules }) ->
 *   { rule, text, kv, connection: 'cable' | 'ohl-tee' | 'none', route: 'cable' | 'overhead line' | null,
 *     landing: { e, n, kv, real, kind: 'gis-bay' | 'dno-sub' | 'tower' } | null }
 * kv: the voltage already fixed (the placed block's grid transformer); else by size.
 */
export function chooseConnection({ mw, at, subs = [], towers = [], kv: fixed = null, minKv = 0, rules = {} }) {
  const R = { ...CONNECT_RULES, ...rules }, kv = fixed || kvForMW(mw, { minKv, rules });
  const size = `${Math.round(mw)} MW`;
  if (kv >= 275) {
    const s = nearest(subs, at, x => x.kv === kv);
    if (s && s.d <= R.transSearchM) return { rule: `bay-${kv}`, kv, connection: 'cable', route: 'cable',
      text: `${size} at ${kv} kV: ducted, unjointed HV cable to a bay at the ${kv} kV substation ${km(s.d)} away (no tee at transmission voltage)`,
      landing: { e: s.e, n: s.n, kv, real: true, kind: 'gis-bay' } };
    return { rule: 'none', kv, connection: 'none', route: null, landing: null,
      text: `${size} at ${kv} kV: no ${kv} kV substation within ${km(R.transSearchM)}; the landing shown is an assumed point, not a substation` };
  }
  const s = nearest(subs, at, x => x.kv === kv);
  if (s && s.d <= R.dnoSearchM) return { rule: `dno-${kv}`, kv, connection: 'cable', route: 'cable',
    text: `${size} at ${kv} kV: cable to the nearest ${kv} kV network operator substation, ${km(s.d)} away`,
    landing: { e: s.e, n: s.n, kv, real: true, kind: 'dno-sub' } };
  const t = kv <= R.teeMaxKv ? nearest(towers, at, x => x.kv === kv) : null;
  if (t && t.d <= R.teeM) return { rule: `tee-${kv}`, kv, connection: 'ohl-tee', route: 'overhead line',
    text: `${size} at ${kv} kV: no ${kv} kV substation within ${km(R.dnoSearchM)}; overhead tee into the ${kv} kV line ${km(t.d)} away (illustrative)`,
    landing: { e: t.e, n: t.n, kv, real: true, kind: 'tower' } };
  return { rule: 'none', kv, connection: 'none', route: null, landing: null,
    text: `${size} at ${kv} kV: no nearby connection at ${kv} kV; the landing shown is an assumed point, not a substation` };
}

Single-Line Diagram (SLD) Rules

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, transformers and battery storage (BESS), using IEC 60502-2 and BS 7671.

Set aside from the main view: 97% of its lines are the same as solar-design-studio/202609271853-site-world/world/sld-rules.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Single-Line Diagram (SLD) Rules; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9733 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/sld-rules.mjs:1-93 b27d1862239e37c3517715c170d703a643f6ca81
  • sha256 5e5a000bd0735ce7c5834a49e0299a1cb13ba1f4f7f17bdafe8c232004a45ddc
  • target sha256 cea903f4aaf404e1a5163ed5b860b79459f01e6d731e1bf3f183a59390943703
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/sld-rules.mjs · lines 1–95 of 95 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern isolationChecks (shared by 3 files)

What it does
It calculates cables, transformers and battery storage (BESS). Defines groupFactor, economicSize, cost, isolationChecks, zOf.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): 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, battery storage (BESS), 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Block MV (globalgrid2050).
What it achieves
It groups factor (`groupFactor`) and is built from the economic size helper (`economicSize`) and the cost step (`cost`). The generic electrical rules the single-line diagram generator shares (`sld-plant.mjs`, `block-mv.mjs`, `sld-graph.mjs`): group factors for circuits sharing a trench, an economic step on top of the technical cable size, the switching and protection devices of each functional way. Its code works with 33 kV.
Why it matters
Imported by Block MV.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Cable Rating (import), Elec Style (import), Measure Format (import)
Used by
imported by Block MV (import)
Produces
SLD_LABEL, groupFactor, ECONOMIC, PALETTE, economicSize, DEVICES, INVERTER_ISOLATION, isolationChecks, SLD_DEFAULTS, C, zOf
Defines here
groupFactor, economicSize, cost, isolationChecks, zOf
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/sld-rules.mjs:1-95 · blob 2c079ebca4c826e5fb25eb9c8bf79636822840d5 · 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 sld-rules.mjs at v12 commit 3adcee9 (file last changed 9b1ffad). Modular star family: public #148057 economicSize.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// sld-rules.mjs: the generic electrical rules the single-line diagram generator shares (sld-plant.mjs, block-mv.mjs,
// sld-graph.mjs): group factors for circuits sharing a trench, an economic step on top of the technical cable size,
// the switching and protection devices of each functional way, and the assumed impedances and source.
// Every value here is generic practice or a public standard, or is marked assumed. Illustrative, not a design for any
// site. Pure: imports only the cable rating.

import { rating, SIZES } from './cable-rating.mjs';

export const SLD_LABEL = 'Illustrative, not a design for any site.';

// Group factors for 33 kV trefoil circuits laid direct side by side, about 0.4-0.45 m apart: approximate values in the
// style of the IEC 60502-2 annex tables (a rating study replaces them). Index = circuits in the trench.
const GROUP = [1, 1, 0.87, 0.78, 0.73, 0.69, 0.66, 0.64, 0.62];
export const groupFactor = n => GROUP[Math.max(1, Math.min(GROUP.length - 1, Math.round(n) || 1))];

// Economic step (assumed unit costs, not any supplier's): capitalised I2R loss against a cable cost that grows with the
// conductor area. Loss hours and the present-worth factor are generic solar figures; money is in plain cost units.
export const ECONOMIC = Object.freeze({ lossHours: 1100, pricePerMWh: 60, years: 25, rate: 0.06, costPerM: 30, costPerMm2M: 0.09 });
export const PALETTE = Object.freeze([120, 185, 300, 500, 630, 800, 1000]); // a small stock of sizes, not the full series

/**
 * economicSize(technicalArea, mva, lengthM, opts) -> the palette size, at or above the technical size, whose cable cost
 * plus capitalised losses is least. opts: cable-rating options plus { economic }.
 */
export function economicSize(area, mva, lengthM, opts = {}) {
  const e = { ...ECONOMIC, ...(opts.economic || {}) }, kv = opts.kv || 33, I = mva * 1e6 / (Math.sqrt(3) * kv * 1000);
  const pw = (1 - (1 + e.rate) ** -e.years) / e.rate;
  const cost = a => {
    const R = rating(a, opts).R;                               // ohm per metre at the rated temperature (conservative)
    return lengthM * (e.costPerM + e.costPerMm2M * a * 3) + 3 * I * I * R * lengthM * e.lossHours / 1e6 * e.pricePerMWh * pw;
  };
  const list = PALETTE.filter(a => a >= area && SIZES.includes(a));
  if (!list.length) return area;
  return list.reduce((best, a) => (cost(a) < cost(best) - 1e-9 ? a : best), list[0]);
}

// Devices of each functional way, as the diagram draws them (state: closed unless marked open).
export const DEVICES = Object.freeze({
  'rmu-in': ['switch-disconnector', 'earth-switch'],
  'rmu-out': ['switch-disconnector', 'earth-switch'],
  'rmu-tx': ['circuit-breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'lv-main': ['main breaker', 'insulation monitor', 'surge protection', 'meter'],
  'lv-way': ['breaker'],                                       // one per inverter; no local isolator at the inverter end
  'mv-way': ['vacuum circuit breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'mv-incomer': ['vacuum circuit breaker', 'protection 51 87T'],
  'bus-tie': ['vacuum circuit breaker (normally open)'],
  'hv-bay': ['disconnector', 'earth switch', 'surge arresters', 'current and voltage transformers'],
  'gis-bay': ['gas-insulated circuit breaker', 'disconnector', 'earth switch'],
  'earthing': ['earthing transformer (zigzag)', 'neutral earthing resistor']
});

// Isolation at the inverter from every source that feeds it (BS 7671 537 and 712.537; IEC 62548-1 isolation clauses):
// each source present needs a named means of isolation at the inverter. Defaults as the diagram draws them: the PV side's
// DC switch-disconnector is taken from the inverter's datasheet (assumed); the AC side has only the board breaker, no
// local isolator at the inverter end; no BESS. A plain check with editable inputs, not a design.
export const INVERTER_ISOLATION = Object.freeze({ pv: 'DC switch-disconnector in the inverter (datasheet, assumed)', grid: null, bess: undefined });
export function isolationChecks(at = INVERTER_ISOLATION) {
  const WORDS = { pv: 'PV (DC)', grid: 'grid (AC)', bess: 'battery (BESS)' };
  return Object.entries(WORDS).filter(([k]) => at[k] !== undefined).map(([k, w]) => ({ source: w, ok: !!at[k], device: at[k] || 'none at the inverter' }));
}

// Assumed impedances and the grid source. Transformer impedances sit inside the usual ranges (station 6-10 %).
export const SLD_DEFAULTS = Object.freeze({
  sBaseMVA: 100, c: 1.1,                       // IEC 60909 voltage factor for maximum fault current
  sourceKA: null, sourceXR: 14,                // grid fault level at the landing: set, or by voltage below (assumed)
  sourceKAByKv: { 400: 40, 275: 40, 132: 25, 33: 12.5 },
  stZPct: 7, stXR: 10, stVector: 'Dy11y11',    // station transformer, one unit with a list of LV windings
  gtZPct: 14, gtXR: 40, gtVector: 'YNd11', gtHvNeutral: 'solid', gtTwoLvFromMVA: 120,
  tapRange: 0.10, tapStep: 0.0125, tapTarget: 1.0,  // grid transformer on-load tap changer (illustrative, editable)
  hvCableOhmKm: [0.012, 0.19],                 // single-core HV cable, large copper (assumed)
  ohlOhmKm: [0.03, 0.3],                       // overhead line option (assumed)
  lvXOhmKm: 0.08,                              // single-core LV cable reactance (assumed)
  busPu: [1e-6, 1e-5],                         // busbars and closed switching devices
  nerA: 1000, powerFactor: 0.95,               // NER limit (assumed); export at 0.95 for the drop (reactive duty)
  module: { w: 660, vmp: 38.6, imp: 17.1, voc: 45.9 }, dcAreaMm2: 6, dcOhmKm20: 3.08, dcTempC: 70
});

/** Complex numbers as [re, im]: the few operations the solvers need. */
export const C = Object.freeze({
  add: (a, b) => [a[0] + b[0], a[1] + b[1]], sub: (a, b) => [a[0] - b[0], a[1] - b[1]],
  mul: (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]],
  div: (a, b) => { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; },
  conj: a => [a[0], -a[1]], abs: a => Math.hypot(a[0], a[1])
});

/** An impedance of |z| per unit at ratio X/R, as [r, x]. */
export const zOf = (mag, xr) => { const r = mag / Math.sqrt(1 + xr * xr); return [r, r * xr]; };

// Every electrical readout ends with this line (earthing, the single-line diagram, Follow, the check HUD's working).
export { ELEC_FOOTER } from './elec-style.mjs';   // one source for the words

// Quantities by the one number rule (measure-format.mjs): significant figures, one dash for none.
export { fmtQ } from './measure-format.mjs';

Substations

A JavaScript file in GlobalGrid2050 that draws grid substations and substations footprints odbl, and uses data from the GridAtlas repository. It labels block (`labelBlock`) and syncs btn (`syncBtn`).

interactionglobalgrid2050 / energy-transition-simulator/202609280014/mod/substations.js · lines 1–189 of 189 · version 2026-09-28 00:14 · 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 24 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 upstream_foresight (path word 'substations'): 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
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
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
globalgrid2050 · energy-transition-simulator/202609280014/mod · script
Uses
none found
Used by
none found
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, start
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/substations.js:1-189 · blob 576b2bdebdae893f821c4809e0f827bb63359e3e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: 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 = 'Substation points: GridAtlas. Fences: OpenStreetMap contributors (ODbL); 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);
  }

  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 };
  }
  (function wait() { if (window.SIM && SIM.map) start(); else setTimeout(wait, 100); })();
})();

Manifest

A configuration file in the feature requests folder of GlobalGrid2050 covering substations, solar and battery storage (BESS).

docs-configglobalgrid2050 / feature_requests/005_extract_v2_substation_data/manifest.yml · lines 1–42 of 42 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, solar, battery storage (BESS).
What it achieves
Moves substation normalisation and loading into `gis-sld-v2-substations.js` without changing map, finance, topology or export logic.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · feature_requests/005_extract_v2_substation_data · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
Extract V2 substation data
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 feature_requests/005_extract_v2_substation_data/manifest.yml:1-42 · blob fcf8ceed1aeca6dc9c9aa77d5d76992f5f737c00 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
name: Extract V2 substation data
summary: Moves substation normalisation and loading into gis-sld-v2-substations.js without changing map, finance, topology or export logic.

operations:
  - type: insert_after
    file: solar-bess-topology-v2/indexforgis-sld-v2.html
    marker: |
      <script src="gis-sld-v2-state.js"></script>
    insert: |
      
      <script src="gis-sld-v2-substations.js"></script>

  - type: regex_replace
    file: solar-bess-topology-v2/indexforgis-sld-v2.html
    pattern: |
      // ============================================================
      // SUBSTATION DATA LOAD
      // ============================================================
      function normaliseSubstations\(raw\) \{[\s\S]*?// ============================================================
      // MAP CLICK HANDLERS
      // ============================================================
    replace: |
      // ============================================================
      // MAP CLICK HANDLERS
      // ============================================================
    flags: ms

  - type: assert_contains
    file: solar-bess-topology-v2/indexforgis-sld-v2.html
    text: 'gis-sld-v2-substations.js'

  - type: assert_contains
    file: solar-bess-topology-v2/gis-sld-v2-substations.js
    text: 'function normaliseSubstations(raw)'

  - type: assert_contains
    file: solar-bess-topology-v2/gis-sld-v2-substations.js
    text: 'async function loadSubstations()'

  - type: assert_contains
    file: solar-bess-topology-v2/indexforgis-sld-v2.html
    text: '// MAP CLICK HANDLERS'