GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609271853-site-world/world

Earth Screen and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, using IEC 60287-1-1 and IEC 60949.

661 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 183 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. Earth Screen electrical · globalgrid2050 / solar-design-studio/202609271853-site-world/world/earth-screen.mjs lines 1–341
  2. Earth Study transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/earth-study.mjs lines 1–193
  3. Extensions render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/extensions.mjs lines 1–16
  4. Fade transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/fade.mjs lines 1–17
  5. First Showing interaction · globalgrid2050 / solar-design-studio/202609271853-site-world/world/first-showing.mjs lines 1–94

Earth Screen

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, using IEC 60287-1-1 and IEC 60949.

electricalglobalgrid2050 / solar-design-studio/202609271853-site-world/world/earth-screen.mjs · lines 1–341 of 341 · version 2026-09-27 18:53 · pattern polar (shared by 2 files)

What it does
It calculates cables. Defines 28 functions or classes, including C, add, mul, div, abs.
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 2 files: Earth Draw (globalgrid2050); Earth Study (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It places marks (`placeMarks`) and is built from the add step (`add`) and the mul step (`mul`). `earth-screen.mjs` (world cartridge, loaded by `earth-mount.mjs`): metallic screen (sheath) bonding of single-core MV/HV cable circuits.
Why it matters
Imported by Earth Draw and Earth Study.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Earth Draw (import), imported by Earth Study (import)
Produces
DISCLAIMER, SCREEN_METAL, BONDING_DEFAULTS, csolve, circuitGeometry, phaseCurrents, screenEmfPerM, solidBonding, solidTrefoilClosed, standingVoltage, maxSinglePointM, crossBonding
Defines here
C, add, mul, div, abs, polar, csolve, circuitGeometry, dist, phaseCurrents, screenEmfPerM, solidBonding, solidTrefoilClosed, standingVoltage, maxSinglePointM, crossBonding, perm, crossTrefoilClosed, carsonDepth, faultStandingVoltage, Zm, adiabaticK, eccMinAreaMm2, ratingRatio, recommendBonding, bondingRows, f, placeMarks
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/earth-screen.mjs:1-341 · blob e4cb8feb0f2258746242928dada1492f393975dd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// earth-screen.mjs (world cartridge, loaded by earth-mount.mjs): metallic screen (sheath) bonding of single-core MV/HV cable circuits.
// Solid bonding, single-point bonding with an earth continuity conductor (ECC), and cross-bonding with
// link boxes and sheath voltage limiters (SVLs). Standing voltage, circulating current, screen loss factor,
// the effect on current rating, through-fault standing voltage, ECC adiabatic check, and what the single-line
// diagram (SLD) and follow-the-power should show.
//
// Method references, by number only (no text, tables or figures of any standard are reproduced here):
//   IEC 60287-1-1  clause 2.3 (screen loss factor lambda1: circulating current for solid bonding, eddy current,
//                  cross-bonded circuits with unequal minor sections).
//   IEC 60949 and BS 7671 regulation 543.1.3 (adiabatic check of a protective conductor, k from material physics).
//   BS 7671 regulation 411 (conventional touch-voltage idea; the limit here is a user setting).
//   IEEE 575 and IEC 62067 / IEC 60840 annexes (bonding arrangements, SVLs): concepts only.
//   ERA 69-30 is cited by number only; nothing of it is reproduced here.
//   Public background: Wikipedia "Electrical cable", "Carson's equations" (earth return, J. R. Carson 1926),
//   "Inductance" (mutual inductance of parallel conductors), all paraphrased.
//
// Our own code and our own words. Physics used: induced voltage per metre on conductor k from phase currents
// E_k = j w (mu0 / 2 pi) sum_i I_i ln(1 / d_ki) (balanced currents, so the reference distance cancels); a thin
// screen tube has geometric mean radius equal to its mean radius. Constants are physical, or labelled assumptions.
//
// NO WARRANTY. Illustrative, early-design only. A real design uses the cable maker's data, the network
// operator's limits and a study checked by a qualified engineer. Pure: no imports, no DOM. SI inside.

export const DISCLAIMER = 'Illustrative early-design estimate, no warranty: confirm screen bonding with a qualified engineer and the cable maker.';

const PI = Math.PI, MU0_2PI = 2e-7;
export const SCREEN_METAL = Object.freeze({
  Cu: Object.freeze({ rho20: 1.7241e-8, alpha20: 3.93e-3, heatCap: 3.45e6, beta: 234.5 }),   // J/(K m3), K
  Al: Object.freeze({ rho20: 2.8264e-8, alpha20: 4.03e-3, heatCap: 2.5e6, beta: 228 }),
  Pb: Object.freeze({ rho20: 21.4e-8, alpha20: 4.0e-3, heatCap: 1.45e6, beta: 230 })
});

/** Assumptions a user should replace. Each is ours, not a standard's value. */
export const BONDING_DEFAULTS = Object.freeze({
  freq: 50,
  touchLimitV: 50,        // normal standing-voltage limit at an open screen end (set the operator's own value)
  drumM: 750,             // longest cable length on one drum: sets joint spacing (assumption)
  solidAcceptPct: 3,      // accept solid bonding if it costs no more than this % of rating
  thetaScreenC: 70,       // screen temperature when the conductor is at 90 C (assumption)
  eccAreaMm2: 95,         // ECC copper area proposed for single-point bonding (assumption)
  eccMm: { dx: 0, dy: 150 }, // ECC position relative to the trefoil centre, mm (assumption)
  faultS: 1,              // earth fault clearance time for the adiabatic check, s (assumption)
  eccThetaC: [30, 160],   // ECC initial and final temperature for the adiabatic check (PVC-covered, assumption)
  earthOhm: 0.1,          // resistance to earth at each bonding point, tied into the plant earth grid (assumption)
  soilOhmM: 100,          // soil resistivity for the Carson earth-return depth (assumption)
  svlClassesKv: [1, 2, 3, 4.5, 6, 9, 12],  // illustrative SVL continuous-voltage ladder; use the maker's list
  flatEarthPathMargin: 1.08, // flat solid bonding: allowance for an earth path (from our own pair check)
  svlMargin: 1.2          // SVL continuous voltage must exceed the worst through-fault standing voltage x this
});

// ---------------------------------------------------------------- complex helpers ----
const C = (re, im = 0) => ({ re, im });
const add = (a, b) => C(a.re + b.re, a.im + b.im), sub = (a, b) => C(a.re - b.re, a.im - b.im);
const mul = (a, b) => C(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
const div = (a, b) => { const d = b.re * b.re + b.im * b.im; return C((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d); };
const abs = (a) => Math.hypot(a.re, a.im), scale = (a, s) => C(a.re * s, a.im * s);
const polar = (m, deg) => C(m * Math.cos(deg * PI / 180), m * Math.sin(deg * PI / 180));

/** Solve A x = b for complex A (n x n) by Gaussian elimination with partial pivoting. */
export function csolve(A, b) {
  const n = b.length, M = A.map((r, i) => [...r, b[i]]);
  for (let k = 0; k < n; k++) {
    let p = k; for (let i = k + 1; i < n; i++) if (abs(M[i][k]) > abs(M[p][k])) p = i;
    [M[k], M[p]] = [M[p], M[k]];
    for (let i = k + 1; i < n; i++) {
      const f = div(M[i][k], M[k][k]);
      for (let j = k; j <= n; j++) M[i][j] = sub(M[i][j], mul(f, M[k][j]));
    }
  }
  const x = Array(n);
  for (let i = n - 1; i >= 0; i--) {
    let s = M[i][n]; for (let j = i + 1; j < n; j++) s = sub(s, mul(M[i][j], x[j]));
    x[i] = div(s, M[i][i]);
  }
  return x;
}

// ---------------------------------------------------------------- geometry ----

/**
 * circuitGeometry({ formation, sMm, screenMeanMm, screenAreaMm2, screenMat })
 * formation 'trefoil' (touching or spaced, sMm = centre spacing) or 'flat' (sMm = adjacent spacing).
 * Returns phase centre positions (m), the screen mean radius and resistance per metre at thetaS.
 */
export function circuitGeometry({ formation = 'trefoil', sMm, screenMeanMm, screenAreaMm2, screenMat = 'Cu',
  thetaS = BONDING_DEFAULTS.thetaScreenC } = {}) {
  const s = sMm / 1000, m = SCREEN_METAL[screenMat];
  if (!m) throw new Error(`screen-bonding: unknown screen metal ${screenMat}`);
  const pos = formation === 'flat' ? [[-s, 0], [0, 0], [s, 0]]
    : [[-s / 2, -s * Math.sqrt(3) / 6], [s / 2, -s * Math.sqrt(3) / 6], [0, s * Math.sqrt(3) / 3]];
  const Rs = m.rho20 / (screenAreaMm2 * 1e-6) * (1 + m.alpha20 * (thetaS - 20));
  return Object.freeze({ formation, s, pos, rs: screenMeanMm / 2000, Rs, screenMat, screenAreaMm2 });
}

const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
/** Balanced positive-sequence phase currents of rms I (A), phase order a, b, c. */
export const phaseCurrents = (I) => [polar(I, 0), polar(I, -120), polar(I, 120)];

/** Induced voltage per metre (V/m, complex) on each open screen from the three core currents. */
export function screenEmfPerM(geo, Icore, freq = BONDING_DEFAULTS.freq) {
  const w = 2 * PI * freq;
  return geo.pos.map((pk, k) => {
    let s = C(0);
    for (let i = 0; i < 3; i++) s = add(s, scale(Icore[i], Math.log(1 / (i === k ? geo.rs : dist(pk, geo.pos[i])))));
    return mul(C(0, w * MU0_2PI), s);
  });
}

// ---------------------------------------------------------------- the three arrangements ----

/**
 * Solid bonding: screens joined and earthed at both ends. Solves the three circulating currents exactly for the
 * geometry (earth path neglected: the balanced currents close among the screens). Returns per-phase screen currents
 * and the circulating-current loss factor lambda1' = Rs |Is|^2 / (R |I|^2) given conductor AC resistance R (ohm/m).
 */
export function solidBonding(geo, { I, R, freq = BONDING_DEFAULTS.freq }) {
  const w = 2 * PI * freq, Ic = phaseCurrents(I), E = screenEmfPerM(geo, Ic, freq);
  const A = [], b = [];
  for (let k = 0; k < 3; k++) {
    const row = [];
    for (let j = 0; j < 3; j++) {
      const L = Math.log(1 / (j === k ? geo.rs : dist(geo.pos[k], geo.pos[j])));
      row.push(add(C(j === k ? geo.Rs : 0), C(0, w * MU0_2PI * L)));
    }
    row.push(C(-1)); A.push(row); b.push(scale(E[k], -1));   // Rs Is + jX.Is + E = V (common drop per metre)
  }
  A.push([C(1), C(1), C(1), C(0)]); b.push(C(0));
  const x = csolve(A, b), Is = x.slice(0, 3);
  const lambda1 = Is.map((i) => geo.Rs * abs(i) ** 2 / (R * I * I));
  return { Is: Is.map(abs), IsPhasor: Is, lambda1, lossWperM: Is.reduce((s, i) => s + geo.Rs * abs(i) ** 2, 0) };
}

/** Closed form for touching or spaced trefoil (the classic result): lambda1' = (Rs/R) / (1 + (Rs/X)^2), X = 2 w 1e-7 ln(2s/d). */
export function solidTrefoilClosed(geo, { R, freq = BONDING_DEFAULTS.freq }) {
  const X = 2 * 2 * PI * freq * 1e-7 * Math.log(geo.s / geo.rs);
  return { X, lambda1: geo.Rs / R / (1 + (geo.Rs / X) ** 2) };
}

/** Single-point bonding: standing voltage (V) at the open end of each screen for a run of lengthM at current I. */
export function standingVoltage(geo, { I, lengthM, freq = BONDING_DEFAULTS.freq }) {
  return screenEmfPerM(geo, phaseCurrents(I), freq).map((e) => abs(e) * lengthM);
}

/** Longest single-point section (m) whose worst standing voltage stays within limitV at current I. */
export function maxSinglePointM(geo, { I, limitV = BONDING_DEFAULTS.touchLimitV, freq = BONDING_DEFAULTS.freq }) {
  return limitV / Math.max(...standingVoltage(geo, { I, lengthM: 1, freq }));
}

/**
 * Cross-bonding of one major section in three minor sections of lengths [a, b, c] (m). Screens are rotated at each
 * link box so each series path passes phases a, b, c in turn. Returns the residual circulating current per path,
 * the loss factor lambda1' (averaged over the path), and the worst standing voltage at the two link boxes.
 * Exact for the geometry under the same "no earth path" assumption as solidBonding.
 */
export function crossBonding(geo, { I, R, minorM, freq = BONDING_DEFAULTS.freq }) {
  const w = 2 * PI * freq, Ic = phaseCurrents(I), E = screenEmfPerM(geo, Ic, freq);
  const perm = (k, p) => (p + k) % 3, Ltot = minorM.reduce((s, x) => s + x, 0);
  const A = [], b = [];
  for (let p = 0; p < 3; p++) {
    const row = [C(0), C(0), C(0)]; let emf = C(0);
    minorM.forEach((Lk, k) => {
      const sp = perm(k, p); emf = add(emf, scale(E[sp], Lk));
      for (let q = 0; q < 3; q++) {
        const sq = perm(k, q), d = sq === sp ? geo.rs : dist(geo.pos[sp], geo.pos[sq]);
        row[q] = add(row[q], scale(add(C(q === p ? geo.Rs : 0), C(0, w * MU0_2PI * Math.log(1 / d))), Lk));
      }
    });
    row.push(C(-1)); A.push(row); b.push(scale(emf, -1));
  }
  A.push([C(1), C(1), C(1), C(0)]); b.push(C(0));
  const J = csolve(A, b).slice(0, 3);
  const lambda1 = geo.Rs * J.reduce((s, j) => s + abs(j) ** 2, 0) / 3 / (R * I * I);
  // Standing voltage at a link box: the screen potential there with the circulating current flowing (small), taken
  // conservatively as the open-circuit emf of the worst minor section on either side.
  const worst = Math.max(...minorM.map((Lk) => Math.max(...E.map(abs)) * Lk));
  return { J: J.map(abs), lambda1, residual: Math.max(...J.map(abs)) / I, linkBoxV: worst, Ltot };
}

/** Closed form for trefoil cross-bonding with unequal minor sections: lambda1 = lambda1_solid x (|a + b h + c h^2| / (a+b+c))^2. */
export function crossTrefoilClosed(geo, { R, minorM, freq = BONDING_DEFAULTS.freq }) {
  const [a, b, c] = minorM, h = polar(1, 120), h2 = polar(1, 240);
  const u = abs(add(add(C(a), scale(h, b)), scale(h2, c))) / (a + b + c);
  return { lambda1: solidTrefoilClosed(geo, { R, freq }).lambda1 * u * u, unbalance: u };
}

// ---------------------------------------------------------------- through faults, with earth return ----

/** Carson earth-return depth De (m) for soil resistivity rho (ohm.m): the simplified form, De = 658.5 sqrt(rho/f). */
export const carsonDepth = (rho, freq = BONDING_DEFAULTS.freq) => 658.5 * Math.sqrt(rho / freq);

/**
 * Standing voltage at the open end of a single-point bonded run during a through phase-to-earth fault on phase a
 * (current If, A), fault current returning partly in the ECC (earthed at both ends through earthOhm) and partly
 * in the ground (Carson). Returns |screen - ECC| at the open end (what the SVL sees), the ECC current and the
 * voltage to remote earth. Also the three-phase through-fault value for comparison.
 */
export function faultStandingVoltage(geo, { If3, If1, lengthM, ecc = {}, freq = BONDING_DEFAULTS.freq,
  soilOhmM = BONDING_DEFAULTS.soilOhmM, earthOhm = BONDING_DEFAULTS.earthOhm }) {
  const w = 2 * PI * freq, De = carsonDepth(soilOhmM, freq), rg = w * 4e-7 * PI / 8;   // earth-return resistance per m
  const e = { ...BONDING_DEFAULTS.eccMm, ...ecc }, areaE = e.areaMm2 || BONDING_DEFAULTS.eccAreaMm2;
  const pe = [e.dx / 1000, e.dy / 1000], Re = SCREEN_METAL.Cu.rho20 / (areaE * 1e-6);
  const gmrE = 0.7788 * Math.sqrt(areaE / PI) / 1000;
  const Zm = (d) => C(rg, w * MU0_2PI * Math.log(De / d));
  const L = lengthM, pa = geo.pos[0];
  const Zee = add(C(Re), Zm(gmrE)), Zec = Zm(dist(pe, pa)), Zse = Zm(dist(pe, pa)), Zsc = Zm(geo.rs);
  // ECC current (returning, signed along +x): -2 Rg Ie = L (Zee Ie + Zec If)
  const If = C(If1), Ie = div(scale(mul(Zec, If), -L), add(scale(Zee, L), C(2 * earthOhm)));
  const Ve0 = scale(Ie, -earthOhm), VeL = scale(Ie, earthOhm);
  const VsL = sub(Ve0, scale(add(mul(Zse, Ie), mul(Zsc, If)), L));
  const threePhase = Math.max(...standingVoltage(geo, { I: If3, lengthM, freq }));
  return { toEcc: abs(sub(VsL, VeL)), toRemote: abs(VsL), eccA: abs(Ie), eccShare: abs(Ie) / If1, threePhase };
}

/** Adiabatic minimum area (mm2) of a copper ECC for fault If (A) lasting t (s): S = I sqrt(t) / k, k from physics. */
export function adiabaticK(mat = 'Cu', [thI, thF] = BONDING_DEFAULTS.eccThetaC) {
  const m = SCREEN_METAL[mat];
  // k (A s^0.5 / mm2) = sqrt(Qc (B + 20) / rho20 x ln((B + thF) / (B + thI))), Qc in J/(K mm3), rho20 in ohm.mm
  return Math.sqrt(m.heatCap * 1e-9 * (m.beta + 20) / (m.rho20 * 1e3) * Math.log((m.beta + thF) / (m.beta + thI)));
}
export const eccMinAreaMm2 = (If, t = BONDING_DEFAULTS.faultS, mat = 'Cu') => If * Math.sqrt(t) / adiabaticK(mat);

// ---------------------------------------------------------------- rating effect and recommendation ----

/**
 * Approximate rating ratio between two bonding choices, when the ground thermal resistance dominates:
 * I_b / I_a ~ sqrt((1 + lambda_a) / (1 + lambda_b)). The e2 rating engine gives the exact figure (its bonding option).
 */
export const ratingRatio = (lambdaA, lambdaB) => Math.sqrt((1 + lambdaA) / (1 + lambdaB));

/**
 * recommendBonding(run, opts): pick an arrangement for one MV cable run and say why.
 * run = { id, kv, lengthM, loadA, R (ohm/m at 90 C), If3, If1, formation, sMm, screenMeanMm, screenAreaMm2,
 *         screenMat, fromLabel, toLabel }
 * Returns a frozen study with choice, reasons, numbers, link boxes, SVLs, ECC, SLD marks and follow-the-power rows.
 */
export function recommendBonding(run, opts = {}) {
  const o = { ...BONDING_DEFAULTS, ...opts };
  const geo = circuitGeometry({ ...run, thetaS: o.thetaScreenC });
  const I = run.loadA, L = run.lengthM, R = run.R;
  const solid = solidBonding(geo, { I, R, freq: o.freq });
  // Flat formation has a zero-sequence screen emf: with the screens earthed both ends, an earth path shifts the
  // phase split and raised the hottest-phase lambda1 by up to about 7 % in our network pair check (pair-report.json).
  // Trefoil showed no such effect. The classic formula (and solidBonding) ignore the earth path, so allow for it.
  const lamSolid = Math.max(...solid.lambda1) * (geo.formation === 'flat' ? o.flatEarthPathMargin : 1);
  const spLimitM = maxSinglePointM(geo, { I, limitV: o.touchLimitV, freq: o.freq });
  const costPct = (1 - ratingRatio(0, lamSolid)) * 100;          // rating lost by solid vs single-point (eddy ignored)
  const reasons = [];
  let choice;
  if (costPct <= o.solidAcceptPct) {
    choice = 'solid';
    reasons.push(`Solid bonding costs about ${costPct.toFixed(1)} % of rating (limit set ${o.solidAcceptPct} %), and needs no SVL or ECC.`);
  } else if (L <= spLimitM) {
    choice = 'single-point';
    reasons.push(`Solid bonding would cost about ${costPct.toFixed(1)} % of rating; the run (${L.toFixed(0)} m) is within`
      + ` the ${spLimitM.toFixed(0)} m single-point length for a ${o.touchLimitV} V standing voltage.`);
  } else {
    choice = 'cross';
    reasons.push(`Solid bonding would cost about ${costPct.toFixed(1)} % of rating and the run is longer than ${spLimitM.toFixed(0)} m, so the screens are cross-bonded.`);
  }
  const study = { id: run.id, kv: run.kv, lengthM: L, loadA: I, choice, reasons, geometry: geo, disclaimer: DISCLAIMER };
  study.lambda1Solid = lamSolid; study.solidScreenA = Math.max(...solid.Is);
  study.solidLossKW = solid.lossWperM * L / 1000;
  study.solidRatingCostPct = costPct;
  study.singlePointMaxM = spLimitM;
  const marks = [];
  if (choice === 'solid') {
    study.lambda1 = lamSolid; study.lossKW = study.solidLossKW;
    study.standingV = 0; study.linkBoxes = 2; study.svl = null; study.ecc = null;
    marks.push({ atM: 0, kind: 'screen-earth', label: 'screens earthed' }, { atM: L, kind: 'screen-earth', label: 'screens earthed' });
  } else if (choice === 'single-point') {
    const sv = Math.max(...standingVoltage(geo, { I, lengthM: L, freq: o.freq }));
    const fv = faultStandingVoltage(geo, { If3: run.If3, If1: run.If1, lengthM: L, freq: o.freq, soilOhmM: o.soilOhmM, earthOhm: o.earthOhm,
      ecc: { ...o.eccMm, areaMm2: o.eccAreaMm2 } });
    const need = Math.max(fv.toEcc, fv.threePhase) * o.svlMargin / 1000;
    const svl = o.svlClassesKv.find((k) => k >= need) ?? null;
    const eccMin = eccMinAreaMm2(run.If1, o.faultS);
    study.lambda1 = 0; study.lossKW = 0; study.standingV = sv; study.fault = fv; study.linkBoxes = 2;
    study.svl = { count: 3, ucKv: svl, needKv: need, where: 'open end' };
    study.ecc = { areaMm2: o.eccAreaMm2, minAreaMm2: eccMin, ok: o.eccAreaMm2 >= eccMin, eccShare: fv.eccShare };
    if (!svl) reasons.push(`Through-fault standing voltage ${(need / o.svlMargin).toFixed(1)} kV is above the SVL ladder: shorten the section or cross-bond.`);
    if (!study.ecc.ok) reasons.push(`ECC ${o.eccAreaMm2} mm² is below the adiabatic minimum ${eccMin.toFixed(0)} mm²: increase it.`);
    marks.push({ atM: 0, kind: 'screen-earth', label: 'screens earthed, ECC bonded' },
      { atM: L, kind: 'svl-link', label: `SVL link box, 3 SVLs ${svl ?? '?'} kV` }, { atM: L / 2, kind: 'ecc', label: `ECC ${o.eccAreaMm2} mm² Cu, transposed at mid-point` });
  } else {
    const minorMax = Math.min(o.drumM, spLimitM);
    const majors = Math.max(1, Math.ceil(L / (3 * minorMax)));
    const minor = L / (3 * majors), minorM = [minor, minor, minor];
    const xb = crossBonding(geo, { I, R, minorM, freq: o.freq });
    const fv = faultStandingVoltage(geo, { If3: run.If3, If1: run.If1, lengthM: minor, freq: o.freq, soilOhmM: o.soilOhmM, earthOhm: o.earthOhm,
      ecc: { ...o.eccMm, areaMm2: o.eccAreaMm2 } });
    const need = Math.max(fv.toEcc, fv.threePhase) * o.svlMargin / 1000;
    const svl = o.svlClassesKv.find((k) => k >= need) ?? null;
    // Sensitivity: 5 % unequal minor sections, the usual site reality.
    const xbUneq = crossBonding(geo, { I, R, minorM: [minor * 0.95, minor, minor * 1.05], freq: o.freq });
    study.lambda1 = xb.lambda1; study.lambda1Unequal5 = xbUneq.lambda1; study.lossKW = geo.Rs * xb.J.reduce((s, j) => s + j * j, 0) * L / 1000;
    study.standingV = xb.linkBoxV; study.fault = fv; study.majors = majors; study.minorM = minor;
    study.linkBoxes = 4 * majors; study.svl = { count: 6 * majors, ucKv: svl, needKv: need, where: 'cross-bonding link boxes' };
    study.ecc = null;
    for (let m = 0; m < majors; m++) {
      const x0 = m * 3 * minor;
      if (m === 0) marks.push({ atM: 0, kind: 'screen-earth', label: 'screens solidly earthed' });
      marks.push({ atM: x0 + minor, kind: 'cross-link', label: `cross-bonding link box, 3 SVLs ${svl ?? '?'} kV` },
        { atM: x0 + 2 * minor, kind: 'cross-link', label: `cross-bonding link box, 3 SVLs ${svl ?? '?'} kV` },
        { atM: x0 + 3 * minor, kind: 'screen-earth', label: 'screens solidly earthed (star point)' });
    }
    if (!svl) reasons.push('Through-fault standing voltage is above the SVL ladder: shorten the minor sections.');
  }
  study.ratingVsSinglePoint = ratingRatio(0, study.lambda1);
  study.marks = marks;
  study.rows = bondingRows(study);
  return Object.freeze(study);
}

const NAME = { solid: 'Solid (both ends)', 'single-point': 'Single-point, with ECC', cross: 'Cross-bonded' };

/** Rows for the follow-the-power panel and the Check HUD, in the same [label, value] form as sld-follow.mjs. */
export function bondingRows(s) {
  const f = (x, d = 1) => (Number.isFinite(x) ? x.toFixed(d) : '—');
  const rows = [['Screen bonding', NAME[s.choice]], ['Screen loss factor', `λ1 ${f(s.lambda1, 3)}${s.choice === 'solid' ? ` (${f(s.solidScreenA, 0)} A in each screen)` : ''}`],
    ['Screen loss', `${f(s.lossKW, 2)} kW over ${f(s.lengthM, 0)} m`],
    ['Rating vs single-point', `${f(s.ratingVsSinglePoint * 100, 1)} %`],
    ['Standing voltage, full load', s.choice === 'solid' ? '0 V (screens earthed both ends)' : `${f(s.standingV, 0)} V at ${s.choice === 'cross' ? 'link boxes' : 'the open end'}`]];
  if (s.fault) rows.push(['Standing voltage, through fault', `${f(Math.max(s.fault.toEcc, s.fault.threePhase) / 1000, 2)} kV`]);
  if (s.svl) rows.push(['SVLs', `${s.svl.count} × ${s.svl.ucKv ?? '?'} kV class at ${s.svl.where}`]);
  rows.push(['Link boxes', `${s.linkBoxes}${s.choice === 'cross' ? ` (${s.majors} major section${s.majors > 1 ? 's' : ''} of 3 × ${f(s.minorM, 0)} m)` : ''}`]);
  if (s.ecc) rows.push(['ECC', `${s.ecc.areaMm2} mm² Cu (adiabatic minimum ${f(s.ecc.minAreaMm2, 0)} mm²)${s.ecc.ok ? '' : ' — too small'}`]);
  rows.push(['Why', s.reasons[0]], ['Note', DISCLAIMER]);
  return rows;
}

/** Map marks along a cable path (array of [x, y, z?] points) to world positions for the SLD / 3D overlay. */
export function placeMarks(marks, path) {
  const seg = []; let tot = 0;
  for (let i = 1; i < path.length; i++) { const l = Math.hypot(path[i][0] - path[i - 1][0], path[i][1] - path[i - 1][1]); seg.push(l); tot += l; }
  return marks.map((m) => {
    let d = Math.min(Math.max(0, m.atM), tot) * (tot ? 1 : 0), i = 0;
    while (i < seg.length - 1 && d > seg[i]) { d -= seg[i]; i++; }
    const a = path[i], b = path[Math.min(i + 1, path.length - 1)], t = seg[i] ? d / seg[i] : 0;
    return { ...m, at: a.map((v, k) => v + ((b[k] ?? v) - v) * t) };
  });
}

Earth Study

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, substations, 33kV and transformers, using BS 7430 and BS 7671.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/earth-study.mjs · lines 1–193 of 193 · version 2026-09-27 18:53 · pattern polyLen (shared by 44 files)

What it does
It calculates cables, substations, 33kV and transformers. Defines 11 functions or classes, including blockRects, size, polyLen, earthStudy, fieldMesh.
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, substations, 33kV, transformers.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Earth Mount (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It is built from the block rects helper (`blockRects`), the size step (`size`) and the poly len helper (`polyLen`). The earthing study of the placed solar block, from its geometry and single-line network, using the three earthing engines (`earth-pv.mjs`, `earth-grid.mjs`, `earth-screen.mjs`). Its code works with 33 kV and 10 MVA.
Why it matters
Imported by Earth Mount.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Earth Grid (import), Earth Photovoltaic (PV) (import), Earth Screen (import), Cable Rating (import), Station (import), Single-Line Diagram (SLD) Rules (import)
Used by
imported by Earth Mount (import)
Produces
EARTH_DEFAULTS, DC_WORDS, blockRects, earthStudy, earthChecks, earthRows
Defines here
blockRects, size, polyLen, earthStudy, fieldMesh, ring, up, gt, earthChecks, add, earthRows
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/earth-study.mjs:1-193 · blob c86d021488574c569d2b581135045247ed099395 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// earth-study.mjs: the earthing study of the placed solar block, from its geometry and single-line network, using the
// three earthing engines (earth-pv.mjs, earth-grid.mjs, earth-screen.mjs). Pure: no DOM. Loaded by earth-mount.mjs only.
//   stations    each station pad's earth ring and rods, in parallel with the array bonding mesh under its field
//   substation  the compound's earth grid (mesh and perimeter rods), EPR, touch, step and fence against tolerable limits
//   array       PV earthing of one 10 MVA station: LV earth-fault loop, DC insulation, bonding mesh, piles (earth-pv)
//   cables      screen bonding of each 33 kV feeder cable (earth-screen): arrangement, standing voltage, SVLs, ECC
// Every figure is illustrative, early design only, with no warranty: soil, fault currents, split factor and clearance
// times are assumptions the owner types over. Standards are cited by number and clause only; nothing is copied.

import { studyEarthGrid, tolerable } from './earth-grid.mjs';
import { blockEarthing, meshResistance, BLOCK_DEFAULTS } from './earth-pv.mjs';
import { recommendBonding, BONDING_DEFAULTS as SB } from './earth-screen.mjs';
import { build as cableBuild, rating } from './cable-rating.mjs';
import { STATION_DEFAULTS as SD, tableShape, tableOrigin } from './station.mjs';
import { ELEC_FOOTER, fmtQ } from './sld-rules.mjs';

// The typed settings and their assumed defaults (every one can be typed over; see cmd-grammar.mjs, earthing verbs).
export const EARTH_DEFAULTS = Object.freeze({
  rho: 100, rhoTyped: false,       // soil resistivity, ohm.m: assumed until typed or surveyed (uniform soil)
  ringDepth: 0.6, rods: 4, rodLength: 2.4, mesh: 5, // station ring depth, rods per station, rod length, substation mesh (m)
  earthTarget: null,               // resistance target, ohm: a typed setting, never a standard's limit; no default
  bonding: 'auto',                 // 33 kV screen bonding: auto (recommended per cable), both-ends, single-point, cross
  split: 0.5,                      // share of the HV earth-fault current returning through the compound grid (assumed)
  hvFaultTs: 0.5, mvFaultTs: 0.5,  // shock (clearance) times, s (assumed)
  standingLimitV: SB.touchLimitV,  // screen standing-voltage limit at an open end, V (a setting: use the operator's own)
  dcSystem: 'floating'             // DC array: floating (IT on DC, insulation monitoring), typical for transformerless string
});                                // inverters; 'earthed' (one pole) only with the inverter maker's galvanic isolation
export const DC_WORDS = Object.freeze({ floating: 'floating (typical for transformerless string inverters): insulation monitoring, no pole earthed',
  earthed: "one pole earthed: only where the inverter gives galvanic isolation, as its maker specifies" });
const PAD_MARGIN = 12;             // the station pad: 12 m round the transformers, as block-build.mjs levels it
const CRUSHED_ROCK = { rhoS: 3000, hS: 0.1 }; // compound surface layer (assumed)
const T = tableShape(SD);

/** Station and field rectangles in national-grid metres: { id, pad: [e0, n0, e1, n1], field: [...], off: [dx, dy] }. */
export function blockRects(b) {
  const [E, N] = b.anchor, mv = b.built.mv, s0 = mv.stations[0].offset;
  const txs = SD.transformers, px = txs.map(p => p[0]), py = txs.map(p => p[1]);
  const org = Array.from({ length: SD.tables }, (_, n) => tableOrigin(n, SD));
  const W = Math.max(...org.map(o => o[0])) + T.depth + 1, H = Math.max(...org.map(o => o[1])) + T.span + 1;
  const stations = mv.stations.map((S, i) => {
    const [ox, oy] = S.offset, e = E + ox, n = N + oy;
    return { id: S.id, off: [ox - s0[0], oy - s0[1]], level: b.built.pads?.[i]?.level,
      pad: [e + Math.min(...px) - PAD_MARGIN, n + Math.min(...py) - PAD_MARGIN, e + Math.max(...px) + PAD_MARGIN, n + Math.max(...py) + PAD_MARGIN],
      field: [e - T.depth - 1, n - 3, e + W, n + H], tables: org.map(([x, y]) => [e + x, n + y]) };
  });
  const C = mv.compound;
  return { stations, compound: [E + C.x - C.w / 2, N + C.y - C.d / 2, E + C.x + C.w / 2, N + C.y + C.d / 2], compoundLevel: b.built.compoundPad?.level,
    tableSpan: T.span, fieldRows: SD.tables / 4 };
}
const size = r => [r[2] - r[0], r[3] - r[1]];
const polyLen = pts => pts.reduce((t, p, i) => (i ? t + Math.hypot(p[0] - pts[i - 1][0], p[1] - pts[i - 1][1]) : 0), 0);

/**
 * earthStudy({ block: world.block.built(), net: { g, ro } | null, settings }) -> the whole study: { stations, worstStation,
 * substation, array, cables, rects, settings, checks, footer }. net is the single-line network (sld-mount graph()).
 */
export function earthStudy({ block, net = null, settings = {} }) {
  const S = { ...EARTH_DEFAULTS, ...settings }, rects = blockRects(block), rho = S.rho;
  const nerA = net?.g?.params?.nerA ?? 1000, sourceKA = net?.g?.params?.sourceKA ?? 40;
  // ---- array: one 10 MVA station's PV earthing, its AC circuit lengths from the placed design ----
  const inv = block.built.summary?.inventory || {};
  const lengths = (block.built.cables?.ac || []).map(c => polyLen(c.points || [])).filter(x => x > 1);
  const array = blockEarthing({ rhoOhmM: rho, inverterKVA: inv.inverterKVA || SD.inverterKVA, inverters: SD.inverters,
    ...(lengths.length ? { lengthsM: lengths } : {}) });
  // ---- stations: pad ring + rods, in parallel with the field's bonding mesh ----
  const fieldMesh = st => { const [w, h] = size(st.field), bp = array.bonding;
    return meshResistance(rho, w * h, bp.lengthM * (w * h) / Math.max(1, bp.areaM2), S.ringDepth).sverak; };
  const ring = st => { const [Lx, Ly] = size(st.pad);
    return studyEarthGrid({ soil: { rho }, grid: { Lx, Ly, nx: 2, ny: 3, h: S.ringDepth, rods: { n: S.rods, L: S.rodLength } },
      fault: { If: nerA, Sf: 1, ts: S.mvFaultTs, tf: S.mvFaultTs }, fence: null, latticeM: 1, segM: 2 }); };
  const r0 = ring(rects.stations[0]);            // every pad is the same shape: one numerical solve serves them all
  const stations = rects.stations.map(st => {
    const Rring = r0.worst.Rg, Rmesh = fieldMesh(st), R = 1 / (1 / Rring + 1 / Rmesh), epr = nerA * R;
    const pu = r0.numeric ? { touch: r0.numeric.Em / r0.numeric.GPR, step: r0.numeric.Es / r0.numeric.GPR } : { touch: 0.5, step: 0.2 };
    return { id: st.id, Rring, Rmesh, R, epr, touch: pu.touch * epr, step: pu.step * epr, limits: r0.limits };
  });
  const worstStation = stations.reduce((w, s) => (s.touch > w.touch ? s : w), stations[0]);
  // ---- substation compound grid ----
  const [Lx, Ly] = size(rects.compound);
  const sub = studyEarthGrid({ soil: { rho, surface: CRUSHED_ROCK }, grid: { Lx, Ly, D: S.mesh, h: S.ringDepth, rods: { n: Math.max(4, 2 * S.rods), L: S.rodLength } },
    fault: { If: sourceKA * 1000, Sf: S.split, ts: S.hvFaultTs, tf: S.hvFaultTs }, fence: { offsetM: 1, bonded: true, stepM: 3 },
    latticeM: 1.5, segM: Math.max(S.mesh / 2, 2) });
  // ---- 33 kV feeder cables: screen bonding ----
  const cables = [];
  for (const br of net?.g?.branches || []) {
    if (br.kind !== 'feeder-cable' || br.open || !(br.lengthM > 1) || !br.areaMm2) continue;
    const ro = net.ro?.branches?.get(br.id), from = net.ro?.nodes?.get(br.from), c = cableBuild(br.areaMm2);
    const run = { id: br.id, kv: 33, lengthM: br.lengthM, loadA: Math.max(1, ro?.currentA || 0), R: rating(br.areaMm2).R,
      If3: (from?.faultKA || 20) * 1000, If1: nerA, formation: 'trefoil', sMm: c.od, screenMeanMm: (c.di + c.ds) / 2, screenAreaMm2: 35, screenMat: 'Cu' };
    const force = { 'both-ends': { solidAcceptPct: Infinity }, 'single-point': { solidAcceptPct: -1, touchLimitV: 1e9 }, cross: { solidAcceptPct: -1 } }[S.bonding] || {};
    const st = recommendBonding(run, { soilOhmM: rho, touchLimitV: S.standingLimitV, ...force });
    cables.push({ id: br.id, path: br.path || null, study: st });
  }
  const out = { settings: S, rects, nerA, sourceKA, array, stations, worstStation, ring: r0, substation: sub, cables, footer: ELEC_FOOTER };
  out.checks = earthChecks(out);
  return out;
}

const up = s => String(s).toUpperCase();
const gt = f => (f ? '>' : '≤'), lt = f => (f ? '<' : '≥'); // the comparison the numbers show: a passing line never prints '>'
/** Check HUD lines (hud-checks.mjs shape): { id, failed, line, working: { inputs, standard, note } }; red only when failed. */
export function earthChecks(s) {
  const out = [], S = s.settings, rhoWord = `ρ ${fmtQ(S.rho, 'Ω·m', 2)} ${S.rhoTyped ? 'typed' : 'assumed'}`;
  const add = (id, failed, line, inputs, standard) => out.push({ id, failed: !!failed, line: up(line),
    working: { inputs: [...inputs, ['Soil', rhoWord]], standard, note: ELEC_FOOTER } });
  const w = s.worstStation, sub = s.substation, u = sub.worst;
  if (S.earthTarget != null) {
    const worstR = Math.max(...s.stations.map(x => x.R));
    add('earth-target', worstR > S.earthTarget, `STATION EARTH ${fmtQ(worstR, 'Ω', 2)} ${gt(worstR > S.earthTarget)} ${fmtQ(S.earthTarget, 'Ω', 2)} TARGET SET · ${rhoWord}`,
      [['Worst station (ring ∥ array mesh)', fmtQ(worstR, 'Ω', 2)], ['Target', `${S.earthTarget} Ω (typed setting, not a standard's limit)`]], 'BS 7430; BS 7671 Chapter 54');
    add('grid-target', u.Rg > S.earthTarget, `SUBSTATION GRID ${fmtQ(u.Rg, 'Ω', 2)} ${gt(u.Rg > S.earthTarget)} ${fmtQ(S.earthTarget, 'Ω', 2)} TARGET SET`,
      [['Grid resistance (worse of two methods)', fmtQ(u.Rg, 'Ω', 2)], ['Target', `${S.earthTarget} Ω (typed)`]], 'IEEE 80 cl. 14');
  }
  const gin = [['Grid', `${fmtQ(sub.geo.Lx, 'm', 3)} × ${fmtQ(sub.geo.Ly, 'm', 3)}, ${fmtQ(sub.geo.D, 'm', 2)} mesh, ${sub.geo.rods.length} rods`],
    ['Grid current', `${fmtQ(sub.IG, 'A', 3)} (fault ${s.sourceKA} kA assumed × split ${S.split} assumed)`], ['EPR', fmtQ(u.GPR, 'V', 2)]];
  add('grid-touch', !sub.verdict.touch, `SUBSTATION TOUCH ${fmtQ(u.Em, 'V', 2)} ${gt(!sub.verdict.touch)} ${fmtQ(sub.limits.touch, 'V', 2)} TOLERABLE · EPR ${fmtQ(u.GPR, 'V', 2)}`,
    [...gin, ['Touch (worse of two methods)', fmtQ(u.Em, 'V', 2)], ['Tolerable', `${fmtQ(sub.limits.touch, 'V', 2)} (${sub.limits.basis}, crushed rock assumed)`]],
    'IEEE 80 cl. 8, 16; EN 50522 / IEC 61936-1 cl. 10 (its curve not shipped)');
  add('grid-step', !sub.verdict.step, `SUBSTATION STEP ${fmtQ(u.Es, 'V', 2)} ${gt(!sub.verdict.step)} ${fmtQ(sub.limits.step, 'V', 2)} TOLERABLE`,
    [...gin, ['Step (worse of two methods)', fmtQ(u.Es, 'V', 2)], ['Tolerable', fmtQ(sub.limits.step, 'V', 2)]], 'IEEE 80 cl. 8, 16');
  if (sub.fence) add('grid-fence', !sub.fence.pass, `COMPOUND FENCE TOUCH ${fmtQ(sub.fence.touchV, 'V', 2)} ${gt(!sub.fence.pass)} ${fmtQ(sub.fence.limit, 'V', 2)} · ${sub.fence.advice}`,
    [['Fence', sub.fence.bonded ? 'bonded to the grid' : 'separately earthed'], ['Touch 1 m outside', fmtQ(sub.fence.touchV, 'V', 2)]], 'IEEE 80 cl. 17');
  add('station-touch', w.touch > w.limits.touch, `STATION ${w.id} TOUCH ${fmtQ(w.touch, 'V', 2)} ${gt(w.touch > w.limits.touch)} `
    + `${fmtQ(w.limits.touch, 'V', 2)} TOLERABLE · EPR ${fmtQ(w.epr, 'V', 2)}`,
    [['33 kV earth fault', `${fmtQ(s.nerA, 'A', 3)} (NER limit, assumed)`], ['Ring ∥ array mesh', `${fmtQ(w.Rring, 'Ω', 2)} ∥ ${fmtQ(w.Rmesh, 'Ω', 2)} = ${fmtQ(w.R, 'Ω', 2)}`],
      ['Touch on the pad', fmtQ(w.touch, 'V', 2)], ['Tolerable', `${fmtQ(w.limits.touch, 'V', 2)} (${w.limits.basis}, no surface layer)`]], 'IEEE 80 cl. 8; BS 7430');
  const a = s.array.worst;
  add('lv-earth-fault', !a.disconnects, `LV EARTH FAULT ${fmtQ(a.Ief / 1000, 'kA', 3)} ${lt(!a.disconnects)} ${fmtQ(a.Ia / 1000, 'kA', 3)} IA AT ${a.permittedS} S`
    + ` · CIRCUIT ${fmtQ(a.lengthM, 'm', 3)}`
    + ` (MOST ${fmtQ(a.maxLengthM, 'm', 3)})`, [['Loop impedance', fmtQ(a.Zs * 1000, 'mΩ', 3)], ['Least earth-fault current', fmtQ(a.Ief, 'A', 3)],
    ['Ia at the permitted time', `${fmtQ(a.Ia, 'A', 3)} within ${a.permittedS} s, ${a.circuit} circuit (device curve assumed; editable)`],
    ['Fast clearing (instantaneous)', a.fast ? `${fmtQ(a.fast.Ia, 'A', 3)} pick-up; longest ${fmtQ(a.fast.maxLengthM, 'm', 3)}` : '—'],
    ['Touch at the inverter', fmtQ(a.touchV, 'V', 2)]], 'BS 7671 411.3.2, 411.4; IEC 60364-4-41');
  add('lv-cpc', a.cpcOk === false, `LV PROTECTIVE CONDUCTOR BELOW ${fmtQ(a.cpcMinMm2, 'mm²', 2)} ADIABATIC`, [['Least area', fmtQ(a.cpcMinMm2, 'mm²', 2)]], 'BS 7671 543.1.3');
  // The DC array's earthing, always said (an editable setting: earthing dc floating | earthed); a pole earthed is red.
  add('dc-system', S.dcSystem === 'earthed', S.dcSystem === 'earthed' ? 'DC POLE EARTHED: NEEDS THE INVERTER MAKER’S GALVANIC ISOLATION AND APPROVAL'
    : 'DC ARRAY: FLOATING (TYPICAL FOR TRANSFORMERLESS STRING INVERTERS) · EDITABLE: EARTHING DC EARTHED', [['DC system', DC_WORDS[S.dcSystem]],
    ['LV AC', 'TN, winding star earthed at the station (assumed; IT windings need the inverter maker’s approval)']], 'IEC 62548-1 (array earthing); IEC TS 62738');
  out.at(-1).always = true;
  const cs = s.cables.map(c => c.study), sv = cs.filter(c => c.choice !== 'solid').sort((p, q) => q.standingV - p.standingV)[0];
  if (sv) add('screen-standing', sv.standingV > S.standingLimitV, `33 KV SCREEN ${sv.id} ${sv.choice} ${fmtQ(sv.standingV, 'V', 2)} STANDING `
    + `${gt(sv.standingV > S.standingLimitV)} ${S.standingLimitV} V SET`,
    [['Arrangement', sv.choice], ['Standing voltage, full load', fmtQ(sv.standingV, 'V', 2)], ['Limit', `${S.standingLimitV} V (a setting: the operator's own value)`]],
    'IEC 60287-1-1 2.3; BS 7671 411 (touch idea)');
  const ecc = cs.find(c => c.ecc && !c.ecc.ok);
  if (ecc) add('screen-ecc', true, `33 KV ${ecc.id} ECC ${ecc.ecc.areaMm2} MM² < ${fmtQ(ecc.ecc.minAreaMm2, 'mm²', 2)} ADIABATIC`,
    [['ECC', `${ecc.ecc.areaMm2} mm² Cu (assumed)`], ['Adiabatic minimum', fmtQ(ecc.ecc.minAreaMm2, 'mm²', 2)]], 'IEC 60949; BS 7671 543.1.3');
  const svl = cs.find(c => c.svl && c.svl.ucKv == null);
  if (svl) add('screen-svl', true, `33 KV ${svl.id} THROUGH-FAULT SCREEN VOLTAGE ABOVE THE SVL LADDER`, [['Needs', fmtQ(svl.svl.needKv, 'kV', 2)]], 'IEC 60287-1-1; IEEE 575 (concepts)');
  return out;
}

/** Readout sections for the earthing panel and the SLD: [{ title, rows: [[label, value]] }]; the footer closes the list. */
export function earthRows(s, which = null) {
  const S = s.settings, sub = s.substation, u = sub.worst, w = s.worstStation, a = s.array;
  const rhoV = `${fmtQ(S.rho, 'Ω·m', 2)} (${S.rhoTyped ? 'typed' : 'assumed'}; uniform soil; a Wenner survey replaces it)`;
  const sections = [];
  const st = which ? s.stations.find(x => x.id === which) : null;
  if (st) sections.push({ title: `Station ${st.id} earth`, rows: [
    ['Electrode', `ring ${fmtQ(s.ring.geo.Lx, 'm', 2)} × ${fmtQ(s.ring.geo.Ly, 'm', 2)} at ${S.ringDepth} m + ${S.rods} rods × ${S.rodLength} m`],
    ['Soil ρ', rhoV], ['Ring and rods', fmtQ(st.Rring, 'Ω', 2)], ['Array bonding mesh', fmtQ(st.Rmesh, 'Ω', 2)], ['Together', fmtQ(st.R, 'Ω', 2)],
    ['EPR, 33 kV earth fault', `${fmtQ(st.epr, 'V', 2)} at ${fmtQ(s.nerA, 'A', 3)} (NER limit, assumed)`],
    ['Touch · step on the pad', `${fmtQ(st.touch, 'V', 2)} · ${fmtQ(st.step, 'V', 2)} (tolerable ${fmtQ(st.limits.touch, 'V', 2)} · ${fmtQ(st.limits.step, 'V', 2)})`],
    ['Bonded to', 'transformer tanks, LV board PE bar, inverter frames, table steel, RMU'],
    ['Basis', 'own code after the published rod and grid formulas and a numerical check; BS 7430; BS 7671 Ch. 54; IEEE 80 cl. 8, 14']] });
  else sections.push({ title: 'Stations', rows: [['Soil ρ', rhoV], ['Station earth (ring ∥ mesh)', s.stations.map(x => `${x.id} ${fmtQ(x.R, 'Ω', 2)}`).join(' · ')],
    ['Worst touch · EPR', `${w.id} ${fmtQ(w.touch, 'V', 2)} · ${fmtQ(w.epr, 'V', 2)} (tolerable ${fmtQ(w.limits.touch, 'V', 2)})`]] });
  if (!which || which === 'substation') sections.push({ title: 'Substation earth grid', rows: [
    ['Grid', `${fmtQ(sub.geo.Lx, 'm', 3)} × ${fmtQ(sub.geo.Ly, 'm', 3)}, ${fmtQ(sub.geo.D, 'm', 2)} mesh at ${sub.geo.h} m, ${sub.geo.rods.length} rods × ${sub.geo.Lr} m`],
    ['Resistance', `${fmtQ(u.Rg, 'Ω', 2)} (closed form ${fmtQ(sub.closed.Rg, 'Ω', 2)}${sub.numeric ? `, numerical ${fmtQ(sub.numeric.Rg, 'Ω', 2)}` : ''})`],
    ['Grid current', `${fmtQ(sub.IG, 'A', 3)} (${s.sourceKA} kA assumed × split ${S.split} assumed × decrement ${fmtQ(sub.Df, '', 3)})`],
    ['Earth potential rise', fmtQ(u.GPR, 'V', 2)], ['Touch', `${fmtQ(u.Em, 'V', 2)} (tolerable ${fmtQ(sub.limits.touch, 'V', 2)})`],
    ['Step', `${fmtQ(u.Es, 'V', 2)} (tolerable ${fmtQ(sub.limits.step, 'V', 2)})`],
    ...(sub.fence ? [['Fence (bonded)', `${fmtQ(sub.fence.touchV, 'V', 2)} touch 1 m outside`]] : []),
    ...sub.hot.filter(h => h.exceeded).map(h => [`Hot zone ${h.V} V`, `about ${fmtQ(h.radiusM, 'm', 2)} from the grid centre`]),
    ['Earth conductor', `${sub.conductor.pickMm2 ?? 'over 400'} mm² Cu (needs ${fmtQ(sub.conductor.needMm2, 'mm²', 2)})`],
    ...sub.warnings.map(x => ['Caution', x]), ['Basis', 'IEEE 80 cl. 8, 11, 14-17; EN 50522; IEC 61936-1 cl. 10; IEC 60949']] });
  if (!which) sections.push({ title: 'PV array (one 10 MVA station)', rows: [
    ['LV earth fault, longest circuit', `${fmtQ(a.worst.Ief / 1000, 'kA', 3)} vs pick-up ${fmtQ(a.worst.Ia / 1000, 'kA', 3)}; longest that reaches it ${fmtQ(a.worst.maxLengthM, 'm', 3)}`],
    ['DC array', `${DC_WORDS[S.dcSystem]} (editable: earthing dc floating or earthing dc earthed)`],
    ['Touch at an inverter', `${fmtQ(a.worst.touchV, 'V', 2)} (bond frame, structure and pile locally)`],
    ['DC insulation, one inverter', `${fmtQ(a.insulation.perInverter.risoOhm / 1000, 'kΩ', 2)} healthy wet (${fmtQ(a.insulation.wholeBlock.risoOhm / 1000, 'kΩ', 2)} if one array)`],
    ['Bonding mesh', `${fmtQ(a.bonding.lengthM, 'm', 3)} of ${fmtQ(a.bonding.sizeMm2, 'mm²', 2)} Cu, ${a.bonding.across} cross runs`],
    ['Basis', 'BS 7671 411.4, 543.1.3, Section 712; IEC 62548-1 6.4.3, 7.3.2; IEC TS 62738 6.4, 6.5.1']] });
  if (!which || which === 'cables') {
    const by = {}; for (const c of s.cables) by[c.study.choice] = (by[c.study.choice] || 0) + 1;
    const worst = s.cables.map(c => c.study).sort((p, q) => q.standingV - p.standingV)[0];
    sections.push({ title: '33 kV cable screens', rows: [['Bonding', `${S.bonding}: ${Object.entries(by).map(([k, n]) => `${n} ${k}`).join(', ') || 'no cables'}`],
      ...(worst ? [['Highest standing voltage', `${fmtQ(worst.standingV, 'V', 2)} on ${worst.id} (${worst.choice}; limit set ${S.standingLimitV} V)`]] : []),
      ['Basis', 'IEC 60287-1-1 2.3; IEC 60949; BS 7671 543.1.3']] });
  }
  return { sections, footer: ELEC_FOOTER };
}

Extensions

A JavaScript module in the world folder of GlobalGrid2050. It is built from the mount extensions helper (`mountExtensions`).

renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/extensions.mjs · lines 1–16 of 16 · version 2026-09-27 18:53

What it does
Defines ONE, mountExtensions. Side effects: changes the web page (DOM).
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.
Downstream impact
Used directly by 1 file: Substrate (globalgrid2050). Reached from 1 other entry point, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/).
What it achieves
Extensions mounted after the first frame, each in its own chunk: a failure in one is a console line, never a broken page.
Why it matters
Imported by Substrate.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Substrate (dynamic import)
Produces
mountExtensions
Defines here
ONE, mountExtensions
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/extensions.mjs:1-16 · blob 90e83fec4bbc6f376926f2c32f9e8b8dc3cc3c93 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Extensions mounted after the first frame, each in its own chunk: a failure in one is a console line, never a broken page.
// buggy-mount.mjs (E, a chip, "buggy on"), hud-ui.mjs (failed checks), senses-mount.mjs (jump, binoculars),
// table-solids.mjs (the plant's tables as solids: land on them when jumping), packs-mount.mjs (layer packs, world.pack.v1).
// Each mount sets its window.* handle for tests and the console, as the substrate did before this file.
const ONE = (path, name, handle, mount) => import(path).then(m => mount(m)).then(v => { window[handle] = v; }).catch(e => console.warn(`${name}: ${e.message}`));

/** mountExtensions({ api }): starts every extension's load; returns the promises (tests may wait on them). */
export function mountExtensions({ api }) {
  return [
    ONE('./buggy-mount.mjs', 'buggy', 'worldBuggy', m => m.mountBuggy({ api })),
    ONE('./hud-ui.mjs', 'check HUD', 'worldHud', m => m.mountHud({ api, world: window.world })),
    ONE('./senses-mount.mjs', 'jump, binoculars', 'worldSenses', m => m.mountSenses({ api, world: window.world })),
    ONE('./table-solids.mjs', 'table solids', 'worldTableSolids', m => m.mountTableSolids({ api, plant: window.world.plant })),
    ONE('./packs-mount.mjs', 'packs', 'worldPacks', m => m.mountPacks({ api })),
  ];
}

Fade

A JavaScript module in the world folder of GlobalGrid2050 that works with far plane (`farPlane`). It is built from the fade for helper (`fadeFor`) and the far plane helper (`farPlane`).

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/fade.mjs · lines 1–17 of 17 · version 2026-09-27 18:53 · Entry point · pattern farPlane (shared by 3 files)

What it does
It calculates its inputs. Defines fadeFor, farPlane.
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.
Downstream impact
Used directly by 3 files: Layers UI (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
How far the world is drawn before it fades out, and the far plane that follows it.
Why it matters
Loaded by the Site World page at https://globalgrid2050.com/solar-design-studio/202609271853-site-world/. Also imported by Layers UI and Substrate.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Layers UI (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import)
Produces
FADE_M, PLANT_FADE_MAX_M, fadeFor, farPlane
Defines here
fadeFor, farPlane
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/fade.mjs:1-17 · blob ef8ba0ed9a6a2c040cb229cb88632bd6ff9a62d5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// How far the world is drawn before it fades out, and the far plane that follows it. Pure.
export const FADE_M = 450, FAR_M = 5000, MILE_M = 1609.344;

// view: 'standing' | 'aerial'; above: eye height above the ground (m); rangeM: the wider-area roads and rail range
// when that layer is on, else 0. The fade grows 2.5 m per metre up, to 4 km (phone review: a high drone still sees the
// ground below). With the wider area on, a drone sees 30 m per metre up, never past the chosen range.
// plantM: the diagonal of a laid-out plant (0 without one). A drone framing a large plant sees all of it: past 4 km the
// fade keeps growing with height, up to 1.2 times the plant's diagonal (and never past PLANT_FADE_MAX_M).
export const PLANT_FADE_MAX_M = 12000;
export function fadeFor(view, above, rangeM = 0, plantM = 0) {
  const h = Math.max(0, Number.isFinite(above) ? above : 0), base = Math.min(4000, FADE_M + h * 2.5);
  let f = view === 'aerial' && rangeM > 0 ? Math.max(base, Math.min(Math.max(FADE_M, 30 * h), rangeM)) : base;
  if (view === 'aerial' && plantM > 0) f = Math.max(f, Math.min(FADE_M + h * 2.5, 1.2 * plantM, PLANT_FADE_MAX_M));
  return f;
}

export const farPlane = fade => Math.max(FAR_M, fade * 1.1);

First Showing

A JavaScript module in the world folder of GlobalGrid2050 that reads substations and the Renewable Energy Planning Database (REPD) register. It places label (`placeLabel`) and shows place (`showPlace`).

interactionglobalgrid2050 / solar-design-studio/202609271853-site-world/world/first-showing.mjs · lines 1–94 of 94 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern mountFirstShowing (shared by 2 files)

What it does
It loads substations and the REPD register. Defines 11 functions or classes, including placeLabel, substationLine, pinBatch, mountFirstShowing, $. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
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: substations, the REPD register.
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
The first step, offered once (a small card that opens Find; dismissed for good with × or by using Find), and the place just found. It responds to click, pointerdown and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Bng (import), Origin (import), Labels (import), Accuracy (import)
Used by
none found
Produces
PHONE, SUBSTATION_REACH_M, placeLabel, substationLine, pinBatch, mountFirstShowing
Defines here
placeLabel, substationLine, pinBatch, mountFirstShowing, $, remembered, dismissStart, phone, aside, gridLine, showPlace
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/first-showing.mjs:1-94 · blob b5c7435fa66000ef41cced9385b36e9eef637a84 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// First showing: the first step, offered once (a small card that opens Find; dismissed for good with × or by using
// Find), and the place just found: a card with its grid reference and the nearest substation, and a pin on the ground.
// A REPD project is named on the card by its reference only; project names stay in the Find results the user asked for.
import { gridRef } from './bng.mjs';
import { toLocal } from './origin.mjs';
import { distanceLabel } from './labels.mjs';
import { nearestLine } from './accuracy.mjs';

const START_KEY = 'world.start.dismissed';
export const PHONE = '(max-width: 700px), (pointer: coarse)';
export const SUBSTATION_REACH_M = 5000; // further than this, the grid data here is not the grid near the place

// The words for the place card: "REPD 1234" for a project, else the label the search gave (postcode, coordinates).
export const placeLabel = choice => (choice?.ref != null && choice.ref !== '' ? `REPD ${choice.ref}` : String(choice?.label ?? ''));

// The nearest substation line from { label, d, national? } (or null) and the nearest pylon, in plain words. A substation
// from the national index is the true nearest, so its distance is always given. line (accuracy.mjs nearestLine, or null):
// the nearest overhead line measured to the nearest point on a span, not to a pylon; it replaces the pylon when known.
export function substationLine(sub, tower, line = null) {
  const toLine = line ? ` · nearest ${line.label} ${distanceLabel(line.d)} (to the line)` : '';
  if (sub && (sub.national || sub.d <= SUBSTATION_REACH_M)) return `Nearest ${sub.label}: ${distanceLabel(sub.d)}${toLine}`;
  const none = `No substation within ${SUBSTATION_REACH_M / 1000} km in the grid data loaded`;
  return line ? none + toLine : tower ? `${none} · nearest ${tower.label} ${distanceLabel(tower.d)}` : none;
}

// The pin at (x, y, z) local: a 40 m mast with a diamond on the ground, so it can be seen from the drone.
export function pinBatch(x, y, z, version) {
  const r = 6, h = 40;
  const v = [0, 0, 0, 0, 0, h, -r, 0, 0, 0, r, 0, 0, r, 0, r, 0, 0, r, 0, 0, 0, -r, 0, 0, -r, 0, -r, 0, 0,
    0, 0, h, -3, 0, h - 6, 0, 0, h, 3, 0, h - 6];
  return { key: 'place-pin', version, positions: new Float32Array(v), color: [1, 0.45, 0.85, 1], origin: [x, y, z] };
}

// deps: { doc, canvas, redraw(), origin(), heightAt(x, y), groundVersion(), assets() -> [{ kind, label, e, n }],
//   nearest?(e, n) -> Promise<substation | null> (the national index), openFind() }.
export function mountFirstShowing({ doc = document, canvas, redraw, origin, heightAt, groundVersion, assets = () => [], nearest = null, openFind }) {
  const $ = id => doc.getElementById(id);
  let place = null; // { label, e, n } national-grid metres
  const remembered = () => { try { return localStorage.getItem(START_KEY) === '1'; } catch { return false; } };
  function dismissStart() {
    if ($('start')) $('start').hidden = true;
    try { localStorage.setItem(START_KEY, '1'); } catch { /* private window: it just shows again next time */ }
  }
  // On a phone the card would sit over the view: there Find starts closed and opens only from the Find button.
  const phone = () => { try { return !!globalThis.matchMedia?.(PHONE).matches; } catch { return false; } };
  if ($('start')) $('start').hidden = remembered() || phone();
  $('start-close')?.addEventListener('click', () => { dismissStart(); canvas?.focus(); });
  // The card steps aside once the view is used: a press on the ground or a movement key (user test: it never went).
  const aside = () => { if ($('start') && !$('start').hidden) dismissStart(); };
  canvas?.addEventListener('pointerdown', aside, { once: true });
  doc.addEventListener('keydown', e => { if (/^(Arrow|Key[WASD]$)/.test(e.code || '')) aside(); });
  $('start-go')?.addEventListener('click', () => openFind?.());
  $('place-close')?.addEventListener('click', () => { $('place').hidden = true; place = null; redraw(); canvas?.focus(); });

  // Nearest substation and pylon in the grid data loaded here; the national index answers for the substation when it can.
  async function gridLine(e, n) {
    const all = assets(), near = kind => all.filter(a => a.kind === kind)
      .map(a => ({ ...a, d: Math.hypot(a.e - e, a.n - n) })).sort((a, b) => a.d - b.d)[0] || null;
    let sub = near('substation');
    if (nearest) {
      try {
        const a = await nearest(e, n);
        if (a) sub = { ...a, national: true, d: Math.hypot(a.e - e, a.n - n),
          label: a.label || (a.kv ? `${a.kv} kV substation` : a.tier ? `${a.tier} substation` : 'substation') };
      } catch { /* local data only */ }
    }
    if (!sub && !all.length) return 'Grid data not loaded for this area';
    return substationLine(sub, near('tower'), nearestLine({ e, n }, all.filter(a => a.kind === 'tower')));
  }

  // Names the place just found, pins it, and says what is known there. note: the arrival note (terrain), or ''.
  function showPlace(choice, e, n, note = '') {
    place = { label: placeLabel(choice), e, n };
    $('place-name').textContent = place.label;
    let ref = '';
    try { ref = gridRef(e, n, 8); } catch { /* off the national grid */ }
    $('place-grid').textContent = ref;
    const mine = place;
    gridLine(e, n).then(t => { if (place === mine) $('place-grid').textContent = ref ? `${ref} · ${t}` : t; });
    $('place-terrain').textContent = note;
    $('place').hidden = false;
    redraw();
  }

  return {
    dismissStart, showPlace,
    place: () => (place ? { ...place } : null),
    batches() {
      if (!place) return [];
      const o = origin(), [x, y] = toLocal(o, place.e, place.n);
      return [pinBatch(x, y, heightAt(x, y), `${o.id}:${groundVersion()}:${place.e}:${place.n}`)];
    }
  };
}