GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / globalgrid2050 / energy-transition-simulator/202609280014/mod/engine

Cable Route and 2 more files

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables. It routes cable (`routeCable`) and draws lines (`drawLines`).

417 lines of JavaScript from globalgrid2050, in 3 files. Topic: Cables and conductors. Section 14 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. Cable Route electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cable-route.mjs lines 1–209
  2. Cmd Grammar Trench ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-trench.mjs lines 1–87
  3. Cmd Trench transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-trench.mjs lines 1–121

Cable Route

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables. It routes cable (`routeCable`) and draws lines (`drawLines`).

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

Evidence
  • line-jaccard 0.9877 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/cable-route.mjs:1-207 265884bcbba42955a68f34d40a35abe73c8845cc
  • sha256 55b37341581201f8266913d6d47310194a592bb7c836aed1bcb62a36080b4c23
  • target sha256 789555abe8618c46dcdc632271d9d715c670509530e6c9d511739022e0d9831b
  • 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/cable-route.mjs · lines 1–209 of 209 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern bendRadiusAt (shared by 3 files)

What it does
It calculates cables. Defines 13 functions or classes, including sub, norm, unit, turn, planSegments.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
Downstream impact
Used directly by 1 file: Connect Here (globalgrid2050).
What it achieves
A buried cable laid along a plan polyline.
Why it matters
Imported by Connect Here.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Connect Here (import)
Produces
routeCable
Defines here
sub, norm, unit, turn, planSegments, line, at, coreOffsets, routeCable, zAt, walk, bendRadiusAt, drawLines
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/cable-route.mjs:1-209 · blob ddb1aca11f50b02695425fdb02aca571b5ca3ebe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cable-route.mjs at v12 commit 3adcee9 (file last changed 04b1c72). Modular star family: public #144725 routeCable.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// Cable route: a buried cable laid along a plan polyline. Pure: no imports, no DOM, no WebGL.
// Local east (x), north (y), up (z), metres, as camera.mjs.
//
// routeCable({ points, minBendRadius, depthBelowGround, groundAt, formation, spacing, step })
//   points          [[x, y], ...] plan vertices (at least two)
//   minBendRadius   every corner is replaced by a circular arc of this radius (a fillet)
//   depthBelowGround the centreline sits this far below groundAt(x, y)
//   groundAt        (x, y) -> ground height; default flat at 0
//   formation       'flat' (three cores side by side, centre to centre = spacing) or
//                   'trefoil' (three touching cores, centre to centre = spacing = core diameter)
//   step            sampling interval along the route, metres (default 1)
//
// A corner whose legs are too short for the requested radius is still filleted, with the largest radius the
// legs allow, and reported in violations: { index, requestedRadius, available }. Nothing is silently accepted.
// length2d is exact (straights plus arcs). length3d walks the samples with the exact plan distance between
// them and the ground-following height change, so on flat ground length3d equals length2d.

const EPS = 1e-9;

function sub(a, b) { return [a[0] - b[0], a[1] - b[1]]; }
function norm(v) { return Math.hypot(v[0], v[1]); }
function unit(v) { const l = norm(v); return [v[0] / l, v[1] / l]; }

// Signed turn from direction d1 to d2, radians, left (anticlockwise) positive.
function turn(d1, d2) { return Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]); }

// Build the plan geometry: straights and arcs, with fitted radii and violations.
function planSegments(pts, R) {
  const n = pts.length;
  const legs = [];
  for (let k = 0; k < n - 1; k++) {
    const v = sub(pts[k + 1], pts[k]);
    legs.push({ len: norm(v), dir: norm(v) > EPS ? unit(v) : null });
  }
  // Requested tangent length at each vertex (0 at the ends and at straight-through vertices).
  const theta = new Array(n).fill(0);
  const want = new Array(n).fill(0);
  for (let i = 1; i < n - 1; i++) {
    const a = legs[i - 1].dir, b = legs[i].dir;
    if (!a || !b) continue;
    theta[i] = turn(a, b);
    const half = Math.abs(theta[i]) / 2;
    if (half < EPS) continue;
    want[i] = Math.PI / 2 - half < EPS ? Infinity : R * Math.tan(half);
  }
  // Each leg must hold the tangents of both its ends; share a short leg in proportion to what each end asks.
  const cap = want.slice();
  for (let k = 0; k < n - 1; k++) {
    const t0 = want[k], t1 = want[k + 1], len = legs[k].len;
    if (t0 + t1 <= len) continue;
    if (!isFinite(t0) && !isFinite(t1)) { cap[k] = Math.min(cap[k], len / 2); cap[k + 1] = Math.min(cap[k + 1], len / 2); continue; }
    const f0 = !isFinite(t0) ? 1 : !isFinite(t1) ? 0 : t0 / (t0 + t1);
    cap[k] = Math.min(cap[k], len * f0);
    cap[k + 1] = Math.min(cap[k + 1], len * (1 - f0));
  }
  const violations = [];
  const corners = [];
  for (let i = 1; i < n - 1; i++) {
    if (want[i] === 0) continue;
    const half = Math.abs(theta[i]) / 2;
    const reversal = Math.PI / 2 - half < EPS;
    const t = reversal ? 0 : cap[i];
    const r = reversal ? 0 : t / Math.tan(half);
    if (r < R * (1 - 1e-9)) violations.push({ index: i, requestedRadius: R, available: r });
    if (r > EPS) corners.push({ index: i, t, r, theta: theta[i] });
  }
  // Walk the route: straight to each tangent point, arc round, carry on.
  const segs = [];
  let cur = pts[0].slice(0, 2), s = 0;
  const line = (a, b) => {
    const len = norm(sub(b, a));
    if (len < EPS) return;
    segs.push({ type: 'line', a, b, dir: unit(sub(b, a)), len, s0: s, s1: s + len });
    s += len;
  };
  for (const c of corners) {
    const d1 = legs[c.index - 1].dir, d2 = legs[c.index].dir, p = pts[c.index];
    const A = [p[0] - d1[0] * c.t, p[1] - d1[1] * c.t];
    const B = [p[0] + d2[0] * c.t, p[1] + d2[1] * c.t];
    line(cur, A);
    const side = Math.sign(c.theta);
    const centre = [A[0] - d1[1] * c.r * side, A[1] + d1[0] * c.r * side];
    const a0 = Math.atan2(A[1] - centre[1], A[0] - centre[0]);
    const len = c.r * Math.abs(c.theta);
    segs.push({ type: 'arc', centre, r: c.r, a0, theta: c.theta, h0: Math.atan2(d1[1], d1[0]), len, s0: s, s1: s + len, index: c.index });
    s += len;
    cur = B;
  }
  line(cur, pts[n - 1].slice(0, 2));
  return { segs, violations, length2d: s };
}

// Point and heading at parameter u in [0, 1] along a segment.
function at(seg, u) {
  if (seg.type === 'line') {
    return { x: seg.a[0] + (seg.b[0] - seg.a[0]) * u, y: seg.a[1] + (seg.b[1] - seg.a[1]) * u, h: Math.atan2(seg.dir[1], seg.dir[0]) };
  }
  const ang = seg.a0 + seg.theta * u;
  return { x: seg.centre[0] + seg.r * Math.cos(ang), y: seg.centre[1] + seg.r * Math.sin(ang), h: seg.h0 + seg.theta * u };
}

// Lateral (left of travel) and vertical offsets of the three cores from the centreline.
function coreOffsets(formation, spacing) {
  if (formation === 'trefoil') {
    const rc = spacing / Math.sqrt(3); // circumradius of the touching triangle
    return [[0, rc], [-spacing / 2, -rc / 2], [spacing / 2, -rc / 2]];
  }
  return [[spacing, 0], [0, 0], [-spacing, 0]];
}

export function routeCable({
  points, minBendRadius = 0, depthBelowGround = 0, groundAt = () => 0,
  formation = 'flat', spacing = 0, step = 1,
} = {}) {
  if (!Array.isArray(points) || points.length < 2) throw Error('routeCable needs at least two points');
  if (formation !== 'flat' && formation !== 'trefoil') throw Error(`unknown formation: ${formation}`);
  if (!(step > 0)) throw Error('step must be positive');
  const R = Math.max(0, minBendRadius);
  const { segs, violations, length2d } = planSegments(points, R);
  const zAt = (x, y) => groundAt(x, y) - depthBelowGround;

  // Samples along the centreline: plan point, heading, chainage, and the segment they belong to.
  const samples = [];
  segs.forEach((seg, si) => {
    let pieces = Math.max(1, Math.ceil(seg.len / step));
    if (seg.type === 'arc') pieces = Math.max(pieces, Math.ceil(Math.abs(seg.theta) / (Math.PI / 36)));
    for (let j = si === 0 ? 0 : 1; j <= pieces; j++) {
      const u = j / pieces;
      samples.push({ ...at(seg, u), s: seg.s0 + seg.len * u, seg: si });
    }
  });
  if (!samples.length) { const p = points[0]; samples.push({ x: p[0], y: p[1], h: 0, s: 0, seg: -1 }); }

  // Walk one line of samples, offset laterally by `lat` and vertically by `vert`, measuring as we go.
  const walk = (lat, vert) => {
    const poly = [];
    let len2 = 0, len3 = 0;
    for (let k = 0; k < samples.length; k++) {
      const q = samples[k];
      const x = q.x - Math.sin(q.h) * lat, y = q.y + Math.cos(q.h) * lat;
      const z = zAt(q.x, q.y) + vert;
      if (k > 0) {
        const prev = samples[k - 1], seg = segs[q.seg];
        // Exact plan distance: an offset arc has radius r - lat for a left turn, r + lat for a right turn.
        const scale = seg.type === 'arc' ? (seg.r - Math.sign(seg.theta) * lat) / seg.r : 1;
        const ds = (q.s - prev.s) * scale, dz = z - poly[k - 1][2];
        len2 += ds; len3 += Math.hypot(ds, dz);
      }
      poly.push([x, y, z]);
    }
    return { polyline: poly, length2d: len2, length3d: len3 };
  };

  const centre = walk(0, 0);
  const names = formation === 'trefoil' ? ['top', 'left', 'right'] : ['left', 'centre', 'right'];
  const cores = coreOffsets(formation, spacing).map(([lat, vert], i) => {
    const w = walk(lat, vert);
    return { name: names[i], lateral: lat, vertical: vert, polyline: w.polyline, length2d: w.length2d, length3d: w.length3d };
  });

  // A core on the inside of a bend whose offset exceeds the bend radius would fold back on itself.
  const maxLat = Math.max(...cores.map((c) => Math.abs(c.lateral)));
  for (const seg of segs) {
    if (seg.type === 'arc' && seg.r <= maxLat && !violations.some((v) => v.index === seg.index)) {
      violations.push({ index: seg.index, requestedRadius: R, available: seg.r, reason: 'inner core offset exceeds bend radius' });
    }
  }
  violations.sort((a, b) => a.index - b.index);

  const bendRadiusAt = (chainage) => {
    for (const seg of segs) {
      if (chainage >= seg.s0 - EPS && chainage <= seg.s1 + EPS && seg.type === 'arc') return seg.r;
    }
    return Infinity;
  };

  const drawLines = ({ includeCores = true, includeCentreline = true } = {}) => {
    const lines = [];
    if (includeCentreline) lines.push(centre.polyline);
    if (includeCores) for (const c of cores) lines.push(c.polyline);
    let count = 0;
    for (const l of lines) count += Math.max(0, l.length - 1);
    const out = new Float32Array(count * 6);
    let o = 0;
    for (const l of lines) {
      for (let k = 1; k < l.length; k++) {
        out[o++] = l[k - 1][0]; out[o++] = l[k - 1][1]; out[o++] = l[k - 1][2];
        out[o++] = l[k][0]; out[o++] = l[k][1]; out[o++] = l[k][2];
      }
    }
    return out;
  };

  return {
    centreline: centre.polyline,
    segments: segs.map((g) => (g.type === 'arc'
      ? { type: 'arc', centre: g.centre, radius: g.r, turn: g.theta, s0: g.s0, s1: g.s1, index: g.index }
      : { type: 'line', from: g.a, to: g.b, s0: g.s0, s1: g.s1 })),
    violations,
    length2d,
    length3d: centre.length3d,
    formation,
    cores,
    bendRadiusAt,
    drawLines,
  };
}

Cmd Grammar Trench

A JavaScript module in the engine folder of GlobalGrid2050 covering cables, solar and 33kV. It parses trench (`parseTrench`) and is built from the is num helper (`isNum`).

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

Evidence
  • line-jaccard 0.9714 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cmd-grammar-trench.mjs:1-85 7bfe43d5cd0e2c5f71806a066f61f59e60c009d6
  • sha256 eb447bd87f28d4a8f662b929af95f396384297c0b83d536c07f27b2b7f55d310
  • target sha256 f193cbf79545a8e0ff60ca0b80ba8fcb80b91acd12a5433d957c43dd737c30c5
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

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

What it does
It lists and searches cables, solar and 33kV. Defines isNum, parseTrench.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'trench'): 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, solar, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Cmd Grammar (globalgrid2050).
What it achieves
The trench and cable words of the command line (trench, cable, load, xray), split out of `cmd-grammar.mjs` to keep each cartridge under 400 lines. Its code works with 33 kV.
Why it matters
Imported by Cmd Grammar.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar (import)
Produces
TRENCH_KEYS_TYPED, SPLIT_KINDS, COVER_KINDS, TRENCH_COMMANDS, TRENCH_VOCAB, parseTrench
Defines here
isNum, parseTrench
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/cmd-grammar-trench.mjs:1-87 · blob 3b17d62383d44e93604f5a506ef5dff2d5a0a165 · 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 cmd-grammar-trench.mjs at v12 commit 3adcee9 (file last changed 4c57503). Modular star family: public #148229 parseTrench.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-grammar-trench.mjs: the trench and cable words of the command line (trench, cable, load, xray), split out of
// cmd-grammar.mjs to keep each cartridge under 400 lines. Pure: parse() hands each verb here with its words and helpers.

// Typed settings for the block's trenches sized by rating (cmd-trench.mjs), checked like the grammar's KEYS.
export const TRENCH_KEYS_TYPED = Object.freeze({
  soil: { label: 'soil thermal resistivity', unit: 'K.m/W', min: 0.5, max: 3.5 },
  load: { label: 'load profile', choices: ['continuous', 'solar-day'] },
  splitDc: { label: 'DC trenches side by side', unit: '', min: 0, max: 6, int: true },
  splitBranch: { label: 'AC branch trenches side by side', unit: '', min: 0, max: 6, int: true },
  splitCollector: { label: 'collector trenches side by side', unit: '', min: 0, max: 6, int: true },
  splitMv: { label: '33 kV trenches side by side', unit: '', min: 0, max: 6, int: true },
  coverDc: { label: 'DC cover', unit: 'm', min: 0.3, max: 2 },
  coverLv: { label: 'LV AC cover', unit: 'm', min: 0.3, max: 2 },
  coverMv: { label: '33 kV cover', unit: 'm', min: 0.3, max: 2 },
  drumM: { label: 'cable drum length', unit: 'm', min: 100, max: 3000 },
  ring: { label: '33 kV ring rating case', choices: ['n-1', 'normal'] }
});
/** trench split <kind> N and trench cover <kind> N: the kind named and the setting it sets. */
export const SPLIT_KINDS = Object.freeze({ dc: 'splitDc', branch: 'splitBranch', collector: 'splitCollector', mv: 'splitMv' });
export const COVER_KINDS = Object.freeze({ dc: 'coverDc', lv: 'coverLv', ac: 'coverLv', mv: 'coverMv' });

export const TRENCH_COMMANDS = Object.freeze([
  { verb: 'trench', usage: 'trench depth 1.1  ·  trench width 0.6  ·  trench ac trefoil|flat  ·  trench design  ·  trench split collector 4'
    + '  ·  trench cover dc 0.91  ·  trench drum 800  ·  trench ring n-1|normal',
    words: 'cable trench cover containment sized rating width options side by side drum joint ring outage' },
  { verb: 'cable', usage: 'cable 400 al  ·  cable rate 400 al 28 circuits  ·  cable rate 400 al 28 circuits pitch 0.25',
    words: 'conductor size aluminium copper rating ampacity grouping current' },
  { verb: 'load', usage: 'load continuous  ·  load solar-day', words: 'load profile cyclic daily solar day rating loss factor' },
  { verb: 'xray', usage: 'xray on  ·  xray off', words: 'x-ray as built buried see through ground trenches ducts cables backfill' }
]);
export const TRENCH_VOCAB = Object.freeze({
  trench: ['depth', 'width', 'ac', 'trefoil', 'flat', 'design', 'split', 'cover', 'dc', 'lv', 'mv', 'branch', 'collector', 'drum', 'ring', 'n-1', 'normal'],
  cable: ['al', 'cu', 'rate', 'circuits', 'circuit', 'pitch', 'lv', 'mv', 'dc'], load: ['continuous', 'solar-day'], xray: ['on', 'off'] });

const isNum = t => t && typeof t === 'object' && Number.isFinite(t.n);

/** parseTrench(v, rest, out, { has, after, num, put, bad, guard }): fills out.set / out.act / out.arg, or pushes refusals on bad. */
export function parseTrench(v, rest, out, { has, after, num, put, bad, guard }) {
  if (v === 'trench') {
    if (has('design')) { out.act = 'trench-design'; return; }
    if (has('split')) {
      const k = Object.keys(SPLIT_KINDS).find(w => has(w));
      if (!k) bad.push(`trench split names the kind: trench split collector 4 (${Object.keys(SPLIT_KINDS).join(', ')}; 0 lets the rating choose)`);
      else num(rest.indexOf(k) + 1, SPLIT_KINDS[k]);
      out.act = 'trench-design'; return;
    }
    if (has('cover')) {
      const k = ['dc', 'lv', 'mv', 'ac'].find(w => has(w));
      if (!k) bad.push('trench cover names the kind: trench cover dc 0.91 (dc, lv or mv)');
      else num(rest.indexOf(k) + 1, COVER_KINDS[k], ['m']);
      out.act = 'trench-design'; return;
    }
    if (has('drum')) { num(after('drum'), 'drumM', ['m']); out.act = 'trench-design'; return; }
    if (has('ring')) {
      const w = rest.find(x => x === 'n-1' || x === 'normal');
      if (w) put('ring', w); else bad.push('trench ring is n-1 (rated with one ring end out) or normal');
      out.act = 'trench-design'; return;
    }
    if (after('depth') > 0) num(after('depth'), 'depth', ['m']);
    if (after('width') > 0) num(after('width'), 'width', ['m']);
    if (has('trefoil')) put('formation', 'trefoil');
    if (has('flat')) put('formation', 'flat');
    if (!Object.keys(out.set).length && !bad.length) bad.push('trench takes depth, width or a formation: trench depth 1.1, trench width 0.6, trench ac trefoil');
    return;
  }
  if (v === 'cable') {
    if (has('rate')) {
      const nums = rest.filter(isNum), ic = rest.indexOf('circuits') >= 0 ? rest.indexOf('circuits') : rest.indexOf('circuit'), ip = after('pitch');
      const size = nums[0], count = ic > 0 && isNum(rest[ic - 1]) ? rest[ic - 1].n : 1, pitch = ip > 0 && isNum(rest[ip]) ? rest[ip].n : null;
      const kind = has('mv') ? 'mv' : has('dc') ? 'dc' : 'lv';
      if (!size) bad.push('cable rate needs a size, such as cable rate 400 al 28 circuits');
      else if (kind !== 'dc' && guard('size', size.n)) bad.push(guard('size', size.n));
      if (!(count >= 1 && count <= 60 && Math.round(count) === count)) bad.push(`circuits must be a whole number from 1 to 60; you typed ${count}`);
      if (pitch !== null && !(pitch >= 0.05 && pitch <= 3)) bad.push(`pitch between circuits must be 0.05 to 3 m; you typed ${pitch}`);
      out.act = 'rate'; out.arg = { size: size?.n, metal: has('cu') ? 'cu' : 'al', circuits: count, pitchM: pitch, kind };
      return;
    }
    const n = rest.find(isNum);
    if (n) put('size', n.n); else bad.push('cable needs a size in mm², such as cable 400 al');
    put('metal', has('cu') ? 'cu' : 'al');
    return;
  }
  if (v === 'load') { const w = rest.find(x => x === 'continuous' || x === 'solar-day'); if (w) put('load', w); else bad.push('load is continuous or solar-day'); return; }
  if (v === 'xray') { out.act = 'xray'; out.arg = { on: !has('off') }; }
}

Cmd Trench

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

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

Evidence
  • line-jaccard 0.9802 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cmd-trench.mjs:1-119 76b8793066328ffae3f238213e8e48b35e8cd552
  • sha256 4342250cf7ea2070df3aa7183e65ab40d22a4738b510dbf2c573b039d0d37402
  • target sha256 85e1d386116e73b390e120806b12cff75b5333f2f89754efde1d16f85f2653ee
  • 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/cmd-trench.mjs · lines 1–121 of 121 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern designText (shared by 3 files)

What it does
It calculates cables, solar and 33kV. Defines 12 functions or classes, including trenchEnv, envFor, f, pct, tight.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'trench'): 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, solar, 33kV, 132kV.
Inputs & outputs
Voltage levels named: 132kV, 33kV.
Downstream impact
Used directly by 1 file: Cmd Model (globalgrid2050).
What it achieves
It rates text (`rateText`) and is built from the trench env helper (`trenchEnv`) and the env for helper (`envFor`). The command line's trench and cable words, as text. Its code works with 33 kV and 132 kV.
Why it matters
Imported by Cmd Model.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Cable IEC (import), Cable Rating (import), LV DC Sizing (import), Fault Level (import), Trench Plan (import), Station (import), Block Trenches (import), Block MV (import), and 1 more
Used by
imported by Cmd Model (import)
Produces
TRENCH_KEYS, TRENCH_DEFAULTS, trenchEnv, specOf, rateText, designText
Defines here
trenchEnv, envFor, f, pct, tight, specOf, rateText, basis, blockPlan, designText, line, busiest
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/cmd-trench.mjs:1-121 · blob 4ff1066b93af1948637624016a5edca89b96fa64 · 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 cmd-trench.mjs at v12 commit 3adcee9 (file last changed 604729d). Modular star family: public #148279 trenchEnv.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-trench.mjs: the command line's trench and cable words, as text. Pure: the numbers come from the rating cartridges.
//   cable rate 400 al 28 circuits [pitch 0.25] [lv|mv|dc]   one group of circuits rated together, the BS 7671 433.1 overload
//                                                          check (lv-dc-sizing.mjs) and the trench that carries them
//   trench design                                          the solar block's trenches as sized, or the block's two cases
// One rating path: cable rate and trench design both rate through trench-plan.mjs (trench-design.mjs, the IEC 60287 method
// in our own code) with the same cable build, so one case gives one answer. Standards are cited by number and clause only;
// every value is our own computation or a labelled assumption.

import { PRESETS } from './cable-iec.mjs';
import { build as mvBuild } from './cable-rating.mjs';
import { chooseIn, coordinate, faultArea } from './lv-dc-sizing.mjs';
import { transformerFaultKA, TX_FAULT } from './fault-level.mjs';
import { sizeTrench, checkAsDrawn, LOADS, PLAN_DEFAULTS, ILLUSTRATIVE } from './trench-plan.mjs';
import { STATION_DEFAULTS as SD } from './station.mjs';
import { BLOCK_DC_ISC_A, blockTrenches } from './block-trenches.mjs';
import { station } from './station.mjs';
import { mvChain } from './block-mv.mjs';
import { kvForMW } from './sld-connect.mjs';

export const TRENCH_KEYS = Object.freeze(['soil', 'load', 'splitDc', 'splitBranch', 'splitCollector', 'splitMv', 'coverDc', 'coverLv', 'coverMv',
  'drumM', 'ring']);
/** The typed trench settings' defaults (cmd-model.mjs DEFAULTS): the same values the block is built with. */
export const TRENCH_DEFAULTS = Object.freeze({ splitDc: 0, splitBranch: 0, splitCollector: 0, splitMv: 0, coverDc: PLAN_DEFAULTS.cover.dc,
  coverLv: PLAN_DEFAULTS.cover.lv, coverMv: PLAN_DEFAULTS.cover.mv, drumM: PLAN_DEFAULTS.drumM, ring: 'n-1' });
/** The typed sizing inputs, as trench-plan.mjs and block-build.mjs take them. */
export const trenchEnv = st => ({ soilKmW: st.soil, load: st.load,
  split: { dc: st.splitDc ?? 0, branch: st.splitBranch ?? 0, collector: st.splitCollector ?? 0, mv: st.splitMv ?? 0 },
  cover: { dc: st.coverDc ?? PLAN_DEFAULTS.cover.dc, lv: st.coverLv ?? PLAN_DEFAULTS.cover.lv, mv: st.coverMv ?? PLAN_DEFAULTS.cover.mv },
  drumM: st.drumM ?? PLAN_DEFAULTS.drumM, ring: st.ring ?? 'n-1' });
// The environment for one kind of run: its own typed split (the block's collector for LV, as in trench design).
const envFor = (st, kind) => { const e = trenchEnv(st); return { ...e, split: e.split[kind === 'lv' ? 'collector' : kind] }; };

const f = (v, d = 2) => (Number.isFinite(v) ? v.toLocaleString('en-GB', { minimumFractionDigits: d, maximumFractionDigits: d }) : '–');
const pct = v => `${Math.round(v * 100)} %`;
const BLOCK_LV_A = SD.inverterKVA * 1000 / (Math.sqrt(3) * SD.acVolts);   // the block's inverter at full output
const FOOT = `${ILLUSTRATIVE} (IEC 60287 method, own code; not for construction.)`;
const tight = z => (z.tight ? ' (tight: little margin)' : '');

/** One cable, one build: the block's own 400 mm² Al where that is the cable, so cable rate and trench design agree. */
export function specOf(kind, size, metal, loadA) {
  if (kind === 'dc') return { loadA, areaMm2: size, odMm: size <= 6 ? 6 : 7.2 };
  if (kind === 'mv') return { loadA, areaMm2: size, odMm: mvBuild(size).od, material: metal };
  const block = size === SD.acAreaMm2 && metal === 'al';
  const od = block ? SD.acDiameter * 1000 : PRESETS.lvAl(size, metal === 'cu' ? { cond: { mat: 'Cu', area: size } } : {}).od;
  return { loadA, areaMm2: size, odMm: od, material: metal };
}

/**
 * rateText({ size, metal, circuits, pitchM, kind }, st) -> words. kind: 'lv' (default: the block's 800 V inverter
 * circuits), 'mv' (33 kV, rating only) or 'dc' (string cables, 12 in a duct, n ducts).
 */
export function rateText({ size, metal = 'al', circuits = 1, pitchM = null, kind = 'lv' }, st) {
  const head = `${circuits} × ${size} mm² ${metal === 'cu' ? 'Cu' : 'Al'}`;
  if (kind === 'dc') {
    const loadA = 1.25 * BLOCK_DC_ISC_A, spec = specOf('dc', size, metal, loadA), env = envFor(st, 'dc'), z = sizeTrench('dc', circuits, spec, env);
    const drawn = pitchM ? checkAsDrawn('dc', circuits, spec, pitchM, env) : null;
    return [`DC ${head}: ${circuits} duct${circuits > 1 ? 's' : ''} of 12 string cables each, ${f(loadA, 1)} A a cable = 1.25 × Isc ${BLOCK_DC_ISC_A} A `
      + '(assumed; IEC 62548-1 cl. 7.2):',
    drawn ? `at ${f(pitchM)} m pitch the hottest cable runs at ${pct(drawn.utilisation)} of its rating (${drawn.hottestC} °C).` : '',
    `Needs: ${z.name}, ${f(z.widthM)} m wide, cover ${f(z.cover)} m, ${pct(z.utilisation)} loaded${tight(z)}.`, basis(st), FOOT].filter(Boolean).join('\n');
  }
  const Ib = kind === 'mv' ? 1 : BLOCK_LV_A, spec = specOf(kind, size, metal, Ib), env = envFor(st, kind), pitch = pitchM ?? (kind === 'mv' ? 0.45 : 0.25);
  const one = checkAsDrawn(kind, 1, spec, pitch, env).ratingA, grp = checkAsDrawn(kind, circuits, spec, pitch, env).ratingA;
  const lines = [`${kind === 'mv' ? '33 kV' : 'LV'} ${head} trefoils, ${f(pitch)} m apart, ${f(env.cover[kind])} m cover, soil ${f(st.soil, 1)} K.m/W, `
    + `${st.load} load:`,
  `one circuit alone carries ${Math.round(one)} A${circuits > 1 ? `; ${circuits} together carry ${Math.round(grp)} A each (${pct(grp / one)} of alone)` : ''}.`];
  if (kind === 'lv') {
    const In = chooseIn(Ib, { device: 'mccb', adjustable: true, setStep: 5 }), co = coordinate({ Ib, In, Iz: grp, device: 'mccb' });
    const kA = transformerFaultKA(), need = faultArea(metal, kA, TX_FAULT.seconds);
    lines.push(`Inverter circuit Ib ${Math.round(Ib)} A (${SD.inverterKVA} kVA at ${SD.acVolts} V): ${pct(Ib / grp)} of the grouped rating.`,
      `BS 7671 433.1 / IEC 60364-4-43: ${co.checks.map(c => `${c.name} ${c.ok ? 'yes' : 'NO'}`).join(' · ')} (breaker set to ${In} A).`,
      `LV board fault level about ${Math.round(kA)} kA (${TX_FAULT.mva} MVA at ${TX_FAULT.zPct} % impedance assumed, plus the inverters; impedance method): `
      + `${size} mm² needs ${Math.round(need)} mm² for ${TX_FAULT.seconds} s, ${size >= need ? 'yes' : 'NO'} (BS 7671 434.5.2).`);
    const z = sizeTrench('lv', circuits, spec, env);
    lines.push(`Trench that carries them: ${z.name}, ${f(z.widthM)} m wide${z.trenches > 1 ? ` each, ${f(z.corridorM)} m corridor` : ''}, `
      + `${pct(z.utilisation)} loaded${z.ok ? '' : ' (still over: a larger conductor)'}${tight(z)}.`);
  }
  lines.push(basis(st), FOOT);
  return lines.join('\n');
}

const basis = st => `Soil ${f(st.soil, 1)} K.m/W, ground 15 °C, conductor 90 °C; load ${st.load}${st.load === 'solar-day'
  ? ` (loss-load factor ${f(LOADS['solar-day'])}, no clipping: optimistic where inverters clip; continuous is the BS 7671 compliance basis)` : ''}.`;

// The block's own layout for the typed inputs, as block 10mva builds it (no ground needed for the plan): one source.
let planMemo = { key: '', plan: null };
function blockPlan(st) {
  const env = trenchEnv(st), key = JSON.stringify([env, st.pocKv]);
  if (planMemo.key !== key) {
    // Connection voltage as block 10mva picks it: the typed one, else by plant size (sld-connect.mjs), 132 kV at least.
    const s = station(null, { corners: false }), stationMVA = s.inventory.aggregateInverterMVA;
    const pocKv = [132, 275, 400].includes(st.pocKv) ? st.pocKv : kvForMW(mvChain({ stations: 1, stationMVA, pocKv: 132 }).exportMW, { minKv: 132 });
    const mv = mvChain({ stations: 1, stationMVA, pocKv });
    planMemo = { key, plan: blockTrenches(s, mv, 0, 0, a => mvBuild(a).od, env) };
  }
  return planMemo.plan;
}

/**
 * designText(st, rows) -> words: the placed block's sized trenches (rows from block-ui), or, with no block, the same
 * block's layout for the typed inputs, and the options for its busiest collector stretch and busiest DC stretch.
 */
export function designText(st, rows = null) {
  const line = ([k, v, cls]) => `${k ? k + ': ' : '  '}${cls === 'fault' && !['Design fault', 'Not rated'].includes(k) ? '[OVER] ' : ''}${v}`;
  if (rows?.length) return ['Solar block trenches, sized by rating:', ...rows.map(line)].join('\n');
  const b = blockPlan(st), out = ['No block placed (type block 10mva). The block\'s trenches as it would be built:',...b.plan.rows.map(line)];
  const busiest = g => b.items.filter(t => t.group === g).reduce((a, t) => (t.n > a.n ? t : a));
  for (const [kind, t, what, pitch] of [['lv', busiest('collector'), 'inverter circuits on the busiest collector stretch', 0.25],
    ['dc', busiest('dc'), 'DC ducts on the busiest DC stretch', SD.ductSpacing]]) {
    const env = envFor(st, kind), z = sizeTrench(kind, t.n, t.spec, env), d = checkAsDrawn(kind, t.n, t.spec, pitch, env);
    out.push(`${t.n} ${what}, cover ${f(z.cover)} m: at the original drawn pitch (${f(pitch)} m) ${pct(d.utilisation)} loaded.`,
      ...z.options.filter(o => o.layers === 1 || o.trenches === 1).map(o => `  ${o.name === z.name ? '→' : ' '} ${o.name}: ${f(o.widestM)} m wide, `
        + `corridor ${f(o.corridorM)} m, ${f(o.dugM3PerM)} m³ dug per metre, ${pct(o.utilisation)} loaded${o.ok ? '' : ' (over)'}`
        + `${o.name === z.name ? tight(z) : ''}`));
  }
  out.push('Type trench split collector 2 (or dc, branch, mv) to choose trenches side by side; trench cover dc 0.91, soil 1.5 or load solar-day '
    + 'to change the inputs.', basis(st), FOOT);
  return out.join('\n');
}