GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / globalgrid2050 / solar-design-studio/202609271740-site-world/world

Trench Plan and 3 more files

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

626 lines of JavaScript from globalgrid2050, in 4 files. Topic: Cables and conductors. Section 24 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. Cmd Grammar Trench ingest · globalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-grammar-trench.mjs lines 1–85
  2. Cmd Trench transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-trench.mjs lines 1–119
  3. Trench Plan transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/trench-plan.mjs lines 1–263
  4. Block Trenches transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/block-trenches.mjs lines 1–159

Cmd Grammar Trench

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

ingestglobalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-grammar-trench.mjs · lines 1–85 of 85 · version 2026-09-27 17:40 · 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 'design'): 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). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (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 · solar-design-studio/202609271740-site-world/world · 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 solar-design-studio/202609271740-site-world/world/cmd-grammar-trench.mjs:1-85 · blob 7bfe43d5cd0e2c5f71806a066f61f59e60c009d6 · 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: production_core
// 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 world folder of GlobalGrid2050 that works with cables, solar and 33kV, using BS 7671 and IEC 60287.

transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-trench.mjs · lines 1–119 of 119 · version 2026-09-27 17:40 · 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 'design'): 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). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (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 · solar-design-studio/202609271740-site-world/world · 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 solar-design-studio/202609271740-site-world/world/cmd-trench.mjs:1-119 · blob 76b8793066328ffae3f238213e8e48b35e8cd552 · 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: production_core
// 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');
}

Trench Plan

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

transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/trench-plan.mjs · lines 1–263 of 263 · version 2026-09-27 17:40 · pattern corridorCheck (shared by 3 files)

What it does
It calculates cables, solar and 33kV. Defines 14 functions or classes, including splitOf, coverOf, r2, sizeTrench, optionFor.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): 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 3 files: Cmd Trench (globalgrid2050); Block Trenches (globalgrid2050); Plant Feeders (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It sizes trench (`sizeTrench`), checks as drawn (`checkAsDrawn`) and turns deg (`turnDeg`). Loss-load factor by load profile: continuous (the default, conservative) or a clear solar day, unclipped. Its code works with 33 kV.
Why it matters
Imported by Cmd Trench, Block Trenches and Plant Feeders.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Trench Design (import), Cable IEC (import)
Used by
imported by Cmd Trench (import), imported by Block Trenches (import), imported by Plant Feeders (import)
Produces
LOADS, PLAN_DEFAULTS, COVER_WHY, CIRCUIT, sizeTrench, checkAsDrawn, corridorCheck, offsetPath, planTrenches, ILLUSTRATIVE, planRows
Defines here
splitOf, coverOf, r2, sizeTrench, optionFor, checkAsDrawn, corridorCheck, worst, offsetPath, turnDeg, at, planTrenches, pctOf, planRows
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/trench-plan.mjs:1-263 · blob c0156ba112940c5c9be1a9373071686921d5bbb4 · 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: production_core
// trench-plan.mjs: trenches sized by the rating of the cables in them, for the solar block and the plant feeders.
//
// Given what a trench carries (DC string ducts, LV AC inverter trefoils or 33 kV trefoils: how many, what cable, what
// load), sizeTrench() asks trench-design.mjs for the arrangements that keep every conductor within its temperature
// (one trench, two layers, several trenches side by side) and picks one: the typed split, or else the least dig that
// one bucket pass can open, or else the least dig. planTrenches() applies that to a set of trench runs: it widens or
// splits each run, puts draw pits at every turn of a ducted run and where the pulling tension would pass its limit,
// joint bays at drum lengths, and sums the metres, volumes, pits and bays for the readout and the bill of quantities.
//
// Method: the IEC 60287 thermal method (own code, trench-design.mjs; cable-iec.mjs for the daily solar cycle).
// Standards are cited by number only; no values from any standard. Loads and cable builds are labelled assumptions.
// Pure: no DOM.

import { designOptions, solveGap, section as sectionOf, pullPlan, place, temperatures, PULL, COVER } from './trench-design.mjs';
import { solarDayProfile, lossLoadFactor } from './cable-iec.mjs';

/** Loss-load factor by load profile: continuous (the default, conservative) or a clear solar day, unclipped. */
export const LOADS = Object.freeze({ continuous: 1, 'solar-day': lossLoadFactor(solarDayProfile()) });

export const PLAN_DEFAULTS = Object.freeze({
  soilKmW: 1.2,            // native ground, moist (generic rule; measure on site)
  load: 'continuous',      // or 'solar-day'
  split: 0,                // 0: choose; n: n trenches side by side; or per kind { dc, branch, collector, mv } (the block)
  cover: Object.freeze({ dc: 0.6, lv: 0.91, mv: 0.91 }),   // m to the top of the uppermost duct or cable, by kind; editable
  betweenM: 1.0,           // undisturbed ground between parallel trenches
  drumM: 800,              // cable on one drum: a joint bay each time a circuit passes this length (input)
  tight: 0.95              // a chosen trench at or over this share of its rating is shown as tight
});
/** Why each kind's default cover is what it is (shown beside the number; typed: trench cover dc 0.91). */
export const COVER_WHY = Object.freeze({
  dc: 'inside the fenced array, not cultivated: a design choice to agree (0.91 m if grazed or ploughed later)',
  lv: 'farmland, typical UK practice', mv: 'farmland, typical UK practice' });
const splitOf = (split, group) => (typeof split === 'number' ? split : split?.[group] ?? 0);
const coverOf = (e, kind) => (typeof e.cover === 'number' ? e.cover : e.cover?.[kind] ?? PLAN_DEFAULTS.cover[kind]);

// One circuit of each kind, in trench-design.mjs form. Builds and loads are assumptions, each overridable.
export const CIRCUIT = Object.freeze({
  lv: (i, s) => ({ id: `ac${i + 1}`, cls: 'lv', formation: 'trefoil', loadA: s.loadA,
    cable: { material: s.material ?? 'al', areaMm2: s.areaMm2 ?? 400, odMm: s.odMm ?? 37.4, kind: 'ac' } }),
  mv: (i, s) => ({ id: `mv${i + 1}`, cls: 'mv', formation: 'trefoil', loadA: s.loadA,
    cable: { material: s.material ?? 'al', areaMm2: s.areaMm2 ?? 300, odMm: s.odMm ?? 45, kind: 'ac', screenMm2: 35, u0Kv: 19 } }),
  dc: (i, s) => ({ id: `d${i + 1}`, cls: 'dc', formation: 'duct-bundle', loadA: s.loadA, ductOdMm: s.ductOdMm ?? 90, perDuct: s.perDuct ?? 12,
    cable: { material: 'cu', areaMm2: s.areaMm2 ?? 6, odMm: s.odMm ?? 6, kind: 'dc', flexible: true, insulationMm: 0.7, sheathMm: 0.8 } })
});
const LABEL = { lv: 'LV AC, single-core Al trefoils', mv: '33 kV AC, single-core Al trefoils', dc: 'DC string cables in ducts' };

const memo = new Map();
const r2 = x => Math.round(x * 100) / 100;

/**
 * sizeTrench(kind, n, spec, env) -> { kind, n, trenches, layers, widthM, depthM, corridorM, cover, gapM, ok, utilisation,
 *   hottestC, perMetre, section, options, basis }
 * kind 'lv' | 'mv' | 'dc'; n circuits (DC: ducts); spec { loadA, areaMm2, odMm, ductOdMm, perDuct }.
 */
export function sizeTrench(kind, n, spec, env = {}) {
  const e = { ...PLAN_DEFAULTS, ...env }, key = JSON.stringify([kind, n, spec, e]), split = splitOf(e.split, kind);
  if (memo.has(key)) return memo.get(key);
  const circuits = Array.from({ length: n }, (_, i) => CIRCUIT[kind](i, spec));
  const tenv = { soilKmW: e.soilKmW, mu: LOADS[e.load] ?? 1, betweenTrenchesM: e.betweenM };
  const d = designOptions({ circuits, coverM: coverOf(e, kind), env: tenv, maxTrenches: Math.min(n, Math.max(6, split)) });
  // Chosen: one layer (two only as an option shown), the least dig one bucket pass can open, else the least dig.
  const ok = d.options.filter(o => o.ok && !o.conductor && o.layers === 1);
  const pool = ok.filter(o => o.fitsOneBucket).length ? ok.filter(o => o.fitsOneBucket) : ok;
  let pick = pool.sort((a, b) => a.perMetre.dugBank - b.perMetre.dugBank || a.trenches - b.trenches)[0]
    || d.options.filter(o => !o.conductor && o.layers === 1).sort((a, b) => b.ratingFactor - a.ratingFactor)[0];
  // A typed split applies to the kind it names (planTrenches passes each run its own), never beyond one circuit a trench.
  if (split > 0 && Math.min(n, split) !== pick.trenches) {
    const want = Math.min(n, split);
    pick = d.options.find(o => o.trenches === want && o.layers === 1 && !o.conductor) || optionFor(circuits, want, d.cover, tenv);
  }
  const t0 = pick.sections[0], od = (kind === 'dc' ? spec.ductOdMm ?? 90 : spec.odMm ?? (kind === 'mv' ? 45 : 37.4)) / 1000;
  const foot = kind === 'dc' ? od : 2 * od, mv = kind === 'mv';
  const section = {
    id: `${kind}-sized-${n}`, voltage_class: LABEL[kind], status: 'sized by rating (IEC 60287 method, own code)',
    formation: kind === 'dc' ? 'ducts side by side, one layer' : 'trefoil, direct buried', circuits: t0.circuits,
    cover_to_top_m: t0.coverToTop, trench_width_m: r2(t0.width), trench_depth_m: Math.round(t0.depth * 1000) / 1000,
    phase_spacing_mm: Math.round(od * 1000), circuit_spacing_mm: Math.round((foot + pick.gapM) * 1000),
    bedding: { material: 'sand or stone-free soil', thickness_mm: 75 },
    marker: mv ? { type: 'protection tile over the cables', depth_m: t0.surroundTop } : { type: 'warning tape', depth_m: t0.markers.at(-1).depth },
    ...(kind === 'dc' ? { duct_od_mm: Math.round(od * 1000) } : {})
  };
  const out = {
    kind, n, trenches: pick.trenches, layers: pick.layers, widthM: pick.widestM, depthM: pick.deepestM, corridorM: pick.corridorM,
    cover: d.cover, coverWhy: COVER_WHY[kind], gapM: pick.gapM, ok: pick.ok, utilisation: pick.ratingFactor > 0 ? r2(1 / pick.ratingFactor) : Infinity,
    tight: pick.ok && pick.ratingFactor > 0 && 1 / pick.ratingFactor >= e.tight,
    hottestC: pick.hottestC, perMetre: pick.perMetre, section, name: pick.name, load: e.load, soilKmW: e.soilKmW,
    options: d.options.map(o => ({ name: o.name, ok: o.ok, trenches: o.trenches, layers: o.layers, widestM: o.widestM, corridorM: o.corridorM,
      dugM3PerM: o.perMetre.dugBank, utilisation: o.ratingFactor > 0 ? r2(1 / o.ratingFactor) : Infinity, conductor: o.conductor || null })),
    basis: `cover ${d.cover} m (${COVER_WHY[kind]}); ${COVER.basis}; soil ${e.soilKmW} K.m/W, ${e.load} load`
  };
  memo.set(key, out);
  if (memo.size > 400) memo.delete(memo.keys().next().value);
  return out;
}

// An arrangement designOptions did not try (a typed split beyond its list): solved and sized the same way.
function optionFor(circuits, trenches, cover, tenv) {
  const s = solveGap(circuits, { cover, trenches, layers: 1 }, tenv), sec = sectionOf(s, circuits, tenv);
  const per = {};
  for (const t of sec) for (const [k, v] of Object.entries(t.perMetre)) per[k] = (per[k] || 0) + v;
  return { name: `${trenches} trenches side by side`, ok: s.ok, trenches, layers: 1, gapM: s.gapM, sections: sec, perMetre: per,
    widestM: Math.max(...sec.map(t => t.width)), deepestM: Math.max(...sec.map(t => t.depth)), corridorM: r2(s.layout.corridor),
    hottestC: Math.round(s.thermal.hottest.temp * 10) / 10, ratingFactor: s.thermal.factor };
}

/** The drawn trench checked as it stands: n circuits at the drawn centre pitch. -> { utilisation, hottestC } */
export function checkAsDrawn(kind, n, spec, pitchM, env = {}) {
  const e = { ...PLAN_DEFAULTS, ...env }, sized = sizeTrench(kind, n, spec, env);
  const circuits = Array.from({ length: n }, (_, i) => CIRCUIT[kind](i, spec));
  const foot = (kind === 'dc' ? spec.ductOdMm ?? 90 : 2 * (spec.odMm ?? 37.4)) / 1000;
  const s = solveGap(circuits, { cover: sized.cover, trenches: 1, layers: 1, minGapM: Math.max(0, pitchM - foot) },
    { soilKmW: e.soilKmW, mu: LOADS[e.load] ?? 1 }, { maxGapM: Math.max(0, pitchM - foot) + 1e-6 });
  return { utilisation: r2(1 / s.thermal.factor), hottestC: Math.round(s.thermal.hottest.temp), pitchM, ratingA: spec.loadA * s.thermal.factor };
}

/**
 * corridorCheck(parts, env) -> { utilisation, hottestC, parts: [utilisation] }: sized trenches laid side by side in one
 * corridor, rated as one thermal problem so each part's heat reaches the others (what separate sizings leave out).
 * parts: [{ kind, n, spec, sized (sizeTrench), sepM (undisturbed ground before the next part) }].
 */
export function corridorCheck(parts, env = {}) {
  const e = { ...PLAN_DEFAULTS, ...env }, circuits = [], gaps = [], betweens = [], covers = [];
  let t0 = 0;
  parts.forEach((p, pi) => {
    const z = p.sized;
    for (let i = 0; i < p.n; i++) circuits.push({ ...CIRCUIT[p.kind](i, p.spec), id: `${pi}:${i}`, trench: t0 + (i % z.trenches) });
    for (let k = 0; k < z.trenches; k++) { gaps.push(z.gapM); covers.push(z.cover); betweens.push(k < z.trenches - 1 ? e.betweenM : p.sepM ?? e.betweenM); }
    t0 += z.trenches;
  });
  const layout = place(circuits, { cover: covers[0], covers, gaps, betweens, trenches: t0, layers: 1 });
  const th = temperatures(layout, { soilKmW: e.soilKmW, mu: LOADS[e.load] ?? 1 });
  const worst = pi => Math.max(...th.perCircuit.filter(c => c.id.startsWith(`${pi}:`)).map(c => 1 / c.factor));
  return { utilisation: r2(1 / th.factor), hottestC: Math.round(th.hottest.temp), parts: parts.map((_, pi) => r2(worst(pi))), corridorM: r2(layout.corridor) };
}

/** A plan polyline [[x, y]...] moved sideways by d metres (left of travel positive), corners mitred. */
export function offsetPath(pts, d) {
  if (!d) return pts.map(p => p.slice());
  const n = pts.length, nrm = i => { const a = pts[i], b = pts[i + 1], l = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; return [-(b[1] - a[1]) / l, (b[0] - a[0]) / l]; };
  return pts.map((p, i) => {
    const a = nrm(Math.max(0, i - 1)), b = nrm(Math.min(n - 2, i)), m = [a[0] + b[0], a[1] + b[1]], k = (m[0] * b[0] + m[1] * b[1]) || 1;
    return [p[0] + m[0] * d / k, p[1] + m[1] * d / k];
  });
}

const turnDeg = (a, b, c) => {
  const u = Math.atan2(b[1] - a[1], b[0] - a[0]), v = Math.atan2(c[1] - b[1], c[0] - b[0]);
  let t = Math.abs(u - v) % (2 * Math.PI); if (t > Math.PI) t = 2 * Math.PI - t;
  return t * 180 / Math.PI;
};
const at = (pts, s) => {           // the point s metres along a polyline
  for (let i = 1, run = 0; i < pts.length; i++) {
    const L = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    if (run + L >= s - 1e-9) { const k = L ? (s - run) / L : 0; return [pts[i - 1][0] + k * (pts[i][0] - pts[i - 1][0]), pts[i - 1][1] + k * (pts[i][1] - pts[i - 1][1])]; }
    run += L;
  }
  return pts.at(-1).slice();
};

/**
 * planTrenches(runs, env, { hops }) -> { items, pits, joints, summary, totals, env }
 * runs: [{ stage, path: [[x, y]...] plan metres, kind, n, spec, group?, ducted?, drawnPitchM?, takeOffs?: [[x, y]] }]
 *   group names the typed split that applies (dc, branch, collector, mv); takeOffs get a draw pit (ducts rise there).
 * hops: [{ stage, path }] cable routes end to end (the 33 kV circuits): a joint bay each time one passes the drum length.
 *   Runs of a stage that has hops take their joint bays from the hops, not from their own length.
 * items: one per trench dug (a split run gives several), { stage, path, section, sizing, cableOdMm, kind }.
 */
export function planTrenches(runs, env = {}, { hops = [] } = {}) {
  const e = { ...PLAN_DEFAULTS, ...env }, items = [], pits = [], joints = [], byStage = {}, hopStages = new Set(hops.map(h => h.stage));
  const pull = { ...PULL, drumM: e.drumM };
  for (const r of runs) {
    const renv = { ...env, split: splitOf(e.split, r.group ?? r.kind) };
    const z = sizeTrench(r.kind, r.n, r.spec, renv), w = z.section.trench_width_m, n = z.trenches, ducted = r.ducted ?? r.kind === 'dc';
    const drawn = r.drawnPitchM ? checkAsDrawn(r.kind, r.n, r.spec, r.drawnPitchM, renv) : null;
    for (let k = 0; k < n; k++) {
      const path = offsetPath(r.path, (k - (n - 1) / 2) * (w + e.betweenM));
      items.push({ stage: r.stage, kind: r.kind, group: r.group ?? r.kind, n: r.n, spec: r.spec, path, section: z.section, sizing: z, drawn, trench: k + 1, of: n,
        cableOdMm: r.kind === 'dc' ? r.spec.odMm ?? 6 : r.spec.odMm ?? 37.4, ducted });
    }
    // Pulls along the run's centreline: pits (ducted) at turns and at the tension limit, joint bays at drum lengths.
    const plan = pullPlan(r.path, CIRCUIT[r.kind](0, r.spec), { ducted, pull });
    for (const p of plan.pits) pits.push({ at: at(r.path, p.at), why: p.why, stage: r.stage, widthM: z.corridorM });
    for (const p of r.takeOffs || []) pits.push({ at: p.slice(), why: 'ducts rise to the inverter', stage: r.stage, widthM: z.corridorM });
    if (!hopStages.has(r.stage)) {
      for (const j of plan.jointBays) joints.push({ at: at(r.path, j.at), why: j.why, stage: r.stage, lengthM: 4, widthM: z.corridorM + 0.6 });
    }
    const L = r.path.slice(1).reduce((t, q, i) => t + Math.hypot(q[0] - r.path[i][0], q[1] - r.path[i][1]), 0);
    const s = byStage[r.stage] ||= { metres: 0, trenchM: 0, dugM3: 0, beddingM3: 0, widest: 0, worst: 0, notOk: 0, split: 1, drawnWorst: 0, tight: 0,
      cover: z.cover, coverWhy: z.coverWhy, corridor: 0 };
    s.metres += L; s.trenchM += L * n; s.dugM3 += L * z.perMetre.dugBank; s.beddingM3 += L * z.perMetre.beddingSurround;
    s.widest = Math.max(s.widest, w); s.worst = Math.max(s.worst, z.utilisation); s.notOk += z.ok ? 0 : 1; s.split = Math.max(s.split, n);
    s.tight += z.tight ? 1 : 0; s.corridor = Math.max(s.corridor, z.corridorM);
    if (drawn) s.drawnWorst = Math.max(s.drawnWorst, drawn.utilisation);
  }
  // Circuits end to end: a joint each drum length along each one; joints within 5 m of each other share one bay.
  for (const h of hops) {
    const L = h.path.slice(1).reduce((t, q, i) => t + Math.hypot(q[0] - h.path[i][0], q[1] - h.path[i][1]), 0);
    for (let d = e.drumM; d < L - 1; d += e.drumM) {
      const p = at(h.path, d), near = joints.find(j => j.stage === h.stage && Math.hypot(j.at[0] - p[0], j.at[1] - p[1]) < 5);
      if (near) near.circuits++;
      else joints.push({ at: p, why: `drum length (${e.drumM} m) along the circuit`, stage: h.stage, lengthM: 4, widthM: 2, circuits: 1 });
    }
  }
  // Ducted runs that meet end to end at an angle: a draw pit at the corner (the ducts turn there).
  const ends = runs.filter(r => r.ducted ?? r.kind === 'dc').flatMap(r => [[r.path[0], r.path[1], r], [r.path.at(-1), r.path.at(-2), r]]);
  for (let i = 0; i < ends.length; i++) for (let j = i + 1; j < ends.length; j++) {
    const [p, pn, ri] = ends[i], [q, qn, rj] = ends[j];
    if (ri === rj || Math.hypot(p[0] - q[0], p[1] - q[1]) > 0.5) continue;
    if (turnDeg(pn, p, qn) > 10) pits.push({ at: p.slice(), why: 'change of direction', stage: ri.stage });
  }
  // A ducted run whose end lands part-way along another ducted run (a T): the ducts turn into the run, so a pit there too.
  for (const r of runs.filter(x => x.ducted ?? x.kind === 'dc')) for (const p of [r.path[0], r.path.at(-1)]) {
    for (const o of runs) {
      if (o === r || !(o.ducted ?? o.kind === 'dc')) continue;
      for (let i = 1; i < o.path.length; i++) {
        const a = o.path[i - 1], b = o.path[i], dx = b[0] - a[0], dy = b[1] - a[1], L2 = dx * dx + dy * dy || 1;
        const k = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / L2));
        if (Math.hypot(a[0] + k * dx - p[0], a[1] + k * dy - p[1]) < 0.5 && k > 0.01 && k < 0.99) { pits.push({ at: p.slice(), why: 'junction', stage: r.stage }); break; }
      }
    }
  }
  // Pits closer than 2 m are one chamber (sized to the duct bank).
  const merged = [];
  for (const p of pits) {
    const m = merged.find(q => q.stage === p.stage && Math.hypot(q.at[0] - p.at[0], q.at[1] - p.at[1]) < 2);
    if (m) m.widthM = Math.max(m.widthM || 0, p.widthM || 0); else merged.push({ ...p });
  }
  for (const s of Object.values(byStage)) { s.pits = 0; s.joints = 0; }
  for (const p of merged) byStage[p.stage].pits++;
  for (const j of joints) if (byStage[j.stage]) byStage[j.stage].joints++;
  const all = Object.values(byStage), routeM = all.reduce((t, s) => t + s.metres, 0), dugM = all.reduce((t, s) => t + s.trenchM, 0);
  return { items, pits: merged, joints, summary: byStage, env: e, totals: { trenches: items.length, routeM, dugM, pits: merged.length, joints: joints.length } };
}

/** Every electrical readout carries this line. */
export const ILLUSTRATIVE = 'Illustrative — early design, no warranty; confirm with a qualified engineer.';
const pctOf = v => `${Math.round(v * 100)} %`;

/**
 * Readout rows for a plan, in words: [label, text, 'tight' | 'fault' | undefined]; tight and fault rows are the ones the
 * reader must look at (drawn amber and red). extra: { faults, unrated, notes: [text], totals } (totals override the plan's).
 */
export function planRows(plan, extra = {}) {
  const name = { dc: 'DC trenches', ac: 'AC trenches', mv: '33 kV trenches' }, rows = [];
  for (const [stage, s] of Object.entries(plan.summary)) {
    const drawn = s.drawnWorst ? ` · the original drawn pitch would load it to ${pctOf(s.drawnWorst)}` : '';
    const over = s.notOk ? ` (${s.notOk} run${s.notOk > 1 ? 's' : ''} over: larger conductor or split)` : '';
    rows.push([name[stage] || stage, `sized by rating: widest ${s.widest.toFixed(2)} m${s.split > 1 ? `, up to ${s.split} side by side` : ''}`
      + ` · worst cable ${pctOf(s.worst)} of rating${over}${drawn}`, s.notOk ? 'fault' : undefined]);
    if (s.tight) rows.push(['', `tight: ${s.tight} run${s.tight > 1 ? 's' : ''} at ${pctOf(plan.env.tight)} of rating or more; little margin for drier soil`, 'tight']);
    rows.push(['', `${Math.round(s.metres)} m of route, ${Math.round(s.trenchM)} m of trench dug · ${Math.round(s.dugM3)} m³ bank · bedding `
      + `${Math.round(s.beddingM3)} m³ · cover ${s.cover.toFixed(2)} m (${s.coverWhy})${s.pits ? ` · ${s.pits} draw pit${s.pits === 1 ? '' : 's'}` : ''}`
      + `${s.joints ? ` · ${s.joints} joint bay${s.joints === 1 ? '' : 's'}` : ''}`]);
  }
  for (const f of extra.faults || []) rows.push(['Design fault', f, 'fault']);
  for (const f of extra.unrated || []) rows.push(['Not rated', f, 'fault']);
  for (const n of extra.notes || []) rows.push(['', n]);
  const t = extra.totals || plan.totals;
  rows.push(['All trenches', `${t.trenches} trenches dug, ${Math.round(t.dugM)} m (on ${Math.round(t.routeM)} m of route) · `
    + `${t.pits} draw pit${t.pits === 1 ? '' : 's'} · ${t.joints} joint bay${t.joints === 1 ? '' : 's'}`]);
  rows.push(['Rating basis', `IEC 60287 method (own code), soil ${plan.env.soilKmW} K.m/W, ${plan.env.load} load. ${ILLUSTRATIVE}`]);
  return rows;
}

Block Trenches

A JavaScript module in the world folder of GlobalGrid2050 that works with 33kV, transformers, cables and solar.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/block-trenches.mjs · lines 1–159 of 159 · version 2026-09-27 18:53 · pattern hvSection (shared by 3 files)

What it does
It calculates 33kV, transformers, cables and solar. Defines 10 functions or classes, including sum, f2, stretches, hvSection, blockTrenches.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV, transformers, cables, solar.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 2 files: Cmd Trench (globalgrid2050); Block Build (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It is built from the sum step (`sum`), the stretches step (`stretches`) and the HV section helper (`hvSection`). The solar block's trenches, laid out from what each stretch of route really carries, then sized by rating (`trench-plan.mjs`). Its code works with 33 kV.
Why it matters
Imported by Cmd Trench and Block Build.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Station (import), Trench Plan (import)
Used by
imported by Cmd Trench (import), imported by Block Build (import)
Produces
BLOCK_DC_ISC_A, BLOCK_TRENCH, stretches, hvSection, blockTrenches
Defines here
sum, f2, stretches, hvSection, blockTrenches, envFor, mvaOf, whole, half, toEn
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/block-trenches.mjs:1-159 · blob 4f99893811fc31369524b0993cb7c6db934dfada · 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: production_core
// block-trenches.mjs: the solar block's trenches, laid out from what each stretch of route really carries, then sized by
// rating (trench-plan.mjs). One source of truth: the readout, the typed words, the X-ray and the bill of quantities all
// read what this returns.
//
// Layout rules (fixes to our own generator, not design choices):
//   - DC: the home-run ducts of each inverter row run in the aisle in front of the tables, north edge a clear distance
//     short of the first pile line, never under a table. Each stretch carries only the ducts that really pass it
//     (counted from the drawn home runs), so the corridor is as wide as the busiest stretch needs, not the row's total.
//   - AC branch: its own lane south of the DC corridor. The two lanes are rated together (corridorCheck: each lane's heat
//     reaches the other) and moved apart until neither is worse than alone; if the aisle cannot hold both, that is a
//     design fault and it is said in red, not hidden.
//   - Collector: one spine west of the transformers, cut into stretches by the circuits that really pass each one, so the
//     two transformers' circuits where they share a stretch are one group, sized together, never two overlapping trenches.
//   - 33 kV: each ring trench at the ring's load; with one ring end out (N-1, the default) the whole ring from one end.
//     Joint bays where a circuit passes the drum length along its own route.
//   - HV connection: the section follows the connection voltage; nothing above 33 kV is rated here (no cable data).
// Loads: inverter AC at full kVA; DC string current 1.25 x Isc (Isc assumed); all labelled assumptions.
// Pure: no DOM.

import { tableShape, tableOrigin, dcHomeRoutes, STATION_DEFAULTS as SD } from './station.mjs';
import { planTrenches, planRows, sizeTrench, corridorCheck, PLAN_DEFAULTS } from './trench-plan.mjs';

export const BLOCK_DC_ISC_A = 18.5;   // module short-circuit current, assumed: one value for the block and the typed words
export const BLOCK_TRENCH = Object.freeze({
  pileClearM: 0.5,     // clear ground between a trench wall and the nearest pile line (design choice)
  minStretchM: 2,      // a stretch shorter than this carries the larger count of its neighbours
  maxSepM: 4,          // the most ground tried between the DC and AC lanes before the heat is called a fault
  ring: 'n-1'          // 33 kV rings rated with one end out (whole ring from one end) or 'normal' (the larger half)
});
const sum = a => a.reduce((t, x) => t + x, 0);
const f2 = x => x.toFixed(2);

/** Stretches of a line from intervals [[a, b]...]: [{ a, b, n }] with n the intervals that cover it; short pieces merged. */
export function stretches(iv, minM = BLOCK_TRENCH.minStretchM) {
  const bp = [...new Set(iv.flatMap(([a, b]) => [a, b]))].sort((p, q) => p - q);
  const segs = bp.slice(1).map((b, i) => { const a = bp[i], m = (a + b) / 2; return { a, b, n: iv.filter(([p, q]) => p <= m && q >= m).length }; })
    .filter(s => s.b - s.a > 1e-6);
  for (let k = 0; k < segs.length;) {
    const s = segs[k];
    if (s.b - s.a >= minM || segs.length < 2) { k++; continue; }
    const nb = [segs[k - 1], segs[k + 1]].filter(q => q && (q.n > 0 || !s.n)), into = nb.sort((p, q) => q.n - p.n)[0];
    if (!into) { k++; continue; }
    into.n = Math.max(into.n, s.n); into.a = Math.min(into.a, s.a); into.b = Math.max(into.b, s.b);
    segs.splice(k, 1); k = Math.max(0, k - 1);
  }
  const out = [];
  for (const s of segs) { const p = out.at(-1); if (p && p.n === s.n && Math.abs(p.b - s.a) < 1e-6) p.b = s.b; else out.push({ ...s }); }
  return out.filter(s => s.n > 0);
}

/** The HV connection's section by voltage: an outline for the X-ray, never rated here (no cable data held). */
export function hvSection(kv) {
  const big = kv > 132, duct = kv > 132 ? 250 : 160, cableOdMm = kv >= 400 ? 145 : kv > 132 ? 125 : 105;
  return { cableOdMm, rated: false, section: {
    id: `hv-connection-${kv}kv`, voltage_class: big ? `${kv} kV connection: to the transmission owner's design` : `${kv} kV connection, fully ducted`,
    formation: big ? 'three ducts flat, spaced' : 'trefoil of three ducts', circuits: 1, cover_to_top_m: big ? 1.0 : 0.91,
    trench_width_m: big ? 1.4 : 0.8, trench_depth_m: big ? 1.6 : 1.4, duct_od_mm: duct, phase_spacing_mm: big ? 450 : duct,
    bedding: { thickness_mm: 100 }, marker: { type: 'protection tile layer', depth_m: big ? 0.85 : 0.8 },
    status: `UNRATED: outline only, duct ${duct} mm OD and cable about ${cableOdMm} mm OD assumed for ${kv} kV; no rating run` } };
}

/**
 * blockTrenches(st, mv, E, N, odMv, env, s) -> { items, plan: { pits, joints, summary, rows, env, totals, faults, notes } }
 * st: station(...); mv: mvChain(...); E, N: the anchor; odMv(area) the 33 kV cable OD; env: the typed sizing inputs
 * { soilKmW, load, split: { dc, branch, collector, mv }, cover: { dc, lv, mv }, drumM, ring }; s: the station geometry the
 * block was built with (modules in series change the table length), STATION_DEFAULTS when left out.
 */
export function blockTrenches(st, mv, E, N, odMv, env = {}, s = SD) {
  const T = tableShape(s), pitch = T.span + s.aisleGap, clear = BLOCK_TRENCH.pileClearM, e = { ...PLAN_DEFAULTS, ...env };
  const envFor = g => ({ ...env, split: typeof e.split === 'number' ? e.split : e.split?.[g] ?? 0 });
  const runs = [], faults = [], notes = [];
  const dc = { loadA: 1.25 * BLOCK_DC_ISC_A, ductOdMm: s.ductDiameter * 1000, perDuct: 12, areaMm2: 6, odMm: 6 };
  const ac = { loadA: s.inverterKVA * 1000 / (Math.sqrt(3) * s.acVolts), areaMm2: s.acAreaMm2, odMm: s.acDiameter * 1000 };
  const tx = s.transformers, cx = tx[0][0] - s.collectorOffset;

  // ---- DC: each duct's stretch along its row (from the drawn home runs), counted per stretch ----
  const rows = new Map();
  const ductIv = new Map();
  for (const c of dcHomeRoutes(st.strings, st.inverters.map(i => i.point), s)) {
    const y = st.inverters[c.inverter].point[1], xs = c.points.filter(q => Math.abs(q[1] - y) < 1e-6 && q[2] < 0).map(q => q[0]);
    const k = `${c.inverter}:${c.duct}`, d = ductIv.get(k) || { y, lo: Infinity, hi: -Infinity };
    d.lo = Math.min(d.lo, ...xs); d.hi = Math.max(d.hi, ...xs); ductIv.set(k, d);
  }
  for (const i of st.inverters) {
    const y = i.point[1], r = rows.get(y) || { y, row: Math.round((y + 1) / pitch), xs: [], ducts: [], inverters: [] };
    r.xs.push(i.point[0]); r.inverters.push(i); rows.set(y, r);
  }
  for (const d of ductIv.values()) rows.get(d.y).ducts.push([d.lo, d.hi]);
  const laneY = new Map();
  for (const R of rows.values()) {
    const ty = tableOrigin(R.row * 4, s)[1], bottom = R.row > 0 ? ty - s.aisleGap + clear : -Infinity, top = ty - clear;
    const dcS = stretches(R.ducts).map(q => ({ ...q, z: sizeTrench('dc', q.n, dc, envFor('dc')) }));
    const dcMax = Math.max(...dcS.map(q => q.z.corridorM)), dcBig = dcS.reduce((a, q) => (q.n > a.n ? q : a));
    for (const q of dcS) {
      const yc = top - q.z.corridorM / 2, takeOffs = R.xs.filter(x => x >= q.a - 1e-6 && x <= q.b + 1e-6).map(x => [x, yc]);
      runs.push({ stage: 'dc', kind: 'dc', group: 'dc', n: q.n, spec: dc, path: [[q.a, yc], [q.b, yc]], drawnPitchM: s.ductSpacing, takeOffs });
    }
    // AC branch lane: its own trench south of the DC corridor, moved apart until the two heat each other no worse than alone.
    const acS = stretches(R.xs.map(x => [x, cx])).map(q => ({ ...q, z: sizeTrench('lv', q.n, ac, envFor('branch')) }));
    const acMax = Math.max(...acS.map(q => q.z.corridorM)), acBig = acS.reduce((a, q) => (q.n > a.n ? q : a));
    const alone = Math.max(1, dcBig.z.utilisation, acBig.z.utilisation);
    let sep = e.betweenM, chk;
    for (;;) {
      chk = corridorCheck([{ kind: 'dc', n: dcBig.n, spec: dc, sized: dcBig.z, sepM: sep }, { kind: 'lv', n: acBig.n, spec: ac, sized: acBig.z }], env);
      if (chk.utilisation <= alone + 0.005 || sep >= BLOCK_TRENCH.maxSepM) break;
      sep += 0.5;
    }
    const acTop = top - dcMax - sep, acBottom = acTop - acMax;
    for (const q of acS) runs.push({ stage: 'ac', kind: 'lv', group: 'branch', n: q.n, spec: ac, path: [[q.a, acTop - q.z.corridorM / 2], [q.b, acTop - q.z.corridorM / 2]] });
    laneY.set(R.y, acTop - acMax / 2);
    R.check = { sep, util: chk.utilisation, dcMax, acMax };
    if (chk.utilisation > alone + 0.005) faults.push(`Row ${R.row + 1}: the DC and AC lanes heat each other to ${Math.round(chk.utilisation * 100)} % of rating even `
      + `${f2(sep)} m apart. Owner's choice: fewer strings a duct, larger DC cable, or the AC branch in another aisle.`);
    if (acBottom < bottom - 1e-6) faults.push(`Row ${R.row + 1}: the DC corridor (${f2(dcMax)} m) and the AC lane (${f2(acMax)} m, ${f2(sep)} m apart) need `
      + `${f2(top - acBottom + clear)} m; the aisle is ${f2(s.aisleGap)} m, so the AC lane reaches under the tables of row ${R.row}. `
      + 'Owner\'s choice: DC corridor (10 mm² home runs, fewer strings a duct, combiners) or a wider aisle.');
  }
  const seps = [...rows.values()].map(R => R.check);
  notes.push(`Aisles: DC corridor up to ${f2(Math.max(...seps.map(c => c.dcMax)))} m, ${f2(clear)} m clear of the first pile line; AC lane `
    + `${f2(Math.max(...seps.map(c => c.sep)))} m south of it, the two rated together (worst ${Math.round(Math.max(...seps.map(c => c.util)) * 100)} %).`);

  // ---- LV collector: one spine at cx, stretches by the circuits that pass; then a tail into each transformer ----
  const spineIv = st.inverters.map(i => { const a = laneY.get(i.point[1]), b = tx[i.transformer - 1][1]; return [Math.min(a, b), Math.max(a, b)]; });
  for (const q of stretches(spineIv)) runs.push({ stage: 'ac', kind: 'lv', group: 'collector', n: q.n, spec: ac, path: [[cx, q.a], [cx, q.b]], drawnPitchM: 0.25 });
  tx.forEach((t, k) => {
    const n = st.inverters.filter(i => i.transformer === k + 1).length;
    if (n) runs.push({ stage: 'ac', kind: 'lv', group: 'collector', n, spec: ac, path: [[cx, t[1]], [t[0], t[1]]], drawnPitchM: 0.25 });
  });

  // ---- 33 kV: ring trenches at the ring's load (N-1 by default), joint bays along each circuit's own route ----
  const mvaOf = id => mv.stations.find(x => x.id === id)?.mva || 0, amps = m => m * 1e6 / (Math.sqrt(3) * 33000);
  // A radial feeder always carries its whole chain; only a ring splits at its open point in normal running.
  const whole = r => sum(r.stations.map(mvaOf)), ring = e.ring ?? BLOCK_TRENCH.ring;
  const half = r => { if (r.topology !== 'ring' || !(r.open >= 0)) return whole(r); const m = r.stations.map(mvaOf); return Math.max(sum(m.slice(0, r.open)), sum(m.slice(r.open))); };
  const normalA = amps(Math.max(...mv.rings.map(half))), n1A = amps(Math.max(...mv.rings.map(whole))), ringA = ring === 'normal' ? normalA : n1A;
  const od = odMv(mv.rings[0].areaMm2);
  const mvSpec = { loadA: ringA, areaMm2: mv.rings[0].areaMm2, odMm: od };
  for (const tr of mv.trenches) runs.push({ stage: 'mv', kind: 'mv', group: 'mv', n: tr.circuits, spec: mvSpec, path: tr.plan });
  notes.push(ring === 'normal'
    ? `33 kV rings sized for normal running, ${Math.round(normalA)} A a circuit; with one ring end out the ring needs ${Math.round(n1A)} A `
      + '(not rated: curtail during an outage). Type trench ring n-1 to rate it.'
    : `33 kV rings sized with one ring end out (N-1): ${Math.round(n1A)} A a circuit, every circuit in a trench at that load (conservative); `
      + `normal running ${Math.round(normalA)} A. Type trench ring normal to size for normal running.`);

  const plan = planTrenches(runs, env, { hops: mv.circuits.map(c => ({ stage: 'mv', path: c.plan })) }), P = ([x, y]) => ({ e: E + x, n: N + y });
  const items = plan.items.map(t => ({ stage: t.stage, group: t.group, n: t.n, spec: t.spec, path: t.path.map(P), section: t.section, cableOdMm: t.kind === 'mv' ? od : t.cableOdMm,
    sizing: { name: t.sizing.name, utilisation: t.sizing.utilisation, tight: t.sizing.tight, trench: t.trench, of: t.of, drawn: t.drawn }, ducted: t.ducted }));
  // HV connection: fully ducted, from each grid transformer to the connection structure; outline only, never rated here.
  const hv = hvSection(mv.poc.kv);
  for (const g of mv.grid.at) items.push({ stage: 'mv', group: 'hv', path: [P([g[0], g[1]]), P(mv.poc.at)], section: hv.section, cableOdMm: hv.cableOdMm, ducted: true,
    sizing: { name: 'outline', utilisation: null, unrated: true } });
  const hvM = sum(mv.grid.at.map(g => Math.hypot(mv.poc.at[0] - g[0], mv.poc.at[1] - g[1])));
  const unrated = [`HV connection ${mv.poc.kv} kV: no cable data held, so no rating; ${hv.section.status.replace(/^UNRATED: /, '')}.`];
  for (const [stage, x] of Object.entries(plan.summary)) if (x.notOk) faults.push(`${stage.toUpperCase()}: ${x.notOk} run${x.notOk > 1 ? 's' : ''} over rating at the widest arrangement tried.`);
  const totals = { ...plan.totals, trenches: items.length, dugM: plan.totals.dugM + hvM, routeM: plan.totals.routeM + hvM };
  const toEn = w => ({ ...w, at: P(w.at) });
  return { items, plan: { pits: plan.pits.map(toEn), joints: plan.joints.map(toEn), summary: plan.summary, env: plan.env, totals, faults, unrated, notes,
    rows: planRows(plan, { faults, unrated, notes, totals }), aisles: [...rows.values()].map(R => ({ row: R.row + 1, ...R.check })) } };
}