GLOBALGRID2050 / EXPLORE CODE

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

Cable IEC and 2 more files

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

516 lines of JavaScript from globalgrid2050, in 3 files. Topic: Cables and conductors. Section 13 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. Block Trenches transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-trenches.mjs lines 1–161
  2. Cable IEC electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cable-iec.mjs lines 1–259
  3. Cable Rating electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cable-rating.mjs lines 1–96

Block Trenches

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

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

Evidence
  • line-jaccard 0.9855 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/block-trenches.mjs:1-159 4f99893811fc31369524b0993cb7c6db934dfada
  • sha256 4053fbc7d04a4d7cb7fb9ec1781711123ba8b470281921a0ddeceeaa3d4af4ec
  • target sha256 ab853b30bcc4ecf5a541df990ad9b8bd2a2cd27d695f72056394355fc9e70d02
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/block-trenches.mjs · lines 1–161 of 161 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern hvSection (shared by 3 files)

What it does
It calculates 33kV, transformers and cables. Defines 10 functions or classes, including sum, f2, stretches, hvSection, blockTrenches.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV, transformers, cables.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 2 files: Cmd Trench (globalgrid2050); Block Build (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 · energy-transition-simulator/202609280014/mod/engine · 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 energy-transition-simulator/202609280014/mod/engine/block-trenches.mjs:1-161 · blob 60d066d08b4c6a0306e7fb90dad89ed62d70555b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 block-trenches.mjs at v12 commit 3adcee9 (file last changed 9b1ffad). Modular star family: public #148126 stretches.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// 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 })) } };
}

Cable IEC

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

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

Evidence
  • line-jaccard 0.9898 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cable-iec.mjs:1-257 c218e4b046496efdb568f5a03e1b45bc8c92466a
  • sha256 40ba9caaf07eebc0d704dc6343c592c731096e321e45f5a336baf121760858ae
  • target sha256 4ebfde6251f5cb1945d2486e1679dae595943271df97f0c5cff311e02d030360
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

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

What it does
It calculates cables, solar and 33kV. Defines 16 functions or classes, including makeCable, rdcAt, skinY, acResistance, dielectricLoss.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): 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, 1.5kV, 1kV.
Inputs & outputs
Voltage levels named: 33kV, 1.5kV, 1kV.
Downstream impact
Used directly by 2 files: Cmd Trench (globalgrid2050); Trench Plan (globalgrid2050).
What it achieves
It makes cable (`makeCable`) and is built from the rdc at helper (`rdcAt`) and the skin y helper (`skinY`). One buried single-core cable by the IEC 60287 thermal method: its build, losses and thermal resistances. Its code works with 33 kV, 1 kV and 1.5 kV.
Why it matters
Imported by Cmd Trench and Trench Plan.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Trench (import), imported by Trench Plan (import)
Produces
METAL, THERMAL_RHO, DEFAULTS, makeCable, PRESETS, rdcAt, acResistance, dielectricLoss, screenLossFactors, internalThermal, selfG, mutualG
Defines here
makeCable, rdcAt, skinY, acResistance, dielectricLoss, screenLossFactors, eddy, internalThermal, selfG, mutualG, trefoilTouchingG, cyclicSelfG, airGapT4, bundleDiameter, solarDayProfile, lossLoadFactor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cable-iec.mjs:1-259 · blob 0e29d0f73cf246a73603b5d0430834486ae3beca · 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 cable-iec.mjs at v12 commit 3adcee9 (file last changed 3012c07). Modular star family: public #148197 makeCable.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cable-iec.mjs: one buried single-core cable by the IEC 60287 thermal method: its build, losses and thermal resistances.
// Laid direct or in ducts, by the steady-state thermal method of the IEC 60287 family. The group model that rates
// many cables together is cable-group-iec.mjs.
//
// Method references, by number only (no text, tables or figures of any standard are reproduced here):
//   IEC 60287-1-1  clause 1.4 (rating equation), 2.1 (AC resistance, skin and proximity), 2.2 (dielectric loss),
//                  2.3 (screen and sheath loss: circulating and eddy currents, solid and single-point bonding)
//   IEC 60287-2-1  clause 4.1 (internal thermal resistances T1, T3), 4.2 (external T4: single buried cable,
//                  touching trefoil, groups by superposition of images, cables in ducts: air gap, duct wall, ground)
//   IEC 60853-1/-2 (cyclic rating) is the standard route for daily cycles; this file uses the published
//                  1957 loss-factor approach instead, see cyclicGround().
//
// Our own code and our own words. The equations of the method are implemented in our own code; no tabulated data is
// shipped (not the duct U, V, Y constants, not the material tables). Every material constant below is a physical
// property or a stated engineering assumption. The duct air gap is computed from heat-transfer physics; a user may
// pass the standard's duct constants from their own licensed copy.
//
// Indicative engineering only: a real design uses the cable maker's data, measured soil resistivity and a checked
// rating study. Units: SI inside (m, ohm/m, W/m, K.m/W); cable dimensions in mm at the API.
// Pure: no imports, no DOM.

const PI = Math.PI;
const SIGMA = 5.670374419e-8;            // radiation constant, W/m2K4
const G = 9.80665;

/** Conductor and screen metals: resistivity at 20 C (ohm.m) and temperature coefficient at 20 C (1/K). Physics. */
export const METAL = Object.freeze({
  Cu: Object.freeze({ rho20: 1.7241e-8, alpha20: 3.93e-3 }),
  Al: Object.freeze({ rho20: 2.8264e-8, alpha20: 4.03e-3 })
});

/**
 * Thermal resistivities of materials (K.m/W) = 1 / conductivity. Own assumptions from typical polymer
 * conductivities: XLPE ~0.29 W/mK, PE ~0.29, PVC ~0.17, HDPE duct ~0.40, PVC duct ~0.17.
 */
export const THERMAL_RHO = Object.freeze({ XLPE: 3.5, PE: 3.5, PVC: 6.0, HDPE: 2.5, PVCduct: 6.0, EPR: 3.5 });

export const DEFAULTS = Object.freeze({
  freq: 50, ambientC: 15, soilKmW: 1.2, thetaMaxC: 90,
  diffusivityM2h: 0.0018,                 // soil thermal diffusivity (about 5e-7 m2/s), for the cyclic option
  mu: 1,                                  // loss-load factor: 1 = continuous
  dryZone: null,                          // { rhoDry: 2.5, critRiseK: 35 } two-zone drying option (60287-1-1 1.4.2)
  ductAirUVY: null                        // [U, V, Y] from the user's licensed copy of 60287-2-1; null = own physics
});

// ---------------------------------------------------------------- cable build ----

/**
 * makeCable(spec) -> a frozen cable type with its geometry in mm.
 * spec = { kind: 'ac'|'dc', u0Kv, thetaMaxC,
 *   cond: { mat, area, fill=0.9, kR=1.10, r20OhmKm?, ks=1, kp=1 },
 *   ins: { tMm, condScreenMm=0, insScreenMm=0, rhoT, epsR=2.5, tanDelta=0.004 },
 *   screen: null | { mat='Cu', areaMm2, wireMm=1.0 },
 *   sheath: { tMm, rhoT }, odMm? }
 * kR scales the ideal solid-metal resistance up for stranding, lay and tolerance (own conservative assumption;
 * pass r20OhmKm from the maker's data or the conductor standard to replace it). ks, kp default 1 (conservative).
 */
export function makeCable(spec) {
  const c = spec.cond, i = spec.ins, sc = spec.screen || null, sh = spec.sheath;
  const metal = METAL[c.mat]; if (!metal) throw new Error(`cable-rating-iec: unknown metal ${c.mat}`);
  const dc = c.dcMm || Math.sqrt(4 * c.area / (PI * (c.fill || 0.9)));
  const dcs = dc + 2 * (i.condScreenMm || 0);                 // over conductor screen
  const dins = dcs + 2 * i.tMm;                                // over insulation
  const di = dins + 2 * (i.insScreenMm || 0);                  // over insulation screen
  const ds = sc ? di + 2 * (sc.wireMm || 1.0) : di;            // over metallic screen
  const od = spec.odMm || ds + 2 * sh.tMm;
  const r20 = c.r20OhmKm ? c.r20OhmKm / 1000 : metal.rho20 / (c.area * 1e-6) * (c.kR || 1.10);
  return Object.freeze({
    kind: spec.kind || 'ac', u0Kv: spec.u0Kv || 0, thetaMaxC: spec.thetaMaxC || 90, name: spec.name || '',
    cond: Object.freeze({ mat: c.mat, area: c.area, r20, alpha: metal.alpha20, ks: c.ks ?? 1, kp: c.kp ?? 1 }),
    ins: Object.freeze({ rhoT: i.rhoT ?? THERMAL_RHO.XLPE, epsR: i.epsR ?? 2.5, tanDelta: i.tanDelta ?? 0.004,
      t1Mm: (i.condScreenMm || 0) + i.tMm + (i.insScreenMm || 0) }),
    screen: sc ? Object.freeze({ mat: sc.mat || 'Cu', areaMm2: sc.areaMm2, ...METAL[sc.mat || 'Cu'],
      dMeanMm: (di + ds) / 2, tEqMm: sc.areaMm2 / (PI * (di + ds) / 2), dOutMm: ds }) : null,
    sheath: Object.freeze({ tMm: (od - ds) / 2, rhoT: sh.rhoT ?? THERMAL_RHO.PE }),
    dc, dcs, dins, di, ds, od
  });
}

/**
 * Generic builds for the owner's cases. Estimates, not catalogue data: replace with the maker's datasheet.
 * lvAl(area): 0.6/1 kV single-core Al XLPE, no metallic screen or armour.
 * mvAl(area): 19/33 kV single-core Al XLPE, Cu wire screen, PE oversheath.
 * dcCu(area): 1.5 kV DC single-core fine-stranded tinned Cu, cross-linked insulation and sheath (solar string cable).
 */
export const PRESETS = Object.freeze({
  lvAl: (area, o = {}) => makeCable({ kind: 'ac', u0Kv: 0.6, name: `LV ${area} Al`,
    cond: { mat: 'Al', area, ...o.cond }, ins: { tMm: area >= 300 ? 2.4 : 1.8, rhoT: THERMAL_RHO.XLPE },
    sheath: { tMm: area >= 300 ? 2.2 : 1.8, rhoT: THERMAL_RHO.PVC }, ...o }),
  mvAl: (area, o = {}) => makeCable({ kind: 'ac', u0Kv: 19, name: `33 kV ${area} Al`,
    cond: { mat: 'Al', area, ...o.cond },
    ins: { tMm: 8.0, condScreenMm: 0.8, insScreenMm: 1.0, rhoT: THERMAL_RHO.XLPE, epsR: 2.5, tanDelta: 0.004 },
    screen: { mat: 'Cu', areaMm2: area >= 630 ? 50 : 35, wireMm: 1.0 },
    sheath: { tMm: area >= 630 ? 3.6 : 3.2, rhoT: THERMAL_RHO.PE }, ...o }),
  dcCu: (area, o = {}) => makeCable({ kind: 'dc', u0Kv: 0, name: `DC ${area} Cu`,
    cond: { mat: 'Cu', area, kR: 1.18, fill: 0.78, ...o.cond }, ins: { tMm: 0.7, rhoT: THERMAL_RHO.XLPE },
    sheath: { tMm: 0.8, rhoT: THERMAL_RHO.XLPE }, ...o })
});

// ---------------------------------------------------------------- losses (60287-1-1 clause 2) ----

/** DC resistance per metre at theta (C). */
export const rdcAt = (cable, theta) => cable.cond.r20 * (1 + cable.cond.alpha * (theta - 20));

function skinY(x2) {                    // x2 = xs squared; three ranges of the published skin-effect method
  const x = Math.sqrt(x2);
  if (x <= 2.8) { const x4 = x2 * x2; return x4 / (192 + 0.8 * x4); }
  if (x <= 3.8) return -0.136 - 0.0177 * x + 0.0563 * x2;
  return 0.354 * x - 0.733;
}

/**
 * AC resistance per metre at theta: R = R'(1 + ys + yp). sMm = axial spacing between phase conductors
 * (for flat formation pass the geometric mean spacing). DC cables return R'.
 */
export function acResistance(cable, theta, sMm, freq = 50) {
  const r = rdcAt(cable, theta);
  if (cable.kind === 'dc') return { R: r, rdc: r, ys: 0, yp: 0 };
  const base = 8 * PI * freq / r * 1e-7;
  const ys = skinY(base * cable.cond.ks);
  const xp2 = base * cable.cond.kp, xp4 = xp2 * xp2, F = xp4 / (192 + 0.8 * xp4);
  const q = cable.dc / sMm;
  const yp = F * q * q * (0.312 * q * q + 1.18 / (F + 0.27));
  return { R: r * (1 + ys + yp), rdc: r, ys, yp };
}

/** Dielectric loss per phase, W/m: omega C U0^2 tan(delta), C from the insulation diameters. Zero for DC and LV. */
export function dielectricLoss(cable, freq = 50) {
  if (cable.kind === 'dc' || cable.u0Kv < 3) return 0;
  const C = cable.ins.epsR / (18 * Math.log(cable.dins / cable.dcs)) * 1e-9;
  return 2 * PI * freq * C * (cable.u0Kv * 1000) ** 2 * cable.ins.tanDelta;
}

/**
 * Screen loss factors lambda1 for each cable position of a three-phase single-core circuit.
 * formation: 'trefoil' | 'flat'; bonding: 'solid' (both ends) | 'single-point' | 'cross' (ideal cross-bonding);
 * sMm = axial spacing between adjacent phases; R = conductor AC resistance (ohm/m); thetaS = screen temperature.
 * Returns an array of 3 lambda1 (for flat: [outer lagging, middle, outer leading]).
 */
export function screenLossFactors(cable, { R, sMm, formation = 'trefoil', bonding = 'solid', thetaS = 70, freq = 50 }) {
  const sc = cable.screen;
  if (!sc || cable.kind === 'dc') return [0, 0, 0];
  const w = 2 * PI * freq;
  const Rs = sc.rho20 / (sc.areaMm2 * 1e-6) * (1 + sc.alpha20 * (thetaS - 20));
  const d = sc.dMeanMm;
  if (bonding === 'solid') {
    const X = 2 * w * 1e-7 * Math.log(2 * sMm / d);
    if (formation === 'trefoil') { const l = Rs / R / (1 + (Rs / X) ** 2); return [l, l, l]; }
    // Flat, not transposed: unequal circulating currents in the three screens (60287-1-1 2.3.1, 2.3.2 approach).
    const Xm = 2 * w * 1e-7 * Math.log(2), P = X + Xm, Q = X - Xm / 3, rs2 = Rs * Rs;
    const common = 0.75 * P * P / (rs2 + P * P) + 0.25 * Q * Q / (rs2 + Q * Q);
    const cross = 2 * Rs * P * Q * Xm / (Math.sqrt(3) * (rs2 + P * P) * (rs2 + Q * Q));
    const mid = Rs / R * Q * Q / (rs2 + Q * Q);
    return [Rs / R * (common + cross), mid, Rs / R * (common - cross)];
  }
  // Single-point or cross-bonded: no circulating current; eddy current loss only (60287-1-1 2.3.6).
  const m = w / Rs * 1e-7, r = d / (2 * sMm), m2 = m * m, base = m2 / (1 + m2);
  const beta1 = Math.sqrt(4 * PI * w / (1e7 * sc.rho20 * (1 + sc.alpha20 * (thetaS - 20))));
  const ts = sc.tEqMm, Ds = sc.dOutMm;
  const gs = 1 + (ts / Ds) ** 1.74 * (beta1 * Ds * 1e-3 - 1.6);
  const tail = (beta1 * ts) ** 4 / 12e12;
  const eddy = (l0, d1, d2) => Rs / R * (gs * l0 * (1 + d1 + d2) + tail);
  if (formation === 'trefoil') {
    const l0 = 3 * base * r * r, d1 = (1.14 * m ** 2.45 + 0.33) * r ** (0.92 * m + 1.66);
    const l = Math.max(0, eddy(l0, d1, 0)); return [l, l, l];
  }
  const lag = eddy(1.5 * base * r * r, -0.74 * (m + 2) * Math.sqrt(m) / (2 + (m - 0.3) ** 2) * r ** (m + 1),
    0.92 * m ** 3.7 * r ** (m + 2));
  const mid = eddy(6 * base * r * r, 0.86 * m ** 3.08 * r ** (1.4 * m + 0.7), 0);
  const lead = eddy(1.5 * base * r * r, 4.7 * m ** 0.7 * r ** (0.16 * m + 2), 21 * m ** 3.3 * r ** (1.47 * m + 5.06));
  return [lag, mid, lead].map((x) => Math.max(0, x));
}

// ---------------------------------------------------------------- thermal resistances (60287-2-1 clause 4) ----

/** Internal thermal resistances of a single-core cable, K.m/W: T1 insulation (with semicons), T3 oversheath. */
export function internalThermal(cable) {
  const T1 = cable.ins.rhoT / (2 * PI) * Math.log(1 + 2 * cable.ins.t1Mm / cable.dc);
  const T3 = cable.sheath.rhoT / (2 * PI) * Math.log(1 + 2 * cable.sheath.tMm / cable.ds);
  return { T1, T2: 0, T3 };
}

/** Self term of an isolated buried source: ln(u + sqrt(u^2 - 1)), u = 2L/De (image method, isothermal surface). */
export const selfG = (Lm, DeMm) => { const u = 2 * Lm / (DeMm / 1000); return Math.log(u + Math.sqrt(u * u - 1)); };

/** Mutual term between two buried sources: ln(d'/d), d' to the image of the other source above ground. */
export function mutualG(a, b) {
  const dx = a.x - b.x, d = Math.hypot(dx, a.y - b.y), di = Math.hypot(dx, a.y + b.y);
  return Math.log(di / d);
}

/**
 * Touching trefoil, equally loaded, direct in ground, hottest cable (60287-2-1 4.2.4 approach), as a multiple of
 * rho/(2 pi): 3 [ln(2u) - 0.630]; L to the trefoil centre. Returned as {near, far} so the cyclic option can weight it.
 */
export function trefoilTouchingG(Lm, DeMm) {
  const u = 2 * Lm / (DeMm / 1000);
  return 3 * (Math.log(2 * u) - 0.630);
}

/**
 * Cyclic ground term (the published 1957 loss-factor method): the soil inside diameter Dx sees the peak loss, beyond it the mean
 * (loss-load factor mu). Dx = 1.02 sqrt(24 h * diffusivity). Returns the self G to use in place of selfG.
 */
export function cyclicSelfG(Lm, DeMm, mu, diffusivityM2h) {
  if (mu >= 1) return selfG(Lm, DeMm);
  const Dx = 1.02 * Math.sqrt(24 * diffusivityM2h) * 1000;       // mm
  if (Dx <= DeMm) return mu * selfG(Lm, DeMm);
  return Math.log(Dx / DeMm) + mu * Math.log(4 * Lm * 1000 / Dx);
}

/**
 * Air gap between a cable (or a bundle of equivalent diameter DeMm) and the duct bore DbMm, K.m/W, for total heat
 * W (W/m) at mean air temperature thetaM. Own physics: conduction with natural convection in a horizontal annulus
 * (a published effective-conductivity correlation for a horizontal annulus) in parallel with grey-body radiation. If uvy = [U, V, Y] is given (the
 * user's licensed constants for 60287-2-1 4.2.7.1) the empirical form U / (1 + 0.1 (V + Y thetaM) De) is used.
 */
export function airGapT4(DeMm, DbMm, W, thetaM, uvy = null, eps = 0.9) {
  if (uvy) return uvy[0] / (1 + 0.1 * (uvy[1] + uvy[2] * thetaM) * DeMm);
  const Di = DeMm / 1000, Do = DbMm / 1000;
  if (Do <= Di * 1.0001) return 0;
  const Tk = thetaM + 273.15, k = 0.02414 + 7.4e-5 * thetaM, nu = 1.34e-5 + 9.2e-8 * thetaM, Pr = 0.71;
  const alpha = nu / Pr, Lc = (Do - Di) / 2, lnr = Math.log(Do / Di);
  const Grad = 4 * SIGMA * Tk ** 3 * PI * Di / (1 / eps + Di / Do * (1 / eps - 1));
  let T = lnr / (2 * PI * k);
  for (let it = 0; it < 12; it++) {
    const dT = Math.max(0.05, W * T);
    const RaL = G * (1 / Tk) * dT * Lc ** 3 / (nu * alpha);
    const Rac = lnr ** 4 / (Lc ** 3 * (Di ** -0.6 + Do ** -0.6) ** 5) * RaL;
    const keff = k * Math.max(1, 0.386 * (Pr / (0.861 + Pr)) ** 0.25 * Rac ** 0.25);
    const Tnew = 1 / (2 * PI * keff / lnr + Grad);
    if (Math.abs(Tnew - T) < 1e-6) { T = Tnew; break; }
    T = 0.5 * (T + Tnew);
  }
  return T;
}

/** Diameter of the circle that holds n touching cables of diameter d in a ring (own geometry). */
export const bundleDiameter = (n, d) => (n <= 1 ? d : d * (1 + 1 / Math.sin(PI / n)));

// ---------------------------------------------------------------- solar day ----

/** Per-unit current over 24 h for a solar plant: half-sine between sunrise and sunset, clipped at `clip`. */
export function solarDayProfile({ sunrise = 6, sunset = 18, clip = 1, stepH = 0.25 } = {}) {
  const out = [];
  for (let t = 0; t < 24; t += stepH) {
    const x = (t + stepH / 2 - sunrise) / (sunset - sunrise);
    out.push(x > 0 && x < 1 ? Math.min(clip, Math.sin(PI * x)) / clip : 0);
  }
  return out;
}

/** Loss-load factor mu = mean of (I / Imax)^2 over the day. */
export function lossLoadFactor(profile) {
  const m = Math.max(...profile); if (!(m > 0)) return 0;
  return profile.reduce((s, p) => s + (p / m) ** 2, 0) / profile.length;
}

Cable Rating

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

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

Evidence
  • line-jaccard 0.9744 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cable-rating.mjs:1-94 95370a608d9286348dd20bc1ec55d68ded9084c7
  • sha256 80e139628b8dbe5225b7b3f66c7f3e22e417806e47c4a99ae638b1f37ea9e04c
  • target sha256 d6b73ce4f65b11d0dc719312da35a6e43cf34bb8f36087452e148e3179862199
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cable-rating.mjs · lines 1–96 of 96 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern impedance (shared by 4 files)

What it does
It calculates cables and 33kV. Defines 7 functions or classes, including alR20, cuR20, build, rating, impedance.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 7 files: Cmd Trench (globalgrid2050); Plant Feeders (globalgrid2050); Single-Line Diagram (SLD) Rules (globalgrid2050); Block Build (globalgrid2050); and 3 more.
What it achieves
It is built from the al r20 helper (`alR20`), the cu r20 helper (`cuR20`) and the build step (`build`). Continuous current rating of a 33kV single-core aluminium XLPE cable laid direct in trefoil, by the steady-state method of IEC 60287-1-1 (losses) and IEC 60287-2-1 (thermal resistances), and the size a feeder segment needs for the load it carries. Its code works with 33 kV.
Why it matters
Imported by 7 files, including Cmd Trench, Plant Feeders and Single-Line Diagram (SLD) Rules.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
VEDIC
PERCENT (GG2050-VEDIC-000025): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. drop_volts, nominal_volts → drop_percent
Uses
none found
Used by
imported by Cmd Trench (import), imported by Plant Feeders (import), imported by Single-Line Diagram (SLD) Rules (import), imported by Block Build (import), imported by Block MV (import), imported by Connect Here (import), imported by Plant Template (import)
Produces
SIZES, AL_RHO20, alR20, CU_RHO20, cuR20, RATING_DEFAULTS, build, rating, impedance, dropPercent, sizeFor
Defines here
alR20, cuR20, build, rating, impedance, dropPercent, sizeFor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cable-rating.mjs:1-96 · blob 264a01473a9b87e1149ffb06c6eb3f601d145526 · 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 cable-rating.mjs at v12 commit 3adcee9 (file last changed 604729d). Modular star family: not known to star-find.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cable-rating.mjs: continuous current rating of a 33 kV single-core aluminium XLPE cable laid direct in trefoil,
// by the steady-state method of IEC 60287-1-1 (losses) and IEC 60287-2-1 (thermal resistances), and the size a
// feeder segment needs for the load it carries.
//
// Indicative only: a real design uses the manufacturer's data and a rating study. The cable build is estimated
// (conductor from its area, 8 mm insulation for 19/33 kV, a 35 mm2 copper wire screen) unless an OD is given.
// Soil thermal resistivity is an input: default 1.2 K.m/W native ground, ground at 15 C, conductor 90 C.
// Pure: no imports, no DOM.

// Nominal aluminium conductor sizes (mm2) this world offers. Resistance at 20 C is worked out from the resistivity of
// aluminium with a stated allowance for stranding and compaction (own estimate, conservative), not taken from any
// standard's table: pass r20OhmKm from the maker's data to replace it. IEC 60228 is cited by number only.
export const SIZES = Object.freeze([35, 50, 70, 95, 120, 150, 185, 240, 300, 400, 500, 630, 800, 1000]);
export const AL_RHO20 = 2.8264e-8, AL_ALPHA20 = 0.00403, STRAND_ALLOWANCE = 1.10;   // ohm.m, 1/K, ratio
/** Resistance at 20 C in ohm per km of an aluminium conductor of `area` mm2 (physical estimate). */
export const alR20 = area => AL_RHO20 / (area * 1e-6) * STRAND_ALLOWANCE * 1000;
// Copper the same way: R20 = rho20 / A x k, k the same stated allowance (own estimate, not a standard's table).
export const CU_RHO20 = 1.7241e-8, CU_ALPHA20 = 0.00393;                             // ohm.m (annealed copper), 1/K
/** Resistance at 20 C in ohm per km of a copper conductor of `area` mm2 (physical estimate). */
export const cuR20 = area => CU_RHO20 / (area * 1e-6) * STRAND_ALLOWANCE * 1000;

export const RATING_DEFAULTS = Object.freeze({
  kv: 33, u0Kv: 19, freq: 50, conductorMaxC: 90, groundC: 15, soilKmW: 1.2, depthM: 0.8,
  insulationMm: 8.0, semiconMm: 1.8, screenMm2: 35, screenMm: 1.0, sheathMm: 3.2,
  xlpeKmW: 3.5, sheathKmW: 3.5, epsR: 2.5, tanDelta: 0.004, bonding: 'both-ends', groupFactor: 1
});

const PI = Math.PI;

// Cable build from the conductor area (mm); a given OD sets the oversheath instead.
export function build(area, p = RATING_DEFAULTS, odMm = null) {
  const dc = Math.sqrt(4 * area / (PI * 0.9));               // compacted stranded conductor
  const di = dc + 2 * (p.insulationMm + p.semiconMm);       // over the insulation screen
  const ds = di + 2 * p.screenMm;                            // over the wire screen
  const od = odMm || ds + 2 * p.sheathMm;
  return { dc, di, ds, od, sheath: (od - ds) / 2 };
}

/** rating(area, opts) -> { amps, mva, R, T1, T3, T4, lambda1, Wd, build } */
export function rating(area, opts = {}) {
  const p = { ...RATING_DEFAULTS, ...opts };
  if (!(area > 0)) throw new Error(`cable-rating: no conductor of ${area} mm2`);
  const b = build(area, p, opts.odMm || null), w = 2 * PI * p.freq;
  // AC resistance at the maximum temperature: DC resistance, then skin and proximity (IEC 60287-1-1 2.1).
  const rdc = (opts.r20OhmKm || alR20(area)) / 1000 * (1 + AL_ALPHA20 * (p.conductorMaxC - 20));
  const xs4 = (8 * PI * p.freq / rdc * 1e-7) ** 2, ys = xs4 / (192 + 0.8 * xs4);
  const ratio = b.dc / b.od, yf = xs4 / (192 + 0.8 * xs4);
  const yp = yf * ratio ** 2 * (0.312 * ratio ** 2 + 1.18 / (yf + 0.27));
  const R = rdc * (1 + ys + yp);
  // Dielectric loss (small at 33 kV, kept for completeness).
  const C = p.epsR / (18 * Math.log(b.di / b.dc)) * 1e-9;
  const Wd = w * C * (p.u0Kv * 1000) ** 2 * p.tanDelta;
  // Screen loss factor: bonded both ends, trefoil, circulating current (IEC 60287-1-1 2.3.1).
  const rs = 1.7241e-8 / (p.screenMm2 * 1e-6) * STRAND_ALLOWANCE * (1 + 0.00393 * 50);   // copper wires: resistivity x allowance
  const dMean = (b.di + b.ds) / 2, X = 2 * w * 1e-7 * Math.log(2 * b.od / dMean);
  const lambda1 = p.bonding === 'both-ends' ? rs / R / (1 + (rs / X) ** 2) : 0;
  // Thermal resistances (IEC 60287-2-1): insulation, oversheath, and ground for touching trefoil.
  const T1 = p.xlpeKmW / (2 * PI) * Math.log(1 + 2 * (p.insulationMm + p.semiconMm) / b.dc);
  const T3 = p.sheathKmW / (2 * PI) * Math.log(1 + 2 * b.sheath / b.ds);
  const L = p.depthM + b.od / 1000 * (0.5 + Math.sqrt(3) / 4), u = 2 * L / (b.od / 1000);
  const T4 = 1.5 / PI * p.soilKmW * (Math.log(2 * u) - 0.630);
  const dT = p.conductorMaxC - p.groundC - Wd * (0.5 * T1 + T3 + T4);
  const amps = Math.sqrt(dT / (R * T1 + R * (1 + lambda1) * (T3 + T4))) * p.groupFactor;
  return { area, amps, mva: Math.sqrt(3) * p.kv * amps / 1000, R, T1, T3, T4, lambda1, Wd, build: b };
}

/** Series impedance per metre of a trefoil circuit: { r, x } ohm/m at the rated temperature. */
export function impedance(area, opts = {}) {
  const p = { ...RATING_DEFAULTS, ...opts }, rr = rating(area, p);
  const gmr = 0.39 * rr.build.dc, s = rr.build.od;
  return { r: rr.R, x: 2 * PI * p.freq * 2e-7 * Math.log(s / gmr) };
}

/** Voltage drop in % over a length for a three-phase load in MVA at power factor pf. */
export function dropPercent(area, lengthM, mva, { pf = 0.95, ...opts } = {}) {
  const p = { ...RATING_DEFAULTS, ...opts }, z = impedance(area, p);
  const I = mva * 1e6 / (Math.sqrt(3) * p.kv * 1000), sin = Math.sqrt(1 - pf * pf);
  return Math.sqrt(3) * I * lengthM * (z.r * pf + z.x * sin) / (p.kv * 1000) * 100;
}

/**
 * sizeFor(mva, opts) -> the smallest size whose rating carries the load: { area, amps, loadAmps, utilisation }
 * or null when even the largest will not (the load needs another feeder).
 */
export function sizeFor(mva, opts = {}) {
  const p = { ...RATING_DEFAULTS, ...opts }, loadAmps = mva * 1e6 / (Math.sqrt(3) * p.kv * 1000);
  const min = opts.minArea || 0;
  for (const a of SIZES) {
    if (a < min) continue;
    const r = rating(a, p);
    if (r.amps >= loadAmps) return { area: a, amps: r.amps, loadAmps, utilisation: loadAmps / r.amps };
  }
  return null;
}