GLOBALGRID2050 / EXPLORE CODE

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

Trench and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that works with cut height (`cutHeight`) and offset line (`offsetLine`) and calculates planar distances.

643 lines of JavaScript from globalgrid2050, in 4 files. Topic: Cables and conductors. Section 22 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. Trench Section transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/trench-section.mjs lines 1–148
  2. Trench transform · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/trench.mjs lines 1–301
  3. Cable Checks UI electrical · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/cable-checks-ui.mjs lines 1–90
  4. Cable Checks electrical · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/cable-checks.mjs lines 1–104

Trench Section

A JavaScript module in the world folder of GlobalGrid2050 that works with cables.

transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/trench-section.mjs · lines 1–148 of 148 · version 2026-09-27 02:20 · pattern sectionLines (shared by 3 files)

What it does
It calculates cables. Defines 9 functions or classes, including formationOf, crossSection, halfAt, sectionLines, push.
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 3 files: Design Sections (globalgrid2050); Xray (globalgrid2050); Design Sections (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 formation of helper (`formationOf`), the cross section helper (`crossSection`) and the half at helper (`halfAt`). A trench drawn as a true cross-section, and cables drawn at their real outside diameter.
Why it matters
Imported by Design Sections and Xray.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Design Sections (import), imported by Xray (import), imported by Design Sections (import), mentioned in Standalone (comment link)
Produces
formationOf, crossSection, sectionLines, tubeLines
Defines here
formationOf, crossSection, halfAt, sectionLines, push, rail, tubeLines, frame, off
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/202609270220-site-world-v3/world/trench-section.mjs:1-148 · blob f09a44d25295441dedd1399eaa505b20ef8ba092 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// trench-section.mjs: a trench drawn as a true cross-section, and cables drawn at their real outside diameter.
//
// crossSection(section, eff, opts) works in the plane of the section: u across the trench (metres, left of travel
// positive), z up from the ground at the centreline (negative is below ground). It returns the dug outline (walls
// and floor, battered or supported), the layers (formation over-dig, bedding and surround, backfill), every duct or
// cable as a circle in its formation (trefoil or flat) and spacing, each circuit apart, and the markers (tape,
// tiles) at their depths.
//
// sectionLines(...) lays that section along a real trench: full slices near the viewer (walking up to an open
// trench, or bending down to look in) with the layer, tape and tile lines joined between slices; nothing extra
// further away, where the trench's own wall outline is the clean simplified view.
// tubeLines(...) draws a core as a tube of its outside diameter: four lines along it, rings near the viewer.
// Pure: no imports, no DOM.

const SQ3 = Math.sqrt(3);

// Formation and duct use, from the section's words and numbers.
export function formationOf(section) {
  const f = String(section.formation || '').toLowerCase();
  const ducted = Number(section.duct_od_mm) > 0 || /duct/.test(f);
  const kind = /trefoil/.test(f) ? 'trefoil' : /side by side|flat/.test(f) && !/trefoil/.test(f) ? 'flat' : 'trefoil';
  const perCircuit = /ducts side by side|duct groups/.test(f) ? 'group' : 'three';
  return { kind, ducted, perCircuit, circuits: Math.max(1, Number(section.circuits) || 1) };
}

/**
 * crossSection(section, eff, { cableOdMm }) -> { outline, walls, layers, items, markers, supports, width, depth, topHalf }
 * eff: applyGround(...) output (width, depth, benchSlope, cableDepth, overdig, support).
 */
export function crossSection(section, eff, { cableOdMm = null, tapeAboveM = 0.25 } = {}) {
  const w = eff.width, depth = eff.depth, slope = eff.benchSlope || 0, fm = formationOf(section);
  const halfAt = z => w / 2 + slope * (z + depth);                     // wall half-width at height z
  const topHalf = halfAt(0);
  const outline = [[-topHalf, 0], [-w / 2, -depth], [w / 2, -depth], [topHalf, 0]];
  const ductD = fm.ducted && Number(section.duct_od_mm) > 0 ? section.duct_od_mm / 1000 : 0;
  // A cable in a duct defaults to a little over half the duct bore; a direct-laid one to the section's pitch.
  const cableOd = cableOdMm ? cableOdMm / 1000 : ductD ? 0.55 * ductD : (Number(section.phase_spacing_mm) || 45) / 1000;
  const D = ductD || cableOd;                                           // the circle that sets the formation
  const bed = ((section.bedding && section.bedding.thickness_mm) || 75) / 1000;
  const zBed = -eff.cableDepth + bed;                                   // underside of the lowest duct or cable
  const pitch = Math.max(D, (Number(section.phase_spacing_mm) || 0) / 1000);
  const circuitGap = (Number(section.circuit_spacing_mm) || 0) / 1000;
  const items = [];
  for (let c = 0; c < fm.circuits; c++) {
    const uc = fm.circuits === 1 ? 0 : (c - (fm.circuits - 1) / 2) * Math.max(circuitGap, 3 * pitch + 0.1);
    let at;
    if (fm.perCircuit === 'group') at = [[uc, zBed + D / 2]];
    else if (fm.kind === 'trefoil') at = [[uc - D / 2, zBed + D / 2], [uc + D / 2, zBed + D / 2], [uc, zBed + D / 2 + SQ3 * D / 2]];
    else at = [-1, 0, 1].map(k => [uc + k * pitch, zBed + D / 2]);
    at.forEach(([u, z], k) => {
      items.push({ kind: fm.ducted ? 'duct' : 'cable', circuit: c + 1, phase: fm.perCircuit === 'group' ? null : k + 1, u, z, r: D / 2 });
      if (fm.ducted && fm.perCircuit !== 'group') items.push({ kind: 'cable', circuit: c + 1, phase: k + 1, u, z: z - D / 2 + cableOd / 2, r: cableOd / 2 });
    });
  }
  const topItems = Math.max(...items.map(i => i.z + i.r)), lo = Math.min(...items.map(i => i.u - i.r)), hi = Math.max(...items.map(i => i.u + i.r));
  const zSurround = Math.min(topItems + bed, -0.1);
  const layers = [];
  if (eff.overdig > 0) layers.push({ name: 'formation fill', z0: -depth, z1: -eff.cableDepth });
  layers.push({ name: 'bedding and surround', z0: -eff.cableDepth, z1: zSurround }, { name: 'backfill', z0: zSurround, z1: 0 });
  const markers = [];
  const m = section.marker || {}, mz = -(Number(m.depth_m) || 0);
  // Tiles rest on the surround: at the section's marker depth, never down inside the surround.
  if (/tile|board/i.test(m.type || '')) markers.push({ kind: 'tile', z: Math.min(Math.max(mz, zSurround), -0.2), u0: lo - 0.05, u1: hi + 0.05 });
  const zt = Math.min(topItems + tapeAboveM, -0.15);
  markers.push({ kind: 'tape', z: zt, u0: Math.max(-halfAt(zt) + 0.02, lo - 0.05), u1: Math.min(halfAt(zt) - 0.02, hi + 0.05) });
  const supports = /box|sheet|support/.test(eff.support || '') && slope === 0
    ? [-1, 1].map(side => ({ side, u: side * (w / 2 - 0.04), z0: -depth, z1: 0.3 })) : [];
  return { outline, layers, items, markers, supports, width: w, depth, topHalf, halfAt, formation: fm };
}

/**
 * sectionLines({ trench, groundAt, cs, eye, near = 25, spacing = 2, ringSides = 16 }) -> Float32Array of line pairs
 * trench: createTrench(...) result in local metres; cs: crossSection(...). Only slices within `near` metres of
 * the eye are drawn, so far away the trench is just its wall outline.
 */
export function sectionLines({ trench, groundAt, cs, eye, near = 25, spacing = 2, ringSides = 16 }) {
  const v = [];
  const push = (a, b) => v.push(a[0], a[1], a[2], b[0], b[1], b[2]);
  const L = trench.length2d, count = Math.max(1, Math.floor(L / spacing));
  const slices = [];
  for (let k = 0; k <= count; k++) {
    const s = Math.min(L, k * spacing);
    const [cx, cy] = trench.pointAt(s);
    if (Math.hypot(cx - eye[0], cy - eye[1]) > near) { slices.push(null); continue; }
    const a = trench.pointAt(Math.max(0, s - 0.1)), b = trench.pointAt(Math.min(L, s + 0.1));
    const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, nx = -(b[1] - a[1]) / len, ny = (b[0] - a[0]) / len;
    const g0 = groundAt(cx, cy);
    slices.push(([u, z]) => [cx + nx * u, cy + ny * u, g0 + z]);
  }
  const rails = [];                                   // points repeated on every slice, joined along the trench
  const rail = (key, uz) => rails.push([key, uz]);
  for (const layer of cs.layers) if (layer.z1 < 0) { rail(layer.name + 'L', [-cs.halfAt(layer.z1), layer.z1]); rail(layer.name + 'R', [cs.halfAt(layer.z1), layer.z1]); }
  for (const m of cs.markers) { rail(m.kind + 'L', [m.u0, m.z]); rail(m.kind + 'R', [m.u1, m.z]); }
  slices.forEach((P, k) => {
    if (!P) return;
    for (let i = 1; i < cs.outline.length; i++) push(P(cs.outline[i - 1]), P(cs.outline[i]));
    for (const layer of cs.layers) if (layer.z1 < 0) push(P([-cs.halfAt(layer.z1), layer.z1]), P([cs.halfAt(layer.z1), layer.z1]));
    for (const m of cs.markers) {
      push(P([m.u0, m.z]), P([m.u1, m.z]));
      if (m.kind === 'tile') { push(P([m.u0, m.z + 0.05]), P([m.u1, m.z + 0.05])); push(P([m.u0, m.z]), P([m.u0, m.z + 0.05])); push(P([m.u1, m.z]), P([m.u1, m.z + 0.05])); }
    }
    for (const it of cs.items) {
      const n = it.kind === 'duct' ? ringSides : Math.max(8, ringSides / 2);
      for (let j = 0; j < n; j++) {
        const t0 = 2 * Math.PI * j / n, t1 = 2 * Math.PI * (j + 1) / n;
        push(P([it.u + it.r * Math.cos(t0), it.z + it.r * Math.sin(t0)]), P([it.u + it.r * Math.cos(t1), it.z + it.r * Math.sin(t1)]));
      }
    }
    for (const sp of cs.supports) push(P([sp.u, sp.z0]), P([sp.u, sp.z1]));
    const Q = slices[k + 1];
    if (Q) for (const [, uz] of rails) push(P(uz), Q(uz));
  });
  return new Float32Array(v);
}

/**
 * tubeLines(polyline, od, { eye, near = 20, every = 1, sides = 8 }) -> Float32Array
 * A core drawn at its outside diameter: four lines along it (left, right, top, bottom of the sheath) and, near the
 * eye, a ring every `every` metres. The polyline is the core centre, already bent at its radius by cable-route.mjs.
 */
export function tubeLines(polyline, od, { eye = null, near = 20, every = 1, sides = 8 } = {}) {
  const r = od / 2, v = [], n = polyline.length;
  if (n < 2) return new Float32Array(0);
  const frame = i => {
    const a = polyline[Math.max(0, i - 1)], b = polyline[Math.min(n - 1, i + 1)];
    const dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1;
    return [-dy / l, dx / l];
  };
  const off = (p, [nx, ny], du, dz) => [p[0] + nx * du, p[1] + ny * du, p[2] + dz];
  const sides4 = [[r, 0], [-r, 0], [0, r], [0, -r]];
  let last = -Infinity, s = 0;
  for (let i = 0; i < n; i++) {
    const p = polyline[i], f = frame(i);
    if (i) {
      const q = polyline[i - 1], g = frame(i - 1);
      s += Math.hypot(p[0] - q[0], p[1] - q[1]);
      for (const [du, dz] of sides4) { const a = off(q, g, du, dz), b = off(p, f, du, dz); v.push(...a, ...b); }
    }
    if (eye && s - last >= every && Math.hypot(p[0] - eye[0], p[1] - eye[1], p[2] - eye[2]) <= near) {
      last = s;
      for (let j = 0; j < sides; j++) {
        const t0 = 2 * Math.PI * j / sides, t1 = 2 * Math.PI * (j + 1) / sides;
        v.push(...off(p, f, r * Math.cos(t0), r * Math.sin(t0)), ...off(p, f, r * Math.cos(t1), r * Math.sin(t1)));
      }
    }
  }
  return new Float32Array(v);
}

Trench

A JavaScript module in the world folder of GlobalGrid2050 that works with cut height (`cutHeight`) and offset line (`offsetLine`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/trench.mjs · lines 1–301 of 301 · version 2026-09-27 03:30 · pattern mitredOutline (shared by 2 files)

What it does
It calculates its inputs. Defines 20 functions or classes, including createTrench, pointAt, candidates, floorAt, inside.
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 8 files: Hdd (globalgrid2050); Design UI (globalgrid2050); Design Sections (globalgrid2050); Layers (globalgrid2050); and 4 more. Reached from 4 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050).
What it achieves
It is built from the point at helper (`pointAt`), the candidates step (`candidates`) and the floor at helper (`floorAt`). A trench is a function laid over the ground, never a stored mesh.
Why it matters
Imported by 8 files, including Hdd, Design UI and Design Sections.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Earthworks (import)
Used by
imported by Hdd (import), imported by Design UI (import), imported by Design Sections (import), imported by Layers (dynamic import), imported by Layers (dynamic import), imported by Hdd (import), imported by Design Sections (import), imported by Design UI (import)
Produces
createTrench, composeGround, floorGround
Defines here
createTrench, pointAt, candidates, floorAt, inside, cutHeight, chainage, length3dOn, spoilVolumeOn, dig, straddles, offsetLine, mitredOutline, pad, wallLines, push, topAt, bisector, composeGround, floorGround
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/202609270330-site-world-v3/world/trench.mjs:1-301 · blob 3de964780068cfee469e55e0135ddbca27d628ed · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// trench.mjs: a trench is a function laid over the ground, never a stored mesh.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y).
// A trench is a centreline path with a floor width and a depth. The floor follows
// the ground profile along the centreline, lowered by the depth, so a trench on a
// hillside keeps a constant depth down its length. Walls are vertical unless a
// benchSlope (horizontal metres per metre of height) gives them a batter.
//
// Corners are mitred: each segment owns the strip between the bisector lines at
// its two ends, so the outside of a bend is a sharp corner, not a rounded one.
// Ends are cut square. Where two trenches (or two parts of one) overlap, the
// lowest surface wins. Nothing here fills ground: the cut never rises above it.
//
// No DOM. Pure functions of their inputs. Volumes and the ground with trenches in it come from the shared
// earthworks engine (lib/earthworks.mjs), which the road and pad cartridges use too.

import { stripVolume, gridIntegrate, composeGround as compose } from './lib/earthworks.mjs';

const GRID = 0.25;          // integration cell for spoil volume, metres
const STEP = 0.25;          // sampling step along the centreline, metres
const EPS = 1e-9;

/**
 * createTrench({ path, width, depth, benchSlope = 0, groundAt? })
 * path: [[x, y], ...] with at least two distinct points.
 * groundAt is optional; when given, length3d and spoilVolumeM3 are numbers.
 */
export function createTrench({ path, width, depth, benchSlope = 0, groundAt = null }) {
  if (!Array.isArray(path)) throw new Error('trench: path must be an array of [x, y]');
  if (!(width > 0) || !(depth > 0)) throw new Error('trench: width and depth must be positive');
  if (!(benchSlope >= 0)) throw new Error('trench: benchSlope must be zero or positive');

  // Drop repeated points so every segment has a direction.
  const pts = [];
  for (const p of path) {
    const q = [Number(p[0]), Number(p[1])];
    const last = pts[pts.length - 1];
    if (!last || Math.hypot(q[0] - last[0], q[1] - last[1]) > 1e-6) pts.push(q);
  }
  if (pts.length < 2) throw new Error('trench: path needs two distinct points');

  const half = width / 2;
  // How far out the batter may reach. The cut is clipped by the ground anyway, so
  // this only bounds the search; three depths covers steep side slopes.
  const reach = half + benchSlope * depth * 3;

  // Segments: start, unit direction, left normal, length, chainage at start.
  const segs = [];
  let s0 = 0;
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
    const len = Math.hypot(bx - ax, by - ay);
    const dx = (bx - ax) / len, dy = (by - ay) / len;
    segs.push({ ax, ay, bx, by, dx, dy, nx: -dy, ny: dx, len, s0 });
    s0 += len;
  }
  const length2d = s0;
  const n = segs.length;

  // Cut lines at each end of each segment. At a path end the cut is square to the
  // segment; at a bend it is the bisector, so neighbours share the mitre line.
  for (let i = 0; i < n; i++) {
    const g = segs[i];
    g.first = i === 0;
    g.last = i === n - 1;
    g.mStart = g.first ? [g.dx, g.dy] : bisector(segs[i - 1], g);
    g.mEnd = g.last ? [g.dx, g.dy] : bisector(g, segs[i + 1]);
  }

  // Bounding box of everything the trench can touch, for quick rejection.
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const [x, y] of pts) {
    minX = Math.min(minX, x); maxX = Math.max(maxX, x);
    minY = Math.min(minY, y); maxY = Math.max(maxY, y);
  }
  // A mitre can reach reach / cos(half the turn); cap the allowance at four times.
  const pad = reach * 4;
  const bbox = { minX: minX - pad, minY: minY - pad, maxX: maxX + pad, maxY: maxY + pad };

  function pointAt(s) {
    const c = Math.min(Math.max(s, 0), length2d);
    for (const g of segs) {
      if (c <= g.s0 + g.len || g.last) {
        const t = Math.min(Math.max(c - g.s0, 0), g.len);
        return [g.ax + g.dx * t, g.ay + g.dy * t];
      }
    }
    return pts[pts.length - 1];
  }

  // Every segment region the point falls in: chainage, lateral offset and how far
  // it lies beyond the floor edge (0 on the floor itself).
  function candidates(x, y, limit) {
    const out = [];
    if (x < bbox.minX || x > bbox.maxX || y < bbox.minY || y > bbox.maxY) return out;
    for (const g of segs) {
      const px = x - g.ax, py = y - g.ay;
      const t = px * g.dx + py * g.dy;
      const off = px * g.nx + py * g.ny;
      if (Math.abs(off) > limit + EPS) continue;
      let endExcess = 0;
      if (g.first) { if (t < -EPS) endExcess = -t; } // round-off at the square end stays inside (review B, 1a)
      else if (px * g.mStart[0] + py * g.mStart[1] < -EPS) continue;
      const qx = x - g.bx, qy = y - g.by;
      if (g.last) { if (t > g.len + EPS) endExcess = t - g.len; }
      else if (qx * g.mEnd[0] + qy * g.mEnd[1] > EPS) continue;
      const excess = Math.max(Math.abs(off) - half, endExcess, 0);
      if (excess > limit - half + EPS) continue;
      out.push({ s: g.s0 + Math.min(Math.max(t, 0), g.len), off, excess });
    }
    return out;
  }

  const floorAt = (s, g = groundAt) => {
    if (!g) throw new Error('trench: floorAt needs a ground function');
    const [x, y] = pointAt(s);
    return g(x, y) - depth;
  };

  const inside = (x, y) => candidates(x, y, half).some((c) => c.excess === 0);

  function cutHeight(x, y, g = groundAt) {
    const ground = g(x, y);
    const cs = candidates(x, y, benchSlope > 0 ? reach : half);
    let z = ground;
    for (const c of cs) {
      let surface = floorAt(c.s, g);
      if (c.excess > 0) {
        if (benchSlope === 0) continue;
        surface += c.excess / benchSlope;
      }
      if (surface < z) z = surface;
    }
    return z;
  }

  // Chainage of the nearest point on the centreline (inside or not).
  function chainage(x, y) {
    let best = Infinity, bestS = 0;
    for (const g of segs) {
      const t = Math.min(Math.max((x - g.ax) * g.dx + (y - g.ay) * g.dy, 0), g.len);
      const d = Math.hypot(x - (g.ax + g.dx * t), y - (g.ay + g.dy * t));
      if (d < best - EPS) { best = d; bestS = g.s0 + t; }
    }
    return bestS;
  }

  function length3dOn(g) {
    let total = 0, [px, py] = pointAt(0), pz = g(px, py);
    const steps = Math.max(1, Math.ceil(length2d / STEP));
    // Sample every vertex exactly as well as the regular steps.
    const marks = new Set();
    for (let k = 0; k <= steps; k++) marks.add(Math.min(k * length2d / steps, length2d));
    for (const sg of segs) marks.add(sg.s0);
    const ss = [...marks].sort((a, b) => a - b);
    for (let k = 1; k < ss.length; k++) {
      const [x, y] = pointAt(ss[k]);
      const z = g(x, y);
      total += Math.hypot(x - px, y - py, z - pz);
      px = x; py = y; pz = z;
    }
    return total;
  }

  // Excavated volume: ground minus cut surface, summed over a 0.25 m grid of cell
  // centres across the trench's reach, for this trench alone.
  function spoilVolumeOn(g) {
    if (benchSlope === 0) return stripVolume(pts, width, depth, g); // vertical walls: exact strips, no grid aliasing
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (const [x, y] of mitredOutline(benchSlope > 0 ? reach : half)) {
      x0 = Math.min(x0, x); x1 = Math.max(x1, x);
      y0 = Math.min(y0, y); y1 = Math.max(y1, y);
    }
    const nx = Math.ceil((x1 - x0) / GRID - 1e-9), ny = Math.ceil((y1 - y0) / GRID - 1e-9);
    const dig = (x, y) => Math.max(0, g(x, y) - cutHeight(x, y, g));
    // Cell corners, computed once. A cell whose corners disagree on whether they
    // are dug straddles a wall, so it is split 8 x 8 to find where the wall runs.
    const cw = nx + 1, corner = new Float64Array(cw * (ny + 1));
    for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) corner[j * cw + i] = dig(x0 + i * GRID, y0 + j * GRID);
    const straddles = (x, y, i, j) => {
      const dug = [corner[j * cw + i], corner[j * cw + i + 1], corner[(j + 1) * cw + i], corner[(j + 1) * cw + i + 1]].filter((d) => d > 0).length;
      return dug !== 0 && dug !== 4;
    };
    let vol = 0;
    gridIntegrate({ x0, y0, nx, ny, cell: GRID, split: straddles, visit: (x, y, w) => { vol += dig(x, y) * w * GRID * GRID; } });
    return vol;
  }

  // Offset polyline at signed distance h, with mitred vertices.
  function offsetLine(h) {
    const out = [];
    for (let k = 0; k <= n; k++) {
      let mx, my;
      if (k === 0) { mx = segs[0].nx; my = segs[0].ny; }
      else if (k === n) { mx = segs[n - 1].nx; my = segs[n - 1].ny; }
      else {
        const a = segs[k - 1], b = segs[k];
        const c = 1 + a.nx * b.nx + a.ny * b.ny;
        if (c < 1e-3) { mx = b.nx; my = b.ny; }            // a U-turn: no finite mitre
        else { mx = (a.nx + b.nx) / c; my = (a.ny + b.ny) / c; }
      }
      const s = k === n ? length2d : segs[k].s0;
      out.push([pts[k][0] + mx * h, pts[k][1] + my * h, s]);
    }
    return out;
  }

  function mitredOutline(h) {
    const L = offsetLine(h), R = offsetLine(-h);
    const e = benchSlope > 0 ? reach : half;
    const a = segs[0], b = segs[n - 1];
    // Square ends pushed out by the batter reach beyond the floor.
    const ext = e - half;
    const pad = (p, g, sign) => [p[0] + g.dx * ext * sign, p[1] + g.dy * ext * sign];
    return [...L, ...R, pad(L[0], a, -1), pad(R[0], a, -1), pad(L[n], b, 1), pad(R[n], b, 1)];
  }

  // Line pairs (x, y, z, x, y, z) for both floor edges, both wall tops, the uprights
  // at bends and ends, and the square end lines across the floor.
  function wallLines(g = groundAt) {
    if (!g) throw new Error('trench: wallLines needs a ground function');
    const v = [];
    const push = (a, b) => v.push(a[0], a[1], a[2], b[0], b[1], b[2]);
    const topAt = (x, y, floor) => {
      // With a batter the wall top sits out from the floor edge by depth * slope.
      return [x, y, Math.max(g(x, y), floor)];
    };
    for (const side of [1, -1]) {
      const edge = offsetLine(side * half);
      const top = benchSlope > 0 ? offsetLine(side * (half + benchSlope * depth)) : edge;
      for (let k = 0; k < n; k++) {
        const len = segs[k].len;
        const steps = Math.max(1, Math.ceil(len / 1));
        let prevF = null, prevT = null;
        for (let j = 0; j <= steps; j++) {
          const f = j / steps;
          const s = edge[k][2] + (edge[k + 1][2] - edge[k][2]) * f;
          const floor = floorAt(s, g);
          const ex = edge[k][0] + (edge[k + 1][0] - edge[k][0]) * f;
          const ey = edge[k][1] + (edge[k + 1][1] - edge[k][1]) * f;
          const tx = top[k][0] + (top[k + 1][0] - top[k][0]) * f;
          const ty = top[k][1] + (top[k + 1][1] - top[k][1]) * f;
          const F = [ex, ey, floor], T = topAt(tx, ty, floor);
          if (prevF) { push(prevF, F); push(prevT, T); }
          if (j === 0 || j === steps) push(F, T);
          prevF = F; prevT = T;
        }
      }
    }
    // Square end lines across the floor.
    for (const s of [0, length2d]) {
      const g0 = s === 0 ? segs[0] : segs[n - 1];
      const [cx, cy] = pointAt(s);
      const z = floorAt(s, g);
      push([cx + g0.nx * half, cy + g0.ny * half, z], [cx - g0.nx * half, cy - g0.ny * half, z]);
    }
    return new Float32Array(v);
  }

  const trench = {
    path: pts, width, depth, benchSlope, length2d, bbox,
    cutHeight, inside, floorAt, chainage, wallLines, pointAt,
    length3dOn, spoilVolumeOn,
  };
  let len3 = null, vol = null;
  Object.defineProperty(trench, 'length3d', {
    enumerable: true,
    get() {
      if (!groundAt) throw new Error('trench: length3d needs groundAt; use length3dOn(g)');
      return len3 ?? (len3 = length3dOn(groundAt));
    },
  });
  Object.defineProperty(trench, 'spoilVolumeM3', {
    enumerable: true,
    get() {
      if (!groundAt) throw new Error('trench: spoilVolumeM3 needs groundAt; use spoilVolumeOn(g)');
      return vol ?? (vol = spoilVolumeOn(groundAt));
    },
  });
  return trench;
}

// Unit normal of the mitre line between two segments: the sum of their directions.
// For a U-turn the sum vanishes, so fall back to the incoming direction.
function bisector(a, b) {
  const x = a.dx + b.dx, y = a.dy + b.dy, l = Math.hypot(x, y);
  return l < 1e-6 ? [a.dx, a.dy] : [x / l, y / l];
}

/**
 * composeGround(groundAt, trenches) -> a new heightAt with every trench cut in (lib/earthworks.mjs composeGround).
 * Each trench cuts against the original ground; where they overlap the lowest wins.
 */
export const composeGround = (groundAt, trenches) => compose(groundAt, { trenches: [...trenches] });

/**
 * floorGround(trench, groundAt) -> (x, y) -> the trench's own floor level at the nearest point of its centreline.
 * A cable lies on its trench floor even where its bend fillet cuts the corner wider than half the trench, so it
 * never climbs onto the natural ground at a bend (review B, finding 1b).
 */
export const floorGround = (trench, groundAt) => (x, y) => trench.floorAt(trench.chainage(x, y), groundAt);

Cable Checks UI

A JavaScript module in the world folder of GlobalGrid2050 that loads staged (`loadStaged`) and line (`loadLine`) (units: mm²), covering cables and solar, using IEC 60364-5-52 and IEC 60287-1-1.

electricalglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/cable-checks-ui.mjs · lines 1–90 of 90 · version 2026-09-27 04:02 · Not reached from any entry point (candidate for review) · pattern range (shared by 5 files)

What it does
It draws cables and solar. Defines 10 functions or classes, including loadStaged, mountCableChecks, el, note, n. Side effects: changes the web page (DOM).
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.
Downstream impact
Used directly by 3 files: Design Sections (globalgrid2050); Block UI (globalgrid2050); Design Sections (globalgrid2050).
What it achieves
It loads staged (`loadStaged`) and loads line (`loadLine`). The Cable checks fold under Design > Plant > Solar block. It responds to change events.
Why it matters
Imported by Design Sections and Block UI.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
Uses
Layers (import), Cable Checks (import), Measure Format (import)
Used by
imported by Design Sections (dynamic import), imported by Block UI (dynamic import), imported by Design Sections (dynamic import)
Produces
loadStaged, mountCableChecks
Defines here
loadStaged, mountCableChecks, el, note, n, table, dl, range, loadLine, render
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/202609270402-site-world-v3/world/cable-checks-ui.mjs:1-90 · blob 2ae4398349b2e4436b14e4c70df8dad3868f9f2a · 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: unreached_review
// cable-checks-ui.mjs: the Cable checks fold under Design > Plant > Solar block. Loads the staged cable schedule (the
// manifest pins its SHA-256: manifest.site.cables), lets the assumptions be changed, and shows voltage drop and
// loading per circuit as numbers (cable-checks.mjs). Loaded the first time the fold opens; nothing is drawn in 3D.
// Wording: an illustrative check with editable assumptions. A loading over 100 % reads "above 100% at these
// assumptions", in the same colour as every other number: no verdict words, no warning colour (tests/cable-checks.test.mjs).

import { makeApi } from './layers.mjs';
import { CHECK_LABEL, AXES, AXIS_WORDS, valueWords, loadingWords, parseChecks, defaultChoice, acChecks, dcChecks, tableRow } from './cable-checks.mjs';
import { formatNumber } from './measure-format.mjs';

const STYLE = `#cables-box .cc-note { color: var(--dim); margin: 4px 0; }
#cables-box label { display: flex; justify-content: space-between; gap: 8px; margin: 2px 0; }
#cables-box select, #cables-box input { max-width: 48%; }
#cables-box dd { color: var(--text); font-variant-numeric: tabular-nums; }
#cables-box .cc-table { overflow-x: auto; max-height: 260px; overflow-y: auto; margin: 4px 0 8px; }
#cables-box table { border-collapse: collapse; font-variant-numeric: tabular-nums; width: 100%; }
#cables-box th, #cables-box td { padding: 1px 6px; text-align: right; white-space: nowrap; color: var(--text); }
#cables-box th:first-child, #cables-box td:first-child { text-align: left; }
#cables-box th { color: var(--dim); font-weight: normal; position: sticky; top: 0; background: var(--panel); }`;

// The staged file through the manifest's hash: { doc } or throws with a plain reason.
export async function loadStaged({ manifestUrl = './world/manifest.json', fetchImpl } = {}) {
  const base = new URL(manifestUrl, location.href), res = await (fetchImpl || fetch)(base.href, { cache: 'no-cache' });
  if (!res.ok) throw Error(`manifest HTTP ${res.status}`);
  const pin = (await res.json()).site?.cables;
  if (!pin?.path || !pin?.sha256) throw Error('no cable schedule is staged for this site (tools/stage-cable-schedule.mjs)');
  return makeApi(new URL('./', base).href, { fetchImpl }).fetchJSON(pin.path, pin.sha256);
}

// deps: { doc, box, load() -> Promise<staged json> }. Returns { choice(), set(k, v), ac(), dc() } once loaded.
export async function mountCableChecks({ doc, box, load = () => loadStaged() }) {
  if (!box) return null;
  if (!doc.getElementById('cables-style')) { const s = doc.createElement('style'); s.id = 'cables-style'; s.textContent = STYLE; doc.head.append(s); }
  const el = (tag, props = {}, ...kids) => { const e = Object.assign(doc.createElement(tag), props); e.append(...kids); return e; };
  const note = t => el('p', { className: 'cc-note', textContent: t });
  box.replaceChildren(note('Reading the staged cable schedule…'));
  let checks;
  try { checks = parseChecks(await load()); } catch (e) { box.replaceChildren(note(`${CHECK_LABEL} No schedule to check here: ${e.message}.`)); return null; }

  const n = (x, d) => (Number.isFinite(x) ? formatNumber(x, d) : '–');
  const choice = defaultChoice(checks);
  const form = el('div', { className: 'cc-form' }), ac = el('dl'), acTable = el('div', { className: 'cc-table' });
  const dc = el('dl'), dcTable = el('div', { className: 'cc-table' }), invSel = el('select', { id: 'cables-inverter' });
  // Editable assumptions: every axis the GPU sweep rated, and the power factor for the voltage drop.
  if (checks.cases) {
    for (const k of AXES) {
      const sel = el('select', { id: `cables-${k}` });
      for (const v of checks.cases.axes[k]) sel.append(el('option', { value: String(v), textContent: valueWords(v), selected: v === choice[k] }));
      sel.addEventListener('change', () => { choice[k] = checks.cases.axes[k].find(v => String(v) === sel.value); render(); });
      form.append(el('label', {}, AXIS_WORDS[k] + ' ', sel));
    }
  } else form.append(note('The rated sweep is not staged: AC loading is not worked out; voltage drop uses the assumed cable.'));
  const pf = el('input', { id: 'cables-pf', type: 'number', min: '0.8', max: '1', step: '0.01', value: String(choice.pf) });
  pf.addEventListener('change', () => { choice.pf = Math.min(1, Math.max(0.8, Number(pf.value) || 1)); pf.value = String(choice.pf); render(); });
  form.append(el('label', {}, 'Power factor (voltage drop) ', pf));
  const inverters = [...new Set(checks.dc.map(c => c.inverter))];
  for (const i of inverters) invSel.append(el('option', { value: String(i), textContent: `Inverter ${i}` }));
  invSel.addEventListener('change', () => render());

  const table = (heads, rows) => el('table', {}, el('thead', {}, el('tr', {}, ...heads.map(h => el('th', { textContent: h })))),
    el('tbody', {}, ...rows.map(r => el('tr', {}, ...r.map((v, i) => el('td', { textContent: i && typeof v === 'number' ? n(v, [1, 2, 2, 1][i - 1]) : v ?? '–' }))))));
  const HEADS = ['Circuit', 'Length m', 'Drop V', 'Drop %', 'Loading %'];
  const dl = (target, rows) => target.replaceChildren(...rows.flatMap(([k, v]) => [el('dt', { textContent: k }), el('dd', { textContent: v })]));
  const range = s => (s ? `${n(s.min, 2)} to ${n(s.max, 2)} % (median ${n(s.median, 2)} %)` : '–');
  const loadLine = s => (s?.loading_pct ? `${n(s.loading_pct.max, 1)} % at most · ${loadingWords(s.loading_pct.max)}` +
    (s.above100 ? ` (${s.above100} of ${s.count})` : '') : loadingWords(NaN));
  let last = null;
  function render() {
    const A = acChecks(checks, choice), D = dcChecks(checks), inv = Number(invSel.value) || inverters[0];
    dl(ac, [['AC phase cables', `${A.summary.count} · ${n(choice.size, 0)} mm² ${valueWords(choice.mat)}, ${n(checks.assumed.ac.volts, 0)} V`],
      ['Rating, this case', Number.isFinite(A.rating_A) ? `${n(A.rating_A, 1)} A per cable (GPU-rated sweep, assumed data)` : 'not in the rated sweep'],
      ['Loading', loadLine(A.summary)], ['Voltage drop', range(A.summary.vd_pct) + ' of line volts'],
      ...(Number.isFinite(A.width_m) ? [['Trench width, this case', `${n(A.width_m, 2)} m`]] : [])]);
    acTable.replaceChildren(table(HEADS, A.circuits.map(tableRow)));
    dl(dc, [['DC string cables', `${D.summary.count} · ${n(checks.assumed.dc.area_mm2, 0)} mm² copper, as scheduled (assumed rating ` +
      `${n(checks.assumed.dc.base_duct_A, 0)} A in duct, grouping factors as scheduled)`],
      ['Loading', loadLine(D.summary)], ['Voltage drop', range(D.summary.vd_pct) + ` of the string's ${n(checks.assumed.string_vmp_V, 0)} V`],
      ['Per string', range(D.summary.strings) + ' (both conductors)']]);
    dcTable.replaceChildren(table(HEADS, D.circuits.filter(c => c.inverter === inv).map(tableRow)));
    last = { ac: A, dc: D };
  }
  const why = `Grouping factors cited as ${checks.standards[0] || 'IEC 60364-5-52 Annex B Tables B.52.18 and B.52.19'}; rating method of the form of ` +
    `${checks.standards.slice(1, 4).join(', ') || 'IEC 60287-1-1, IEC 60287-2-1, IEC 60853-2'}; conductor resistance of the kind listed in ` +
    `${checks.standards[4] || 'IEC 60228 Tables 2 and 3'}. Table numbers to be checked against the editions held.`;
  box.replaceChildren(note(`${CHECK_LABEL} ${checks.illustrative.replace(CHECK_LABEL, '').trim()}`), form, ac, acTable,
    dc, el('label', {}, 'DC circuits shown ', invSel), dcTable, note(checks.lengths), note(why),
    note('Sources: ' + checks.sources.map(s => `${s.file} ${String(s.sha256).slice(0, 12)}`).join(' · ')));
  render();
  return { choice: () => ({ ...choice }), set(k, v) { choice[k] = v; render(); }, ac: () => last.ac, dc: () => last.dc };
}

Cable Checks

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

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

Evidence
  • line-jaccard 0.9213 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/cable-checks.mjs:1-113 8f4e30d5af21ff441ea296cd666cadfe0b0bb9fb
  • sha256 8036fd69a3fba6b2ba2e4aa74018f38d64681cc47bec20c704c29fe76977ed4e
  • target sha256 76033be33d779fd8426706a25a0580d61744b0ed2af037903b13141cecdcb882
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/cable-checks.mjs · lines 1–104 of 104 · version 2026-09-27 04:02 · Not reached from any entry point (candidate for review) · pattern defaultChoice (shared by 2 files)

What it does
It calculates cables and solar. Defines 14 functions or classes, including valueWords, loadingWords, num, rTheta, round.
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.
Downstream impact
Used directly by 1 file: Cable Checks UI (globalgrid2050).
What it achieves
It parses checks (`parseChecks`) and is built from the value words helper (`valueWords`) and the loading words helper (`loadingWords`). The Solar block's cable schedule as illustrative checks (Design > Plant > Solar block > Cable checks).
Why it matters
Imported by Cable Checks UI.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Cable Checks UI (import), mentioned in Standalone (comment link)
Produces
CHECK_LABEL, AXES, AXIS_WORDS, valueWords, loadingWords, parseChecks, defaultChoice, caseFor, acChecks, dcChecks, summarise, tableRow
Defines here
valueWords, loadingWords, num, rTheta, round, parseChecks, rows, defaultChoice, caseFor, acChecks, dcChecks, summarise, stat, tableRow
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/202609270402-site-world-v3/world/cable-checks.mjs:1-104 · blob a972c33846bf84513694eaf55ec5d740289839c3 · 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: unreached_review
// cable-checks.mjs: the Solar block's cable schedule as illustrative checks (Design > Plant > Solar block > Cable checks).
// Per circuit: voltage drop and loading, worked out again from the staged schedule (tools/stage-cable-schedule.mjs)
// at the assumptions chosen in the panel. Every property, rating, factor, spacing and power factor is ASSUMED; the
// numbers are an illustrative check, not a design and not a calculation to any standard. A loading over 100 % is
// said in neutral words ("above 100% at these assumptions"): it is a question about the assumptions, never a verdict.
// Pure: no DOM, no fetch.
//
//   voltage drop, DC string cable   I x L x R(theta)                     (one conductor; % of the string's Vmp)
//   voltage drop, AC phase cable    sqrt(3) x I x L x (R(theta) cos(phi) + X sin(phi))           (% of line volts)
//   R(theta) = R20 x (1 + alpha (theta - 20))
//   loading, AC                     design current / rating of the chosen case (GPU-rated sweep, one rating per case)
//   loading, DC                     design current / (assumed rating in duct x assumed grouping factor), as scheduled

export const CHECK_LABEL = 'Illustrative check, assumptions editable.';
export const AXES = ['size', 'mat', 'inst', 'rho', 'depth', 'nper', 'spacing', 'layers', 'load'];
export const AXIS_WORDS = Object.freeze({
  size: 'Conductor size, mm²', mat: 'Material', inst: 'Installation', rho: 'Soil thermal resistivity, K·m/W', depth: 'Depth to the circuit centres, m',
  nper: 'Circuits per trench', spacing: 'Spacing between circuits, m', layers: 'Layers of circuits', load: 'Load profile'
});
const VALUE_WORDS = { Al: 'aluminium', Cu: 'copper', 'trefoil-direct': 'trefoil, laid direct', 'trefoil-ducted': 'trefoil, each circuit in a duct',
  'flat-spaced': 'flat, one cable width apart', continuous: 'full current all day', solar: 'a solar day (daily cycle)' };
export const valueWords = v => VALUE_WORDS[v] ?? String(v);

// Neutral words for a loading: the only two things this page ever says about one.
export const loadingWords = pct => (!Number.isFinite(pct) ? 'not worked out at these assumptions'
  : pct > 100 ? 'above 100% at these assumptions' : 'within 100% at these assumptions');

const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : NaN);
const rTheta = (r20, alpha, theta) => r20 * (1 + alpha * (theta - 20));
const round = (x, d) => Math.round(x * 10 ** d) / 10 ** d;

// The staged file, checked for shape; throws with a plain reason.
export function parseChecks(doc) {
  if (!doc || doc.schema !== 'world.cable-checks.v1') throw Error('not a cable-checks file (world.cable-checks.v1)');
  for (const k of ['dc', 'ac']) if (!Array.isArray(doc[k]?.rows) || !Array.isArray(doc[k]?.columns)) throw Error(`no ${k} circuits`);
  const a = doc.assumed;
  if (!a?.dc || !a?.ac) throw Error('no assumed cable data');
  const rows = k => doc[k].rows.map(r => Object.fromEntries(doc[k].columns.map((c, i) => [c, r[i]])));
  const cases = doc.cases && AXES.every(k => Array.isArray(doc.cases.axes?.[k])) && Array.isArray(doc.cases.rating_A) ? doc.cases : null;
  return { dc: rows('dc'), ac: rows('ac'), assumed: a, cases, illustrative: String(doc.illustrative || CHECK_LABEL),
    lengths: String(doc.lengths || ''), standards: (doc.standards || []).map(String), sources: doc.sources || [] };
}

// The panel's starting assumptions: the sweep's own baseline, else the first value of every axis; power factor as assumed.
export function defaultChoice(checks) {
  const c = checks.cases, base = c?.baseline || {};
  const out = Object.fromEntries(AXES.map(k => [k, c ? (c.axes[k].includes(base[k]) ? base[k] : c.axes[k][0]) : null]));
  out.size ??= checks.assumed.ac.area_mm2; out.mat ??= checks.assumed.ac.material;
  return { ...out, pf: num(checks.assumed.ac.pf) || 1 };
}

// The rated case for a choice: { rating_A, width_m } or null when the sweep has no such case.
export function caseFor(cases, choice) {
  if (!cases) return null;
  let i = 0;
  for (const k of AXES) {
    const j = cases.axes[k].indexOf(choice[k]);
    if (j < 0) return null;
    i = i * cases.axes[k].length + j;
  }
  const rating = num(cases.rating_A[i]);
  return Number.isFinite(rating) && rating > 0 ? { rating_A: rating, width_m: num(cases.width_m?.[i]) } : null;
}

// AC phase cables at a choice: per circuit length, voltage drop (V and % of line volts) and loading.
export function acChecks(checks, choice) {
  const a = checks.assumed.ac, r20 = num(a.r20_ohm_km?.[choice.mat]?.[choice.size]), alpha = num(a.alpha?.[choice.mat]);
  const pf = Math.min(1, Math.max(0.5, num(choice.pf) || 1)), sin = Math.sqrt(1 - pf * pf);
  const R = rTheta(r20, alpha, num(a.theta_C)), X = num(a.x_ohm_km) || 0, rated = caseFor(checks.cases, choice);
  const circuits = checks.ac.map(c => {
    const vd = Math.sqrt(3) * num(c.current_A) * num(c.length_m) / 1000 * (R * pf + X * sin);
    const loading = rated ? 100 * num(c.design_current_A) / rated.rating_A : NaN;
    return { id: c.id, inverter: c.inverter, phase: c.phase, length_m: num(c.length_m), vd_V: vd, vd_pct: 100 * vd / num(a.volts), loading_pct: loading };
  });
  return { rating_A: rated?.rating_A ?? NaN, width_m: rated?.width_m ?? NaN, r_ohm_km: R, circuits, summary: summarise(circuits) };
}

// DC string cables as scheduled: per circuit voltage drop (% of the string's Vmp) and loading.
export function dcChecks(checks) {
  const d = checks.assumed.dc, R = rTheta(num(d.r20_ohm_km), num(d.alpha), num(d.theta_C)), vmp = num(checks.assumed.string_vmp_V);
  const circuits = checks.dc.map(c => {
    const vd = num(c.current_A) * num(c.length_m) / 1000 * R;
    return { id: c.id, inverter: c.inverter, string: c.string, length_m: num(c.length_m), vd_V: vd, vd_pct: 100 * vd / vmp,
      loading_pct: 100 * num(c.design_current_A) / num(c.rating_A) };
  });
  // A string's drop is both its conductors' (NEG and POS together).
  const strings = new Map();
  for (const c of circuits) { const k = `${c.inverter}:${c.string}`; strings.set(k, (strings.get(k) || 0) + c.vd_pct); }
  const perString = summarise([...strings.values()].map(vd_pct => ({ vd_pct, loading_pct: NaN }))).vd_pct;
  return { r_ohm_km: R, circuits, summary: { ...summarise(circuits), strings: perString } };
}

// Min, median and max of voltage drop and loading, and how many circuits are above 100 % at these assumptions.
export function summarise(circuits) {
  const stat = k => {
    const v = circuits.map(c => c[k]).filter(Number.isFinite).sort((x, y) => x - y);
    return v.length ? { min: v[0], median: v[Math.floor(v.length / 2)], max: v[v.length - 1] } : null;
  };
  return { count: circuits.length, vd_pct: stat('vd_pct'), loading_pct: stat('loading_pct'),
    above100: circuits.filter(c => c.loading_pct > 100).length };
}

// Rows for a table, numbers rounded for the screen.
export const tableRow = c => [c.id, round(c.length_m, 1), round(c.vd_V, 2), round(c.vd_pct, 2), Number.isFinite(c.loading_pct) ? round(c.loading_pct, 1) : null];