In this section
- Trench Design transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/trench-design.mjs lines 1–400
- Trench Plan transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/trench-plan.mjs lines 1–265
Trench Design
A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, using IEC 60287-1-1 and IEC 60287-2-1. It solves gap (`solveGap`) and checks drawn (`checkDrawn`).
Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609271853-site-world/world/trench-design.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Trench Design; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9937 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/trench-design.mjs:1-398 042b70b0236e14be5671144d5fe2d6b81ebdd7f6
- sha256 1c6087dbd32db318437cb439129766d31b9dcb535498902a5cd46fc15f1bc443
- target sha256 2f324c42cc53449b975ed4aafe5aa77e2dcbcbd51d57a34f5c159eb99990e95b
- 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/trench-design.mjs · lines 1–400 of 400 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern designOptions (shared by 3 files)
- What it does
- It calculates cables. Defines 22 functions or classes, including cable, ductAirT, footprint, place, rowW.
- 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.
- Downstream impact
- Used directly by 1 file: Trench Plan (globalgrid2050).
- What it achieves
- A trench cross-section designed from the cables it has to carry.
- Why it matters
- Imported by Trench Plan.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- none found
- Used by
- imported by Trench Plan (import)
- Produces
- COVER, DEFAULTS, METAL, R_ALLOWANCE, cable, ductAirT, footprint, place, temperatures, solveGap, section, designOptions
- Defines here
- cable, ductAirT, footprint, place, rowW, hMax, temperatures, cyclicSelf, solveGap, at, section, worstClass, round, r3, designOptions, add, sumPerMetre, r1, checkDrawn, pullPlan, turn, cut
- 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/trench-design.mjs:1-400 · blob ec4949e5bda1059827918c742c5b13ddfb64dc5d · 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 trench-design.mjs at v12 commit 3adcee9 (file last changed 9b1ffad). Modular star family: public #148698 cable.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// trench-design.mjs: a trench cross-section designed from the cables it has to carry.
//
// Given a set of circuits (voltage class, conductor, formation, load), it finds the spacing at which every
// circuit stays within its conductor temperature, then sets the trench width, the depth of cover for the land
// use, the bedding / surround / marker / tile stack, and the spoil and backfill volumes. When one trench would be
// wider than a practical limit it offers the other ways out: several narrower trenches side by side, two layers,
// a larger conductor. Along a route it places draw pits (ducted runs) at changes of direction and wherever the
// pulling tension would pass the limit, and joint bays at drum lengths.
//
// Method (our own code, written from the published method, no tables copied):
// - steady-state conductor temperature by the thermal-circuit method of IEC 60287-1-1 (losses) and
// IEC 60287-2-1 (internal and external thermal resistances);
// - the heating of each cable by every other cable in the ground by superposition with image sources (the
// "unequally loaded groups" approach of IEC 60287-2-1), so a group is rated at its hottest cable;
// - conductor resistance from the resistivity of the metal with a stated allowance, not from a table;
// - the air gap inside a duct from a radiation-plus-convection estimate (our own, conservative), not from the
// standard's duct constants;
// - pulling tension by the capstan relation (straight runs add friction x weight x length, bends multiply by
// e^(friction x angle)), with the tensile limit per mm2 of conductor as an input.
// Cover, clearances and layer thicknesses are typical UK practice or generic project rules, each an input to confirm
// against the operator's or client's spec. A design check, not a rating study: a real design uses the maker's cable
// data and a rating study (BS 7671 Appendix 4 / IEC 60364-5-52 for LV; the operator's method for MV and HV).
// Pure: no imports, no DOM.
const PI = Math.PI, SQ3 = Math.sqrt(3);
// ---------------------------------------------------------------------------------------------------------------
// Inputs that are practice, not physics. Each carries its basis so the world can show it.
/** Depth of cover (m, finished ground to the top of the uppermost cable or duct) by land use and class. */
export const COVER = Object.freeze({
basis: 'typical UK practice; confirm with the network operator or client specification',
farmland: { dc: 0.91, lv: 0.91, mv: 0.91, hv: 0.91, note: 'good agricultural land, cultivated' },
'deep-cultivation': { dc: 1.2, lv: 1.2, mv: 1.2, hv: 1.2, note: 'land that is subsoiled or deep-ploughed' },
'array-field': { dc: 0.6, lv: 0.6, mv: 0.75, hv: 0.9, note: 'inside a fenced array, not cultivated (design choice, to agree)' },
verge: { dc: 0.45, lv: 0.45, mv: 0.75, hv: 0.9, note: 'verge or footway' },
'road-crossing': { dc: 0.6, lv: 0.6, mv: 0.75, hv: 0.9, note: 'carriageway: ducted, 150 mm concrete surround, reinstated to the road spec' },
'track-crossing': { dc: 0.6, lv: 0.6, mv: 0.75, hv: 0.9, note: 'site access track: ducted' }
});
/** Everything below is an input with a stated default; `why` says where it comes from. */
export const DEFAULTS = Object.freeze({
soilKmW: 1.2, groundC: 15, // cleared generic rule: 1.2 K.m/W native, ground at 15 C (IEC 60287 input)
surroundKmW: 1.0, // cleared generic rule: 1.0 K.m/W backfill (used in the sensitivity case only)
bedMm: 75, surroundAboveMm: 75, // typical UK practice: 75 mm bed and 75 mm over the top cable or duct
tapeAboveMm: 200, // cleared project rule: warning tape 200 mm above the service
tileAboveMm: 75, // typical practice: tiles on the surround over MV / HV
sideClearMm: 100, // typical practice: wall to the nearest cable or duct
minGapMm: 75, // typical practice: clear gap between circuits so bedding can be placed
layerGapMm: 150, // two layers: clear vertical gap (a bedding layer between them)
topsoilM: 0.3, // topsoil stripped and kept apart (cleared rule: topsoil and subsoil apart)
bulking: 1.3, // loose spoil over bank volume (cleared generic rule)
maxWidthM: 1.5, // one-pass bucket width that a single trench is allowed (design choice)
betweenTrenchesM: 1.0, // undisturbed ground left between parallel trenches (design choice)
ductWallKmW: 3.5, // polyethylene duct wall (typical material property)
ductBoreRatio: 0.9, // bore over outside diameter of the duct (typical twin-wall / SDR)
emissivity: 0.9, airRiseK: 10, // duct air gap: radiation at this emissivity plus natural convection at this rise
mu: 1, diffusivityM2h: 0.0018 // loss-load factor (1 = continuous; a solar day is lower) and soil diffusivity
});
// Metals: resistivity at 20 C (ohm.m) and temperature coefficient (physical constants), and the allowance that a
// real stranded conductor's resistance carries over the ideal (compaction, lay, the nominal area being a nominal).
export const METAL = Object.freeze({
al: { rho20: 2.8264e-8, alpha: 0.00403, density: 2703 },
cu: { rho20: 1.7241e-8, alpha: 0.00393, density: 8890 }
});
export const R_ALLOWANCE = Object.freeze({ compact: 1.10, flexible: 1.18, why: 'conservative allowance over the ideal resistivity, own estimate; check against the maker\'s data' });
// ---------------------------------------------------------------------------------------------------------------
// One cable: build, losses, internal thermal resistances.
/**
* cable(c) -> the cable's physical build and per-metre electrical figures at its maximum temperature.
* c: { material: 'al'|'cu', areaMm2, odMm, kind: 'ac'|'dc', maxC, insulationMm?, sheathMm?, flexible?, u0Kv?,
* screenMm2? (MV/HV wire screen, copper), bonding? ('both-ends'|'single-point') }
*/
export function cable(c) {
const m = METAL[c.material || 'al'], A = c.areaMm2 * 1e-6;
const dc = Math.sqrt(4 * c.areaMm2 / (PI * (c.flexible ? 0.78 : 0.9))) / 1000; // conductor diameter, m
const od = c.odMm / 1000;
// Insulation and sheath split the radial build unless given; the split only moves T1 against T3 a little.
const radial = (od - dc) / 2;
const scr = c.screenMm2 ? 1.0e-3 : 0;
const ti = c.insulationMm ? c.insulationMm / 1000 : 0.55 * (radial - scr);
const ts = c.sheathMm ? c.sheathMm / 1000 : Math.max(0.0005, radial - scr - ti);
const maxC = c.maxC ?? 90;
const rdc = m.rho20 / A * (c.flexible ? R_ALLOWANCE.flexible : R_ALLOWANCE.compact) * (1 + m.alpha * (maxC - 20));
let R = rdc, lambda1 = 0, Wd = 0;
if (c.kind !== 'dc') {
// Skin and proximity (IEC 60287-1-1 method), round stranded conductor, factors taken as 1 (conservative).
const f = c.freq || 50, x4 = (8 * PI * f / rdc * 1e-7) ** 2, y = x4 / (192 + 0.8 * x4);
const s = c.spacingM || od, r = dc / s;
const yp = y * r * r * (0.312 * r * r + 1.18 / (y + 0.27));
R = rdc * (1 + y + yp);
if (c.screenMm2) {
// Circulating-current screen loss, both ends bonded, trefoil (IEC 60287-1-1 method).
const w = 2 * PI * f, rs = 1.7241e-8 / (c.screenMm2 * 1e-6) * (1 + 0.00393 * (maxC - 30));
const dMean = od - 2 * ts - scr, X = 2 * w * 1e-7 * Math.log(2 * s / dMean);
lambda1 = c.bonding === 'single-point' ? 0 : (rs / R) / (1 + (rs / X) ** 2);
const di = dc + 2 * ti, Cap = (c.epsR || 2.5) / (18 * Math.log(di / dc)) * 1e-9;
Wd = w * Cap * ((c.u0Kv || 19) * 1000) ** 2 * (c.tanDelta || 0.004);
}
}
const T1 = (c.insulationKmW || 3.5) / (2 * PI) * Math.log(1 + 2 * ti / dc);
const T3 = (c.sheathKmW || 5.0) / (2 * PI) * Math.log(1 + 2 * ts / (od - 2 * ts));
// Weight per metre for pulling: metal plus polymer (0.95 t/m3), roughly.
const weightNm = 9.81 * (m.density * A + 950 * (PI / 4) * (od * od - dc * dc));
return { dc, od, R, rdc, lambda1, Wd, T1, T3, maxC, weightNm, areaMm2: c.areaMm2, material: c.material || 'al' };
}
// Air gap between a cable (or a bundle of equivalent diameter De) and the duct bore: 1 / (pi De h), with
// h = radiation (4 e sigma Tm^3) + laminar natural convection of a horizontal cylinder, 1.32 (dT / De)^0.25
// (textbook heat-transfer correlation). Own estimate, not the standard's duct constants; on the high side of them.
export function ductAirT(DeM, p = DEFAULTS, meanC = 60) {
const Tm = meanC + 273.15, hr = 4 * p.emissivity * 5.67e-8 * Tm ** 3, hc = 1.32 * (p.airRiseK / DeM) ** 0.25;
return 1 / (PI * DeM * (hr + hc));
}
// ---------------------------------------------------------------------------------------------------------------
// Layout: every conductor and duct placed in the section (u across, z down positive = depth below ground).
/**
* A circuit: { id, cls: 'dc'|'lv'|'mv'|'hv', cable: {..cable()}, loadA, formation: 'trefoil'|'flat'|'duct-bundle',
* ducted?: true, ductOdMm?, perDuct? (cables in one duct, for a bundle), phases? (3 AC, 2 DC) }
* footprint(c) -> { w, h } of one circuit's group in metres.
*/
export function footprint(ct) {
const od = ct.cable.odMm / 1000, D = ct.ducted || ct.formation === 'duct-bundle' ? ct.ductOdMm / 1000 : od;
if (ct.formation === 'duct-bundle') return { w: D, h: D };
if (ct.formation === 'flat') return { w: 3 * D, h: D };
return { w: 2 * D, h: D * (1 + SQ3 / 2) };
}
/**
* place(circuits, g) -> { sources, width, depthToTop, depthBottom }
* g: { cover, gapM (clear gap between adjacent circuit groups), layers: 1|2, trenches: 1..n, betweenM,
* sideClearM, layerGapM }
* A source is one heat line in the ground: { circuit, u, z, De, W (per unit load^2), ... }.
*/
export function place(circuits, g) {
const p = { ...DEFAULTS, ...g };
const side = (g.sideClearM ?? p.sideClearMm / 1000), gap = g.gapM ?? p.minGapMm / 1000;
const nT = g.trenches || 1, nL = g.layers || 1;
// Split circuits over trenches (round-robin keeps each trench alike), then over layers.
const perTrench = Array.from({ length: nT }, () => []);
circuits.forEach((c, i) => perTrench[Number.isInteger(c.trench) ? Math.min(nT - 1, c.trench) : i % nT].push(c)); // c.trench: fixed
const trenches = [];
let u0 = 0;
const sources = [];
for (const [ti, list] of perTrench.entries()) {
const gapT = g.gaps?.[ti] ?? gap, layers = Array.from({ length: nL }, () => []);
list.forEach((c, i) => layers[Math.floor(i * nL / list.length)].push(c));
const rowW = row => row.reduce((s, c) => s + footprint(c).w, 0) + Math.max(0, row.length - 1) * gapT;
const width = Math.max(...layers.map(rowW)) + 2 * side;
const hMax = row => Math.max(0, ...row.map(c => footprint(c).h));
let zTop = g.covers?.[ti] ?? g.cover;
layers.forEach((row, li) => {
let u = u0 + side + (width - 2 * side - rowW(row)) / 2;
for (const c of row) {
const f = footprint(c), od = c.cable.odMm / 1000;
const D = c.ducted || c.formation === 'duct-bundle' ? c.ductOdMm / 1000 : od;
const zb = zTop + hMax(row); // underside of this layer
const at = [];
if (c.formation === 'duct-bundle') at.push([u + D / 2, zb - D / 2]);
else if (c.formation === 'flat') for (let k = 0; k < 3; k++) at.push([u + D / 2 + k * D, zb - D / 2]);
else at.push([u + D / 2, zb - D / 2], [u + 1.5 * D, zb - D / 2], [u + D, zb - D / 2 - SQ3 / 2 * D]);
at.forEach(([uu, zz], k) => sources.push({ circuit: c.id, phase: k + 1, u: uu, z: zz, D, c, layer: li }));
u += f.w + gapT;
}
zTop += hMax(row) + (p.layerGapMm / 1000);
});
const depthBottom = zTop - p.layerGapMm / 1000;
trenches.push({ u0, width, depthBottom });
u0 += width + (g.betweens?.[ti] ?? g.betweenM ?? p.betweenTrenchesM);
}
return { sources, trenches, corridor: trenches.at(-1).u0 + trenches.at(-1).width };
}
// ---------------------------------------------------------------------------------------------------------------
// Temperatures: every source heats every other through the ground (image method); rating by the hottest cable.
/**
* temperatures(layout, env) -> { hottest, factor, perCircuit }
* factor: how much every load could be multiplied by (all together) before the hottest conductor reaches its
* maximum. factor < 1 means the layout is overloaded; the circuit's rating in this layout is factor x load.
*/
export function temperatures(layout, env = {}) {
const p = { ...DEFAULTS, ...env }, rho = p.soilKmW, S = layout.sources;
// Heat per source at the design load (W/m): all cables in it (a duct bundle holds perDuct cables).
const heat = S.map(s => {
const k = s.c.formation === 'duct-bundle' ? (s.c.perDuct || 1) : 1, cb = s.cb || (s.cb = cable({ ...s.c.cable, spacingM: s.D }));
const Wcond = s.c.loadA ** 2 * cb.R, Wc = Wcond * (1 + cb.lambda1);
return { Wcond, Wc, W: k * Wc, Wd: k * cb.Wd, cb, k };
});
let worst = { factor: Infinity };
const perCircuit = new Map();
S.forEach((s, i) => {
const h = heat[i], cb = h.cb, De = s.D;
// Ground: self (a line source at depth z of diameter De) plus every other source by its image.
const u = 2 * s.z / De, self = rho / (2 * PI) * Math.log(u + Math.sqrt(u * u - 1)), selfL = cyclicSelf(self, s.z, De, p);
let mutualL = 0, mutualD = 0;
S.forEach((o, j) => {
if (j === i) return;
const d = Math.hypot(o.u - s.u, o.z - s.z), d2 = Math.hypot(o.u - s.u, o.z + s.z);
const f = rho / (2 * PI) * Math.log(d2 / Math.max(d, 1e-6));
mutualL += p.mu * heat[j].W * f; mutualD += heat[j].Wd * f;
});
// Duct: air gap and duct wall carry this duct's own heat; a bundle's cable also sits in its neighbours' heat.
let inner = 0, innerD = 0;
if (s.c.ducted || s.c.formation === 'duct-bundle') {
const n = h.k, DeEq = n > 1 ? 1.15 * Math.sqrt(n) * cb.od : cb.od;
const Tair = ductAirT(DeEq, p), Twall = p.ductWallKmW / (2 * PI) * Math.log(1 / p.ductBoreRatio);
inner = h.W * (Tair + Twall); innerD = h.Wd * (Tair + Twall);
}
// Conductor rise at the design load, split into the part that scales with load^2 and the dielectric part.
const load = h.Wcond * cb.T1 + h.Wc * cb.T3 + inner + h.W * selfL + mutualL; // screen loss enters outside T1
const diel = cb.Wd * (0.5 * cb.T1 + cb.T3) + innerD + h.Wd * self + mutualD;
const allow = cb.maxC - p.groundC - diel;
const factor = allow > 0 ? Math.sqrt(allow / load) : 0;
const temp = p.groundC + diel + load;
const cur = perCircuit.get(s.c.id);
if (!cur || factor < cur.factor) perCircuit.set(s.c.id, { factor, temp, amps: factor * s.c.loadA, loadA: s.c.loadA });
if (factor < worst.factor) worst = { factor, temp, circuit: s.c.id, phase: s.phase, u: s.u, z: s.z };
});
return { hottest: worst, factor: worst.factor, perCircuit: [...perCircuit.entries()].map(([id, v]) => ({ id, ...v })) };
}
// Daily cycle (the published 1957 loss-factor approach; IEC 60853-2 is the standard route, cited only): the soil
// within Dx of the cable sees the peak loss, beyond it the mean (mu x peak). mu = 1 gives the steady value back.
function cyclicSelf(self, z, De, p) {
if (!(p.mu < 1)) return self;
const Dx = 1.02 * Math.sqrt(24 * p.diffusivityM2h), rho = p.soilKmW;
return Dx <= De ? p.mu * self : rho / (2 * PI) * (Math.log(Dx / De) + p.mu * Math.log(4 * z / Dx));
}
// ---------------------------------------------------------------------------------------------------------------
// Solve: the smallest gap that meets every rating, for one arrangement.
/**
* solveGap(circuits, g, env) -> { ok, gapM, layout, thermal } : the smallest clear gap between circuit groups
* (at least the practical minimum) at which every conductor is within its limit. ok=false when even a very
* wide gap fails (the circuits in that arrangement are too hot: another arrangement or a larger conductor).
*/
export function solveGap(circuits, g, env = {}, { maxGapM = 3 } = {}) {
const p = { ...DEFAULTS, ...env, ...g }, min = g.minGapM ?? p.minGapMm / 1000;
const at = gap => { const layout = place(circuits, { ...g, gapM: gap }); return { layout, thermal: temperatures(layout, env) }; };
let lo = at(min);
if (lo.thermal.factor >= 1) return { ok: true, gapM: min, ...lo };
let hi = at(maxGapM);
if (hi.thermal.factor < 1) return { ok: false, gapM: maxGapM, ...hi };
let a = min, b = maxGapM;
for (let k = 0; k < 40 && b - a > 0.005; k++) { const m = (a + b) / 2; if (at(m).thermal.factor >= 1) b = m; else a = m; }
// Up to the 25 mm grid, then down while the step below still rates: the smallest grid gap that meets the rating.
let gap = Math.max(min, Math.ceil(b * 40 - 1e-9) / 40), best = at(gap);
for (let q = Math.round(gap * 40 - 1) / 40, t; q >= min - 1e-9 && (t = at(q)).thermal.factor >= 1; q = Math.round(q * 40 - 1) / 40) { gap = q; best = t; }
return { ok: true, gapM: gap, ...best };
}
// ---------------------------------------------------------------------------------------------------------------
// The section: layer stack, markers and volumes per metre for a solved layout.
/** section(solved, env) -> per-trench stack and per-metre volumes (bank m3/m), plus a readout. */
export function section(solved, circuits, env = {}) {
const p = { ...DEFAULTS, ...env }, L = solved.layout, cls = worstClass(circuits);
const bed = p.bedMm / 1000;
return L.trenches.map((t, k) => {
const mine = L.sources.filter(s => s.u >= t.u0 && s.u <= t.u0 + t.width);
const topItem = Math.min(...mine.map(s => s.z - s.D / 2)), bottomItem = Math.max(...mine.map(s => s.z + s.D / 2));
const depth = round(bottomItem + bed, 0.025), w = round(t.width, 0.05);
const surroundTop = Math.max(0.15, topItem - p.surroundAboveMm / 1000);
const itemsArea = mine.reduce((s, x) => s + PI * x.D * x.D / 4, 0);
const dug = w * depth; // vertical sides; batter adds in `ground`
const surround = w * (depth - surroundTop) - itemsArea; // bed + surround material
const topsoil = w * Math.min(p.topsoilM, surroundTop);
const backfill = dug - surround - itemsArea; // includes the topsoil reinstated
const tile = cls === 'mv' || cls === 'hv';
const markers = [
...(tile ? [{ kind: 'tile', depth: round(surroundTop, 0.005), width: round(w - 0.1, 0.05) }] : []),
// Wide trenches carry several tapes side by side so a later dig meets one wherever it opens the ground
// (IEC TS 62738 7.3.4.9.2 asks for this; one per 0.5 m of cable width is our own rule).
{ kind: 'tape', depth: round(Math.max(0.15, topItem - p.tapeAboveMm / 1000), 0.005), count: Math.max(1, Math.ceil((w - 2 * p.sideClearMm / 1000) / 0.5)),
note: 'yellow, service named along it' }
];
// Deeper than 1.2 m the sides are supported or battered (general excavation practice, HSE HSG47; cleared rule).
const support = depth > 1.2 ? 'support (trench box or sheets) or batter the sides' : 'none needed in firm ground; check on site';
return {
trench: k + 1, width: w, depth, coverToTop: round(topItem, 0.005), bed, surroundTop: round(surroundTop, 0.005),
circuits: new Set(mine.map(s => s.circuit)).size, markers, support,
perMetre: { dugBank: r3(dug), spoilLoose: r3(dug * p.bulking), topsoil: r3(topsoil), beddingSurround: r3(surround),
backfillReuse: r3(backfill), ductsOrCables: r3(itemsArea) }
};
});
}
function worstClass(circuits) { const o = ['dc', 'lv', 'mv', 'hv']; return circuits.map(c => c.cls).sort((a, b) => o.indexOf(b) - o.indexOf(a))[0]; }
const round = (x, q) => Math.ceil(x / q - 1e-9) * q;
const r3 = x => Math.round(x * 1000) / 1000;
// ---------------------------------------------------------------------------------------------------------------
// Options for one case: one trench, split, two layers, larger conductor; each solved and sized.
/**
* designOptions({ circuits, landUse, env, upsize }) -> { cover, options: [...] }
* upsize(circuit) -> a circuit with a larger conductor (optional).
*/
export function designOptions({ circuits, landUse = 'farmland', env = {}, upsize = null, maxTrenches = 6, coverM = null }) {
const p = { ...DEFAULTS, ...env }, cls = worstClass(circuits), cover = coverM ?? (COVER[landUse] || COVER.farmland)[cls];
const opts = [];
const add = (name, cs, g, extra = {}) => {
const s = solveGap(cs, { cover, ...g }, env);
const sec = section(s, cs, env);
const widest = Math.max(...sec.map(t => t.width));
opts.push({
name, ok: s.ok, fitsOneBucket: widest <= p.maxWidthM + 1e-9, gapM: s.gapM, trenches: sec.length,
layers: g.layers || 1, corridorM: round(s.layout.corridor, 0.05), widestM: widest, deepestM: Math.max(...sec.map(t => t.depth)),
hottestC: r1(s.thermal.hottest.temp), ratingFactor: r3(s.thermal.factor),
perMetre: sumPerMetre(sec), sections: sec, ...extra
});
};
add('one trench, one layer', circuits, { trenches: 1, layers: 1 });
add('one trench, two layers', circuits, { trenches: 1, layers: 2 });
for (let n = 2; n <= maxTrenches; n++) {
add(`${n} trenches side by side, ${p.betweenTrenchesM} m apart`, circuits, { trenches: n, layers: 1 });
if (opts[opts.length - 1].fitsOneBucket && opts[opts.length - 1].ok) break;
}
if (upsize) {
const big = circuits.map(upsize);
add(`larger conductor (${big[0].cable.areaMm2} mm2 ${big[0].cable.material}), one trench`, big, { trenches: 1, layers: 1 }, { conductor: big[0].cable.areaMm2 });
for (let n = 2; n <= maxTrenches; n++) {
add(`larger conductor, ${n} trenches`, big, { trenches: n, layers: 1 }, { conductor: big[0].cable.areaMm2 });
if (opts[opts.length - 1].fitsOneBucket && opts[opts.length - 1].ok) break;
}
}
return { cover, landUse, coverBasis: COVER.basis, cls, options: opts };
}
function sumPerMetre(sec) {
const o = {};
for (const t of sec) for (const [k, v] of Object.entries(t.perMetre)) o[k] = r3((o[k] || 0) + v);
return o;
}
const r1 = x => Math.round(x * 10) / 10;
/** Check a drawn section as it stands: circuits at a centre pitch in one row at a cover. */
export function checkDrawn(circuits, { cover, pitchM }, env = {}) {
const w = footprint(circuits[0]).w;
const layout = place(circuits, { cover, gapM: Math.max(0, pitchM - w), trenches: 1, layers: 1 });
return { layout, thermal: temperatures(layout, env) };
}
// ---------------------------------------------------------------------------------------------------------------
// Along the route: draw pits, pull sections, joint bays.
export const PULL = Object.freeze({
friction: 0.35, // cable on a lubricated PE duct (typical 0.2-0.5; own conservative choice)
frictionDirect: 0.5, // cable on rollers in an open trench, allowing for roller drag (own choice)
tensileNmm2: { al: 30, cu: 50 },// cleared generic rule: pulling-eye limit per mm2 of conductor
sidewallNm: 3000, // bend sidewall pressure limit, N per m of bend radius (typical for XLPE, to agree)
pitAtTurnDeg: 10, // a change of direction above this gets a draw pit (cleared rule: every change of direction)
drumM: 800, // one cable length on a drum (input: depends on size and drum; joint bays at this)
jointBay: { lengthM: 4.0, extraWidthM: 0.6 }, // typical joint bay for LV/MV single-core (design choice)
pit: { internalM: [1.2, 0.9], covers: 'D400 where vehicles run, C250 elsewhere (cleared rule)' },
basis: 'capstan relation; limits are inputs and the cable maker\'s figures govern'
});
/**
* pullPlan(route, circuit, { ducted }) -> { pits, jointBays, sections }. circuit.maxPullN (or pull.maxPullN): the maker's absolute cap, N.
* route: [[x, y], ...] in metres. A pit at every change of direction over pitAtTurnDeg (ducted runs; the cable
* then pulls straight through each), and more wherever the tension or the drum length would be exceeded. Pulls are
* worked from one end; a bend inside a pull multiplies the tension by e^(mu theta).
*/
export function pullPlan(route, ct, { ducted = true, pull = PULL } = {}) {
const cb = cable(ct.cable), phases = ct.formation === 'duct-bundle' ? (ct.perDuct || 1) : ducted ? 1 : 3;
const mu = ducted ? pull.friction : pull.frictionDirect, wN = cb.weightNm * phases;
const stressN = pull.tensileNmm2[cb.material] * ct.cable.areaMm2 * phases, capN = ct.maxPullN ?? pull.maxPullN;
const Tmax = capN > 0 ? Math.min(stressN, capN) : stressN; // the conductor stress limit, capped by the maker's maximum
// Walk the polyline: segment lengths and turn angles.
const segs = [];
for (let i = 1; i < route.length; i++) {
const [ax, ay] = route[i - 1], [bx, by] = route[i];
segs.push({ len: Math.hypot(bx - ax, by - ay), dir: Math.atan2(by - ay, bx - ax) });
}
const turn = i => { let d = Math.abs(segs[i].dir - segs[i - 1].dir) % (2 * PI); return d > PI ? 2 * PI - d : d; };
const pits = [], jointBays = [], sections = [];
let T = 0, run = 0, drum = 0, chain = 0, start = 0;
const cut = (at, why) => { sections.push({ from: r1(start), to: r1(at), lengthM: r1(at - start), tensionN: Math.round(T), limitN: Math.round(Tmax) }); start = at; T = 0; run = 0; };
segs.forEach((s, i) => {
if (i > 0) {
const th = turn(i);
if (ducted && th * 180 / PI > pull.pitAtTurnDeg) { pits.push({ at: r1(chain), why: 'change of direction' }); cut(chain, 'turn'); }
else T *= Math.exp(mu * th);
}
// Along the segment in 1 m steps so the pit or joint lands where the limit is reached.
for (let x = 0; x < s.len; x += 1) {
const dl = Math.min(1, s.len - x);
if (T + mu * wN * dl > Tmax) { if (ducted) pits.push({ at: r1(chain), why: 'pulling tension' }); else jointBays.push({ at: r1(chain), why: 'pulling tension' }); cut(chain); }
if (drum + dl > pull.drumM) { jointBays.push({ at: r1(chain), why: 'drum length' }); drum = 0; if (!ducted) cut(chain); }
T += mu * wN * dl; chain += dl; run += dl; drum += dl;
}
});
cut(chain);
// A joint must sit in a pit or joint bay, never direct-buried (cleared rule); in a ducted run it goes in a pit.
return { lengthM: r1(chain), pits, jointBays, sections, limitN: Math.round(Tmax), weightNm: r3(wN), friction: mu };
}Trench Plan
A JavaScript module in the engine folder of GlobalGrid2050 that works with cables, solar and 33kV, using IEC 60287.
Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609271740-site-world/world/trench-plan.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Trench Plan; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9906 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/trench-plan.mjs:1-263 c0156ba112940c5c9be1a9373071686921d5bbb4
- sha256 1be6f5e8782fc9b0f8ca41e9627f56902a0add1b55beafdeefd6811cdab55b62
- target sha256 a6bdc4c1158e1e17d4c45684e0167e568ff18ca794c81d0c604602d2a013886a
- 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/trench-plan.mjs · lines 1–265 of 265 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · 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 '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 3 files: Block Trenches (globalgrid2050); Cmd Trench (globalgrid2050); Plant Feeders (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 Block Trenches, Cmd Trench and Plant Feeders.
- Application
- globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
- Uses
- Trench Design (import), Cable IEC (import)
- Used by
- imported by Block Trenches (import), imported by Cmd Trench (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 energy-transition-simulator/202609280014/mod/engine/trench-plan.mjs:1-265 · blob e3aa4d37b5fe5a471d777f7bf9b5bff90b5a9fbc · 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 trench-plan.mjs at v12 commit 3adcee9 (file last changed a36f410). Modular star family: public #148717 sizeTrench.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// 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;
}