GLOBALGRID2050 / EXPLORE CODE

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

Piles and 2 more files (part 1)

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

561 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 166 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. Overhead Line (OHL) UI render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/ohl-ui.mjs lines 1–145
  2. Piles transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/piles.mjs lines 1–276
  3. Plant Feeders transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/plant-feeders.mjs lines 1–140

Overhead Line (OHL) UI

A JavaScript module in the world folder of GlobalGrid2050 that creates OHL layer (`createOhlLayer`), mounts OHL control (`mountOhlControl`) and calculates planar distances, covering overhead lines (OHL).

renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/ohl-ui.mjs · lines 1–145 of 145 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern mountOhlControl (shared by 2 files)

What it does
It draws overhead lines (OHL). Defines 14 functions or classes, including readout, n, boqItems, get, goalpostLines. 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. Domain terms in the code: overhead lines (OHL).
Inputs & outputs
In: form fields (user input).
What it achieves
It creates OHL layer (`createOhlLayer`) and attaches OHL (`attachOhl`). Overhead line safety zones on the page: a layer that draws the zones on the ground from the grid layer's conductors, the design checks (`ohl-zones.mjs`), a short readout with the working height input, and the bill rows. It responds to change events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Overhead Line (OHL) Zones (import), Overhead Line (OHL) Gs6 (import), Buffers (import)
Used by
none found
Produces
ID, COLORS, readout, boqItems, goalpostLines, createOhlLayer, mountOhlControl, attachOhl
Defines here
readout, n, boqItems, get, goalpostLines, g, P, createOhlLayer, refresh, lines, mountOhlControl, update, attachOhl, gridItem
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/ohl-ui.mjs:1-145 · blob 7559761c3b19e0f97a3a695141dc781a1b63277d · 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
// Overhead line safety zones on the page: a layer that draws the zones on the ground from the grid layer's conductors,
// the design checks (ohl-zones.mjs), a short readout with the working height input, and the bill rows.
// Nothing is fetched: the conductors are the grid layer's own (layer.wires()), the design is the one in memory.
// A frame is drawn only when something changes (the substrate's frame gate): 0 fps when still.
import { buildSpans, zoneRings, checkDesign, designItems } from './ohl-zones.mjs';
import { DISCLAIMER, WORKING_HEIGHT, ZONES } from './ohl-gs6.mjs';
import { dashRing, drapePieces } from './layers/buffers.mjs';

export const ID = 'ohl-safety';
export const COLORS = { zone: [1.0, 0.62, 0.25, 0.85], barrier: [1.0, 0.38, 0.30, 0.9], flag: [1.0, 0.30, 0.30, 1], goalpost: [1.0, 1.0, 1.0, 0.95] };
const LIFT_M = 0.12, CROSS_M = 2, POST_M = 5, POST_HALF_M = 3; // marker sizes, metres (symbols, not designs)

// Pure: the readout line. No flag is never shown as a good sign: places without a flag are not assessed.
export function readout(spans, result, height) {
  if (!spans.length) return 'Overhead line zones: no overhead line conductors drawn near here yet.';
  const n = f => result.flags.filter(x => x.flag === f).length;
  const items = new Set(result.flags.filter(f => f.flag !== 'height').map(f => f.item)).size;
  const parts = [`Overhead line zones round ${spans.length} span${spans.length === 1 ? '' : 's'}`,
    items ? `${items} design item${items === 1 ? '' : 's'} inside a zone (${n('crosses')} crossing under)` : 'no design item flagged (not assessed beyond the zones)',
    result.goalposts.length ? `${result.goalposts.length / 2} goalpost crossing${result.goalposts.length === 2 ? '' : 's'} suggested` : '',
    height > 0 ? `plant ${height} m tall (user-set) reaches an exclusion distance at ${n('height')} item${n('height') === 1 ? '' : 's'}` : '',
    result.unmeasured ? `${result.unmeasured} points not assessed: no measured ground` : ''];
  return parts.filter(Boolean).join(' · ') + '.';
}

// Pure: the bill items: one per design item with any flag, counting its zone flags, height flags and goalposts.
export function boqItems(result) {
  const by = new Map();
  const get = id => { if (!by.has(id)) by.set(id, { id: `ohl-${id}`, kind: 'ohlZone', zone: 0, height: 0, goalposts: 0 }); return by.get(id); };
  for (const f of result.flags) get(f.item)[f.flag === 'height' ? 'height' : 'zone']++;
  for (const g of result.goalposts) get(g.item).goalposts++;
  return [...by.values()];
}

// Pure: goalpost marker at (x, y) across a road heading (dx, dy): two posts and a crossbar, xyz pairs relative to o.
export function goalpostLines(x, y, dx, dy, heightAt, o) {
  const L = Math.hypot(dx, dy) || 1, px = -dy / L * POST_HALF_M, py = dx / L * POST_HALF_M, out = [];
  const g = (a, b) => (Number.isFinite(heightAt(a, b)) ? heightAt(a, b) : o[2]);
  const P = (a, b, up) => [a - o[0], b - o[1], g(a, b) + up - o[2]];
  const A = [x + px, y + py], B = [x - px, y - py];
  out.push(...P(...A, 0), ...P(...A, POST_M), ...P(...B, 0), ...P(...B, POST_M), ...P(...A, POST_M), ...P(...B, POST_M));
  return out;
}

// deps: { grid() -> grid layer or null, gridShown() -> bool, design() snapshot, origin(), measuredAt, invalidate() }
export function createOhlLayer({ grid, gridShown = () => true, design, designVersion = null, origin, measuredAt, invalidate = () => {} }) {
  let enabled = true, height = WORKING_HEIGHT.defaultM, spans = [], rings = [], result = { flags: [], goalposts: [], unmeasured: 0 };
  let wiresKey = '', checkKey = '', cache = { key: null, batches: [] }, version = 0;
  const layer = {
    id: ID, status: 'waiting for the grid layer', summary: DISCLAIMER,
    get enabled() { return enabled; },
    setEnabled(on) { enabled = !!on; invalidate(); return enabled; },
    setHeight(h) { const v = Number(h); if (Number.isFinite(v)) { height = Math.min(WORKING_HEIGHT.maxM, Math.max(WORKING_HEIGHT.minM, v)); refresh(); invalidate(); } return height; },
    height: () => height, result: () => result, spans: () => spans, boqItems: () => boqItems(result),
    // The zones in national-grid metres, for the plant layout to keep its tables out of: [{ pts, closed, reachM }].
    zonesEN: () => { refresh(); const o = origin(); return spans.map(s => ({ pts: s.quad.pts.map(([x, y]) => [x + o.e, y + o.n]), closed: s.quad.closed, reachM: s.zoneReach })); },
    refresh, lines, debug: () => ({ enabled, spans: spans.length, flags: result.flags.length, goalposts: result.goalposts.length, height })
  };
  // Rebuilds the zones when the grid's conductors change, and the checks when the design, ground or height changes.
  function refresh(groundVersion = 0) {
    const w = grid()?.wires?.(), o = origin();
    if (!w || !w.origin || w.origin.e !== o.e || w.origin.n !== o.n) { layer.status = 'waiting for the grid layer to draw'; return false; }
    if (w.version !== wiresKey) { spans = buildSpans(w.wires); rings = zoneRings(spans); wiresKey = w.version; checkKey = ''; version++; }
    // Keyed on the design's version where it has one: no copy of the whole design on a drawn frame (PERF.md 2).
    const dv = designVersion?.(), d = dv == null ? design() : null;
    const key = `${wiresKey}|${height}|${groundVersion}|${dv ?? JSON.stringify([d.trenches, d.cables, d.works])}`;
    if (key !== checkKey) {
      result = checkDesign(designItems(d || design(), o), spans, measuredAt, { height });
      checkKey = key; version++;
    }
    layer.status = `${readout(spans, result, height)} Zone ${ZONES.planning.m} m or more from the nearest `
      + `conductor plus sway, barrier line ${ZONES.barrier.m} m plus sway (HSE GS6 paragraphs 11 and 19); tower heights and sag assumed`;
    return true;
  }
  function lines(ctx) {
    if (!enabled || !gridShown()) return [];
    refresh(ctx.groundVersion || 0);
    const key = `${version}@${ctx.groundVersion || 0}`;
    if (cache.key === key && cache.heightAt === ctx.heightAt) return cache.batches;
    const batches = [], h = ctx.heightAt, fin = (x, y) => (Number.isFinite(h(x, y)) ? h(x, y) : 0);
    for (const r of rings) for (const kind of ['zone', 'barrier']) {
      const pieces = r[kind].flatMap(ring => dashRing(ring, kind === 'zone' ? { dash: 4, gap: 2 } : { dash: 1.5, gap: 1.5 }));
      if (!pieces.length) continue;
      const [x, y] = r[kind][0][0], o = [x, y, fin(x, y)];
      batches.push({ key: `${ID}/${kind}/${r.line}`, version: key, origin: o, color: COLORS[kind], positions: drapePieces(pieces, h, LIFT_M, o) });
    }
    if (result.flags.length) {
      const c = CROSS_M / 2, pieces = result.flags.flatMap(({ at: [px, py] }) => [[px - c, py - c, px + c, py + c], [px - c, py + c, px + c, py - c]]);
      const [x, y] = result.flags[0].at, o = [x, y, fin(x, y)];
      batches.push({ key: `${ID}/flags`, version: key, origin: o, color: COLORS.flag, positions: drapePieces(pieces, h, LIFT_M * 2, o) });
    }
    if (result.goalposts.length) {
      const [x, y] = result.goalposts[0].at, o = [x, y, fin(x, y)], out = [];
      for (let i = 0; i + 1 < result.goalposts.length; i += 2) {
        const a = result.goalposts[i].at, b = result.goalposts[i + 1].at;
        out.push(...goalpostLines(a[0], a[1], b[0] - a[0], b[1] - a[1], h, o), ...goalpostLines(b[0], b[1], b[0] - a[0], b[1] - a[1], h, o));
      }
      batches.push({ key: `${ID}/goalposts`, version: key, origin: o, color: COLORS.goalpost, positions: new Float32Array(out) });
    }
    cache = { key, heightAt: h, batches };
    return batches;
  }
  return layer;
}

// The readout under the Layers panel: one line, the working height input and the fixed disclaimer.
export function mountOhlControl(host, layer) {
  if (!host || !layer) return null;
  const doc = host.ownerDocument || document, box = doc.createElement('fieldset');
  box.className = 'sun-time ohl-box';
  box.hidden = true;
  box.innerHTML = '<legend>Overhead line safety zones</legend>'
    + `<label>Working height, m (user-set: tallest plant or load) <input type="number" inputmode="decimal" min="${WORKING_HEIGHT.minM}" `
    + `max="${WORKING_HEIGHT.maxM}" step="0.5" data-ohl="height"></label>`
    + '<p class="note" aria-live="polite" data-ohl="readout"></p><p class="note" data-ohl="disclaimer"></p>';
  const input = box.querySelector('[data-ohl="height"]'), line = box.querySelector('[data-ohl="readout"]');
  box.querySelector('[data-ohl="disclaimer"]').textContent = DISCLAIMER;
  input.value = String(layer.height());
  input.addEventListener('change', () => { input.value = String(layer.setHeight(input.value)); update(); });
  const update = () => { line.textContent = readout(layer.spans(), layer.result(), layer.height()); };
  host.appendChild(box);
  update();
  return { element: box, show(v) { box.hidden = !v; if (v) update(); }, update };
}

// Page wiring, kept here so the substrate stays small. items: loadLayers(...).layers; the zones layer joins them before
// the Layers panel is drawn. Switching the grid on switches its zones on with it (they are on whenever the grid is).
// Returns { layer, onChange(ids, panel), mount(host, panel), update() }.
export function attachOhl(items, deps) {
  const gridItem = () => items.find(l => l.id === 'grid');
  const layer = createOhlLayer({ ...deps, grid: () => gridItem()?.layer || null, gridShown: () => !!gridItem()?.layer && !gridItem().hidden });
  items.push({ id: ID, layer, status: 'loaded, worked out on the page from the grid layer' });
  let gridWasOn = false, ui = null;
  return {
    layer,
    onChange(ids, panel) {
      // The zones go with the grid: on when it comes on, off when it goes off (they are worked out from its lines).
      if (ids.includes('grid') && !gridWasOn && !ids.includes(ID)) setTimeout(() => panel()?.set(ID, true));
      if (!ids.includes('grid') && gridWasOn && ids.includes(ID)) setTimeout(() => panel()?.set(ID, false));
      gridWasOn = ids.includes('grid'); ui?.show(ids.includes(ID));
    },
    mount(host, panel) { ui = mountOhlControl(host, layer); ui?.show(!!panel()?.isOn(ID)); },
    update: () => ui?.update()
  };
}

Piles

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

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

What it does
It calculates solar. Defines 9 functions or classes, including pileStations, spreadAt, fitTopLine, clip, slopeAt.
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: solar.
Downstream impact
Used directly by 3 files: Design Earthworks (globalgrid2050); Block Build (globalgrid2050); Plant Piles (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 fits top line (`fitTopLine`) and is built from the pile stations helper (`pileStations`) and the spread at helper (`spreadAt`). Where the piles of a row of solar tables go, how far each stands out of the ground, how deep it goes in, and what grading a row needs where the ground is too uneven for a straight table.
Why it matters
Imported by Design Earthworks, Block Build and Plant Piles.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Pile Rules (import)
Used by
imported by Design Earthworks (import), imported by Block Build (import), imported by Plant Piles (import)
Produces
LIMITS, DEFAULTS, pileStations, fitTopLine, planPiles, followTopLine, revealPercentiles
Defines here
pileStations, spreadAt, fitTopLine, clip, slopeAt, planPiles, topOf, followTopLine, revealPercentiles
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/piles.mjs:1-276 · blob 1795fce86a634da83eaa08325d686215ac9289c4 · 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
// piles.mjs: where the piles of a row of solar tables go, how far each stands out of the ground, how deep it
// goes in, and what grading a row needs where the ground is too uneven for a straight table.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y).
// A row is a straight placement line on the ground, [[x0, y0], [x1, y1]]. Tables of tableLength are laid
// along it end to end with tableGap between them, the set centred on the line. Each table is straight and
// rigid, so the tops of its piles lie on one straight line in the vertical section along the row. Piles sit
// pileSpacing apart, centred on their table.
//
// The top-of-pile line of a table is either given (row.top = [zStart, zEnd], the target top level at the two
// ends of the placement line; every table on the row takes that line) or fitted:
//   1. slope b: the one that makes the spread of (ground - b s) over the table's piles smallest, within the
//      along-row slope limit. That spread is convex and piecewise linear in b, so its least value is at a
//      pairwise slope between two piles or at a limit; ties go to the slope nearest the least-squares slope.
//   2. level a: the allowed window [max(g - b s) + revealMin, min(g - b s) + revealMax]; within it, as near
//      the mean nominal reveal as the window allows; if the window is empty, its middle (excess split evenly).
// A pile whose reveal is above revealMax needs fill under it, below revealMin needs cut; the finished ground is
// then level with the allowed limit. Embedment is at least embedMin below the finished ground; with pileStep the
// pile length is rounded up to a stock step and the embedment grows to suit.
// Grading volume: each pile's cut or fill depth over its tributary length (one pile spacing) times the grading
// width (assumed). Slopes: ground gradient at each pile by central differences, split into north-south and
// east-west parts, and checked against the limits for the mounting system.
//
// Shared rules: pile-rules.mjs (embedment, reveal from the table, adjustment and twist tolerances). Twist: rows paired
// front and rear (row.pair = { with: id, depth }) have each table's twist checked against the tolerance.
// No DOM. Pure functions of their inputs. Figures marked ASSUMED are defaults to be replaced by the
// chosen product's datasheet and the site's geotechnical report; they are not design values.

import { PILE_RULES as R, TRACKER_RULES as TR, revealAt, revealBand, trackerHub, twistDeg } from './pile-rules.mjs';

// Typical slope limits, as fractions (rise over run). Sources:
//  [1] K. Anderson, M. Mikofski, "Slope-Aware Backtracking for Single-Axis Trackers", NREL/TP-5K00-76626, 2020,
//      https://docs.nrel.gov/docs/fy20osti/76626.pdf (definitions of axis tilt and cross-axis slope).
//  [2] Sandia PV Performance Modeling Collaborative, "Single Axis Tracking",
//      https://pvpmc.sandia.gov/modeling-guide/1-weather-design-inputs/array-orientation/single-axis-tracking/
//  [3] Trade-press survey of tracker datasheets, 2023-2024 (standard products commonly 8.5-15 % along the axis,
//      terrain-following products more; cross-axis slope commonly 10-20 % with slope-aware backtracking),
//      https://www.solarpowerworldonline.com/2023/01/single-axis-trackers-upgrade-to-handle-uneven-land-sites/
// Single-axis tracker rows run north-south, so its north-south limit applies along the torque tube.
// Fixed-tilt rows run east-west, so its east-west limit applies along the table.
export const LIMITS = {
  tracker: {
    nsMax: 0.10, ewMax: 0.15, along: 'ns',
    note: 'typical single-axis tracker: 10 % along the axis (north-south), 15 % across (east-west) [1][2][3]; ASSUMED',
  },
  fixed: {
    nsMax: 0.20, ewMax: 0.15, along: 'ew',
    note: 'typical fixed tilt: 15 % along the row (east-west), 20 % north-south (changes the effective tilt) [3]; ASSUMED',
  },
};

// ASSUMED defaults, labelled as such in every result (result.assumed).
// Fixed tilt is the plant layout's table: 28 modules across (32.3 m; class A at -10 °C, the stricter of the cell and Voc x 1.15), 2P portrait at 25 deg (rise 2.02 m), low edge
// 0.8 m, one post at mid-slope -> reveal 1.51 m (pile-rules.mjs). The plant layout passes its own table instead.
const FIXED_RISE = (2 * 2.384 + 0.02) * Math.sin(25 * Math.PI / 180);
export const DEFAULTS = {
  tracker: { tableLength: 60, pileSpacing: TR.pileSpacingM.tracker, tableGap: 1, reveal: revealBand(trackerHub(TR).reveal, TR) },
  fixed: { tableLength: 32.3, pileSpacing: R.pileSpacingM.fixed, tableGap: 0.5,
    reveal: revealBand(revealAt({ lowEdgeM: 0.8, rise: FIXED_RISE, f: R.pivot })) },
  embedMin: R.embedM,  // embedment, metres: in practice set by pile load tests
  gradingWidth: R.gradingWidthM, // width of ground graded along a row, metres
  pileStep: 0,         // stock length step, metres; 0 means piles cut to length
  gradStep: 1.0,       // central-difference half step for the ground gradient, metres
  revealAdjust: R.revealAdjustM, twistTolDeg: R.twistTolDeg,
};

const EPS = 1e-9;

/** Pile chainages along a placement line of length len: [{ table, s }], and the table extents. */
export function pileStations(len, tableLength, pileSpacing, tableGap = 0) {
  if (!(tableLength > 0) || !(pileSpacing > 0)) throw new Error('piles: tableLength and pileSpacing must be positive');
  if (pileSpacing > tableLength + EPS) throw new Error('piles: pileSpacing is longer than the table');
  if (!(tableGap >= 0)) throw new Error('piles: tableGap must be zero or positive');
  const nt = Math.floor((len + tableGap + EPS) / (tableLength + tableGap));
  const used = nt * tableLength + Math.max(nt - 1, 0) * tableGap;
  const off = (len - used) / 2;
  const np = Math.floor(tableLength / pileSpacing + EPS) + 1;
  const over = (tableLength - (np - 1) * pileSpacing) / 2;
  const tables = [], stations = [];
  for (let t = 0; t < nt; t++) {
    const s0 = off + t * (tableLength + tableGap);
    tables.push({ table: t, s0, s1: s0 + tableLength });
    for (let k = 0; k < np; k++) stations.push({ table: t, s: s0 + over + k * pileSpacing });
  }
  return { tables, stations, pilesPerTable: np };
}

const spreadAt = (s, g, b) => {
  let hi = -Infinity, lo = Infinity;
  for (let i = 0; i < s.length; i++) { const d = g[i] - b * s[i]; if (d > hi) hi = d; if (d < lo) lo = d; }
  return { hi, lo, w: hi - lo };
};

/**
 * fitTopLine(s, g, { min, nominal, max }, maxSlope): the straight top-of-pile line z = a + b s for piles at
 * chainages s over ground g. Returns { a, b, spread, window, feasible }.
 */
export function fitTopLine(s, g, reveal, maxSlope = Infinity) {
  const n = s.length;
  if (n < 1 || g.length !== n) throw new Error('piles: fitTopLine needs matching s and g');
  const lim = Math.abs(maxSlope);
  let bls = 0;
  if (n > 1) {
    const ms = s.reduce((p, v) => p + v, 0) / n, mg = g.reduce((p, v) => p + v, 0) / n;
    let sxy = 0, sxx = 0;
    for (let i = 0; i < n; i++) { sxy += (s[i] - ms) * (g[i] - mg); sxx += (s[i] - ms) ** 2; }
    bls = sxx > 0 ? sxy / sxx : 0;
  }
  const clip = (b) => Math.max(-lim, Math.min(lim, b));
  const cand = [clip(bls)];
  if (Number.isFinite(lim)) cand.push(-lim, lim);
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
    if (Math.abs(s[j] - s[i]) > EPS) cand.push(clip((g[j] - g[i]) / (s[j] - s[i])));
  }
  let best = null;
  for (const b of cand) {
    const r = spreadAt(s, g, b);
    if (!best || r.w < best.w - 1e-9 || (r.w <= best.w + 1e-9 && Math.abs(b - bls) < Math.abs(best.b - bls))) best = { b, ...r };
  }
  const { b, hi, lo, w } = best;
  const winLo = hi + reveal.min, winHi = lo + reveal.max;
  let mean = 0;
  for (let i = 0; i < n; i++) mean += g[i] - b * s[i];
  const aNom = mean / n + reveal.nominal;
  const feasible = winLo <= winHi + EPS;
  const a = feasible ? Math.max(winLo, Math.min(winHi, aNom)) : (winLo + winHi) / 2;
  return { a, b, spread: w, window: [winLo, winHi], feasible };
}

function slopeAt(groundAt, x, y, h) {
  const gx = (groundAt(x + h, y) - groundAt(x - h, y)) / (2 * h);
  const gy = (groundAt(x, y + h) - groundAt(x, y - h)) / (2 * h);
  return { gx, gy };
}

/**
 * planPiles({ rows, groundAt, system, ...options }) -> { rows, piles, summary, limits, assumed }
 * rows: [{ id?, line: [[x0, y0], [x1, y1]], top?: [zStart, zEnd] }]
 * system: 'tracker' (default) or 'fixed'. Options override DEFAULTS[system] and DEFAULTS:
 *   tableLength, pileSpacing, tableGap, reveal { min, nominal, max }, embedMin, gradingWidth, pileStep, gradStep,
 *   limits { nsMax, ewMax } (override LIMITS[system]).
 */
export function planPiles(opts) {
  const { rows, groundAt } = opts;
  const system = opts.system || 'tracker';
  if (!LIMITS[system]) throw new Error(`piles: unknown system ${system}`);
  if (typeof groundAt !== 'function') throw new Error('piles: groundAt(x, y) is required');
  if (!Array.isArray(rows)) throw new Error('piles: rows must be an array');
  const D = DEFAULTS[system];
  const tableLength = opts.tableLength ?? D.tableLength, pileSpacing = opts.pileSpacing ?? D.pileSpacing;
  const tableGap = opts.tableGap ?? D.tableGap;
  const reveal = { ...D.reveal, ...(opts.reveal || {}) };
  const embedMin = opts.embedMin ?? DEFAULTS.embedMin, gradingWidth = opts.gradingWidth ?? DEFAULTS.gradingWidth;
  const pileStep = opts.pileStep ?? DEFAULTS.pileStep, gradStep = opts.gradStep ?? DEFAULTS.gradStep;
  const revealAdjust = opts.revealAdjust ?? DEFAULTS.revealAdjust, twistTol = opts.twistTolDeg ?? DEFAULTS.twistTolDeg;
  const embedRatio = opts.embedToReveal ?? 0; // embedment at least this x the post's finished reveal (lateral load)
  const limits = { ...LIMITS[system], ...(opts.limits || {}) };
  if (!(reveal.min <= reveal.nominal && reveal.nominal <= reveal.max)) throw new Error('piles: need reveal min <= nominal <= max');
  if (!(embedMin > 0)) throw new Error('piles: embedMin must be positive');
  const alongMax = limits.along === 'ns' ? limits.nsMax : limits.ewMax;

  const outRows = [], allPiles = [];
  const sum = { rows: 0, tables: 0, piles: 0, revealHigh: 0, revealLow: 0, tablesNeedingGrading: 0,
    cutM3: 0, fillM3: 0, nsSlopeTables: 0, ewSlopeTables: 0, topSlopeTables: 0, localSlopeTables: 0, totalPileLengthM: 0,
    revealAdjust: 0, twistTables: 0, embedBelowReveal: 0 };
  rows.forEach((row, ri) => {
    const [[x0, y0], [x1, y1]] = row.line;
    const len = Math.hypot(x1 - x0, y1 - y0);
    if (!(len > EPS)) throw new Error(`piles: row ${row.id ?? ri} has no length`);
    const ux = (x1 - x0) / len, uy = (y1 - y0) / len;
    const { tables, stations } = pileStations(len, tableLength, pileSpacing, tableGap);
    const rv = row.reveal ? { ...reveal, ...row.reveal } : reveal;   // per-row band: a two-post table's rear line
    const rowOut = { id: row.id ?? ri, length: len, bearingDeg: (Math.atan2(ux, uy) * 180 / Math.PI + 360) % 360,
      tables: [], flags: [], cutM3: 0, fillM3: 0 };
    if (!tables.length) rowOut.flags.push('row shorter than one table');
    for (const tb of tables) {
      const st = stations.filter((p) => p.table === tb.table);
      const s = st.map((p) => p.s);
      const xy = s.map((v) => [x0 + ux * v, y0 + uy * v]);
      const g = xy.map(([x, y]) => groundAt(x, y));
      if (g.some((v) => !Number.isFinite(v))) throw new Error(`piles: no ground under row ${rowOut.id}`);
      const fit = row.tops ? { a: 0, b: 0, given: true, at: st.map(p => row.tops[stations.indexOf(p)]) }
        : row.top ? { a: row.top[0], b: (row.top[1] - row.top[0]) / len, given: true }
          : fitTopLine(s, g, rv, alongMax);
      const topOf = k => (fit.at ? fit.at[k] : fit.a + fit.b * s[k]);
      if (fit.at) fit.b = st.length > 1 ? (fit.at[st.length - 1] - fit.at[0]) / (s[st.length - 1] - s[0]) : 0;
      const tOut = { table: tb.table, s0: tb.s0, s1: tb.s1, topLevelStart: fit.at ? fit.at[0] : fit.a + fit.b * tb.s0,
        topLevelEnd: fit.at ? fit.at[st.length - 1] : fit.a + fit.b * tb.s1, topSlope: fit.b, twistDeg: 0, given: !!fit.given, feasible: true,
        piles: [], cutM3: 0, fillM3: 0, maxNs: 0, maxEw: 0, nsSlope: 0, ewSlope: 0, flags: [] };
      st.forEach((p, k) => {
        const [x, y] = xy[k], ground = g[k], top = topOf(k), rev = top - ground;
        const fill = Math.max(rev - rv.max, 0), cut = Math.max(rv.min - rev, 0);
        const finished = ground + fill - cut, finRev = top - finished;
        const emb = Math.max(embedMin, embedRatio * finRev);
        let length = finRev + emb;
        if (pileStep > 0) length = Math.ceil(length / pileStep - 1e-9) * pileStep;
        const { gx, gy } = slopeAt(groundAt, x, y, gradStep);
        const flags = [];
        if (rev > rv.max + EPS) flags.push('reveal-high');
        if (rev < rv.min - EPS) flags.push('reveal-low');
        const adjust = rev - rv.nominal, outsideAdjust = Math.abs(adjust) > revealAdjust + EPS;
        if (outsideAdjust) sum.revealAdjust++;
        if (emb > embedMin + EPS) sum.embedBelowReveal++; // lengthened past the soil's embedment by the lateral-load rule
        const pile = { row: rowOut.id, table: tb.table, index: k, s: p.s, x, y, ground, top, reveal: rev, cut, fill,
          finishedGround: finished, finishedReveal: finRev, embed: length - finRev, toe: top - length, length, adjust, outsideAdjust,
          slopeNs: gy, slopeEw: gx, slopeAlong: gx * ux + gy * uy, slopeCross: -gx * uy + gy * ux, flags };
        tOut.piles.push(pile); allPiles.push(pile);
        tOut.cutM3 += cut * pileSpacing * gradingWidth; tOut.fillM3 += fill * pileSpacing * gradingWidth;
        tOut.maxNs = Math.max(tOut.maxNs, Math.abs(gy)); tOut.maxEw = Math.max(tOut.maxEw, Math.abs(gx)); // local, 1 m
        tOut.nsSlope += gy / st.length; tOut.ewSlope += gx / st.length;                                   // table mean
        if (flags.length) { tOut.feasible = false; if (flags[0] === 'reveal-high') sum.revealHigh++; else sum.revealLow++; }
        sum.piles++; sum.totalPileLengthM += length;
      });
      if (!tOut.feasible) { tOut.flags.push('grading needed'); sum.tablesNeedingGrading++; }
      // Slope limits apply to the table: the mean ground gradient over its piles, so a ditch, a bank or LiDAR noise
      // under one pile does not flag the table. The worst 1 m point gradient is kept as maxNs / maxEw ("local").
      tOut.nsSlope = Math.abs(tOut.nsSlope); tOut.ewSlope = Math.abs(tOut.ewSlope);
      if (tOut.nsSlope > limits.nsMax + EPS) { tOut.flags.push('north-south slope over limit'); sum.nsSlopeTables++; }
      if (tOut.ewSlope > limits.ewMax + EPS) { tOut.flags.push('east-west slope over limit'); sum.ewSlopeTables++; }
      if (tOut.maxNs > limits.nsMax + EPS || tOut.maxEw > limits.ewMax + EPS) sum.localSlopeTables++;
      if (Math.abs(fit.b) > alongMax + EPS) { tOut.flags.push('table slope over limit'); sum.topSlopeTables++; }
      rowOut.cutM3 += tOut.cutM3; rowOut.fillM3 += tOut.fillM3;
      for (const f of tOut.flags) if (!rowOut.flags.includes(f)) rowOut.flags.push(f);
      rowOut.tables.push(tOut); sum.tables++;
    }
    sum.cutM3 += rowOut.cutM3; sum.fillM3 += rowOut.fillM3; sum.rows++;
    outRows.push(rowOut);
  });
  // Twist: a front row and its rear row carry one rigid table each; their top slopes may differ only by the tolerance.
  rows.forEach((row, ri) => {
    const mi = row.pair ? outRows.findIndex(r => r.id === row.pair.with) : -1, mate = outRows[mi];
    if (!mate || (mi < ri && rows[mi].pair?.with === outRows[ri].id)) return; // each pair once
    outRows[ri].tables.forEach((t, k) => {
      const m = mate.tables[k]; if (!m) return;
      t.twistDeg = m.twistDeg = twistDeg(t.topSlope, m.topSlope, tableLength, row.pair.depth);
      if (t.twistDeg > twistTol + EPS) {
        for (const x of [t, m]) if (!x.flags.includes('twist over tolerance')) x.flags.push('twist over tolerance');
        sum.twistTables++;
      }
    });
  });
  return {
    system, rows: outRows, piles: allPiles, summary: sum,
    limits: { nsMax: limits.nsMax, ewMax: limits.ewMax, alongMax, note: limits.note },
    assumed: { tableLength, pileSpacing, tableGap, reveal, embedMin, gradingWidth, pileStep, gradStep, revealAdjust, twistTolDeg: twistTol,
      note: 'ASSUMED defaults unless passed in: replace with the product datasheet and the geotechnical report. '
        + 'Embedment is the same for every pile, independent of reveal: set it from pile tests. Grading volumes are '
        + 'indicative: depth x pile spacing x grading width per pile.' },
  };
}

/**
 * followTopLine(s, g, nominal, bayMax): a terrain-following tube over posts at chainages s on ground g. It starts at
 * ground + nominal and, pass after pass, pulls each inner post towards the straight line through its neighbours until
 * the slope changes by at most bayMax from bay to bay. Returns the tops.
 */
export function followTopLine(s, g, nominal, bayMax, passes = 400) {
  const t = g.map(v => v + nominal), n = t.length;
  for (let k = 0; k < passes; k++) {
    let moved = 0;
    for (let i = 1; i < n - 1; i++) {
      const h1 = s[i] - s[i - 1], h2 = s[i + 1] - s[i], mid = (t[i - 1] * h2 + t[i + 1] * h1) / (h1 + h2);
      const e = bayMax / (1 / h1 + 1 / h2), d = t[i] - mid, c = Math.max(-e, Math.min(e, d));
      if (Math.abs(c - d) > 1e-12) { t[i] = mid + c; moved++; }
    }
    if (!moved) break;
  }
  return t;
}

/** Reveal distribution of a set of piles: percentiles 0, 5, 25, 50, 75, 95, 100 (nearest-rank). */
export function revealPercentiles(piles) {
  const v = piles.map((p) => p.reveal).sort((a, b) => a - b);
  if (!v.length) return [];
  return [0, 5, 25, 50, 75, 95, 100].map((q) => v[Math.min(v.length - 1, Math.max(0, Math.ceil(q / 100 * v.length) - 1))]);
}

Plant Feeders

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

transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/plant-feeders.mjs · lines 1–140 of 140 · version 2026-09-27 17:40 · pattern routeFeeders (shared by 4 files)

What it does
It calculates cables, 33kV and A roads. Defines 11 functions or classes, including toSpine, roadPath, side, coverage, trenchFor.
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, 33kV, A roads.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 4 files: Block MV (globalgrid2050); Cmd Model (globalgrid2050); Plant Layout (globalgrid2050); Plant UI (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 routes feeders (`routeFeeders`) and is built from the to spine helper (`toSpine`) and the road path helper (`roadPath`). The 33kV feeders of a laid-out plant, routed along its roads, with their trenches and cables. Its code works with 33 kV.
Why it matters
Imported by 4 files, including Block MV, Cmd Model and Plant Layout.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Cable Rating (import), Trench Plan (import)
Used by
imported by Block MV (import), imported by Cmd Model (import), imported by Plant Layout (import), imported by Plant UI (import)
Produces
SECTION_FOR, CABLE_ALLOW, roadPath, coverage, trenchFor, routeFeeders, SECTION_WORDS, trenchRows
Defines here
toSpine, roadPath, side, coverage, trenchFor, routeFeeders, onRoad, add, dropOf, trenchRows, k
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/plant-feeders.mjs:1-140 · blob 41af101dc03f6e5bf650be8182a15e0a326dd9a2 · 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
// plant-feeders.mjs: the 33 kV feeders of a laid-out plant, routed along its roads, with their trenches and cables.
//
// Each feeder of the plant template runs from its board in the substation compound along the access road, the
// spine and the branch tracks to its first station, then station to station. Routes stay on the road network
// (a comb: one spine, tracks off it), so every route is a set of intervals on a few straight lines. Where several
// circuits share a stretch they share a trench: one circuit in a single trefoil trench, two in a two-circuit
// trench, more in parallel trenches. Where a circuit turns across a road it goes in ducts.
// Cable lengths: route plus 3 % for snaking and 5 m at each end for terminations, three single cores a circuit.
// Voltage drop is worked out on the routed lengths (cable-rating.mjs), replacing the template's placeholder lengths;
// where it passes the limit, the segment that saves most drop per step is upsized, as the template does.
// Trench section ids are those of data/trench-sections.json: farmland cover (0.91 m) for the runs, ducts at crossings.
// The busiest hop's cable is checked by rating (trench-plan.mjs) alone and two circuits side by side as the section
// draws them. Pure: imports only the rating cartridges.

import { dropPercent, SIZES, build } from './cable-rating.mjs';
import { checkAsDrawn } from './trench-plan.mjs';

export const SECTION_FOR = Object.freeze({ one: '33kv-1-agri', two: '33kv-2-agri', crossing: '33kv-1-ducted' });
export const CABLE_ALLOW = Object.freeze({ slack: 0.03, tailM: 5, cores: 3 });

// A point on the road network: on a track (k, u), on the access road (u), or on the spine (v).
function toSpine(pt, net) {
  if (pt.line === 'track') return { parts: [{ key: 't' + pt.k, a: pt.u, b: net.us }], v: net.tracks[pt.k] };
  if (pt.line === 'access') return { parts: [{ key: 'a', a: pt.u, b: net.us }], v: net.cv };
  return { parts: [], v: pt.v };
}

/** Intervals from A to B along the roads, and how many times the route turns across a road. */
export function roadPath(A, B, net) {
  const side = pt => Math.sign(pt.u - net.us);
  if (A.line === 'track' && B.line === 'track' && A.k === B.k && side(A) === side(B)) return { parts: [{ key: 't' + A.k, a: A.u, b: B.u }], turns: 0 };
  const a = toSpine(A, net), b = toSpine(B, net);
  const parts = [...a.parts, ...(a.v !== b.v ? [{ key: 's', a: a.v, b: b.v }] : []), ...b.parts];
  return { parts: parts.filter(q => q.a !== q.b), turns: (a.parts.length ? 1 : 0) + (b.parts.length ? 1 : 0) };
}

/** Sweep a line's intervals into stretches with a constant circuit count: [{ a, b, c }]. */
export function coverage(intervals) {
  const ev = [];
  for (const { a, b } of intervals) { ev.push([Math.min(a, b), 1], [Math.max(a, b), -1]); }
  ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const out = [];
  let c = 0, last = null;
  for (const [x, d] of ev) {
    if (c > 0 && last !== null && x > last) {
      const prev = out[out.length - 1];
      if (prev && prev.c === c && Math.abs(prev.b - last) < 1e-9) prev.b = x; else out.push({ a: last, b: x, c });
    }
    c += d; last = x;
  }
  return out;
}

/** Trench metres by section for a stretch of length L carrying c circuits. */
export function trenchFor(c, L, into) {
  const two = Math.floor(c / 2), one = c % 2;
  if (two) into[SECTION_FOR.two] = (into[SECTION_FOR.two] || 0) + two * L;
  if (one) into[SECTION_FOR.one] = (into[SECTION_FOR.one] || 0) + L;
  return into;
}

/**
 * routeFeeders(template, net, p) -> { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct, crossings }
 * net: { us, cv, spine, access, tracks, stations: [{ id, u, v, k, track }] } in the layout frame.
 */
export function routeFeeders(tpl, net, p) {
  const at = new Map(net.stations.map(s => [s.id, s]));
  const board = net.access ? { line: 'access', u: net.access.u0 } : { line: 'spine', v: net.cv };
  const onRoad = s => ({ line: 'track', k: s.k, u: s.u });
  const byKey = new Map(), stubs = new Map();
  const add = (key, a, b) => { if (!byKey.has(key)) byKey.set(key, []); byKey.get(key).push({ a, b }); };
  const opts = { pf: tpl.params.powerFactor, soilKmW: tpl.params.soilKmW, kv: 33 };
  const cableBySize = {}, trenchByType = {};
  let crossings = 0, cableM = 0, worst = 0, upsized = 0;
  const dropOf = hops => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opts), 0);
  const feeders = tpl.feeders.map((f, fi) => {
    let from = board, fromStub = 0, fromId = null;
    const hops = f.chain.map((st, k) => {
      const s = at.get(st.id), to = onRoad(s), path = roadPath(from, to, net), stub = Math.abs(s.v - s.track);
      for (const q of path.parts) add(q.key, q.a, q.b);
      stubs.set(s.id, (stubs.get(s.id) || 0) + 1);
      if (fromId) stubs.set(fromId, stubs.get(fromId) + 1);
      crossings += path.turns;
      const road = path.parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0), seg = f.segments[k];
      const hop = { from: fromId || f.board, to: s.id, areaMm2: seg.area, loadMVA: seg.loadMVA, lengthM: road + stub + fromStub, parts: path.parts };
      from = to; fromStub = stub; fromId = s.id;
      return hop;
    });
    for (let guard = 0; dropOf(hops) > tpl.params.vdropLimitPct && guard < 60; guard++) {
      const can = hops.filter(h => h.areaMm2 < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
      if (!can) break;
      can.areaMm2 = SIZES[SIZES.indexOf(can.areaMm2) + 1]; upsized++;
    }
    for (const h of hops) {
      const cable = CABLE_ALLOW.cores * (h.lengthM * (1 + CABLE_ALLOW.slack) + 2 * CABLE_ALLOW.tailM);
      cableBySize[h.areaMm2] = (cableBySize[h.areaMm2] || 0) + cable; cableM += cable;
    }
    const drop = dropOf(hops);
    worst = Math.max(worst, drop);
    return { id: `F${fi + 1}`, board: f.board, hops, dropPct: drop, stations: f.chain.map(s => s.id) };
  });

  // Shared stretches: one trench per stretch, sized by the circuits in it.
  const pieces = [];
  let trenchM = 0;
  for (const [key, list] of byKey) for (const { a, b, c } of coverage(list)) {
    pieces.push({ key, a, b, c }); trenchFor(c, b - a, trenchByType); trenchM += b - a;
  }
  for (const [id, c] of stubs) {
    const s = at.get(id), L = Math.abs(s.v - s.track);
    if (L > 0) { pieces.push({ key: 'stub:' + id, a: s.track, b: s.v, c, u: s.u }); trenchFor(c, L, trenchByType); trenchM += L; }
  }
  const crossM = crossings * (p.spineWidthM + 2);
  if (crossM) { trenchByType[SECTION_FOR.crossing] = (trenchByType[SECTION_FOR.crossing] || 0) + crossM; trenchM += crossM; }
  // Rating of the shared trenches: the busiest hop's cable alone, and two such circuits at 450 mm centres.
  const busy = feeders.flatMap(f => f.hops).sort((a, b) => b.loadMVA - a.loadMVA)[0];
  let trenchRating = null;
  if (busy) {
    const spec = { loadA: busy.loadMVA * 1e6 / (Math.sqrt(3) * 33000), areaMm2: busy.areaMm2, odMm: build(busy.areaMm2).od };
    const env = { soilKmW: tpl.params.soilKmW || 1.2 }, one = checkAsDrawn('mv', 1, spec, 0.45, env), two = checkAsDrawn('mv', 2, spec, 0.45, env);
    trenchRating = { hop: `${busy.from} to ${busy.to}`, loadA: Math.round(spec.loadA), areaMm2: busy.areaMm2, one: one.utilisation, two: two.utilisation,
      ok: two.utilisation <= 1, basis: 'IEC 60287 method (own code), 0.91 m cover; indicative' };
  }
  return { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct: worst, crossings, upsized, trenchRating,
    dropOk: worst <= tpl.params.vdropLimitPct + 1e-9 };
}

// Readout rows for the MV trenches and cables that add up, in words (user test H3). Each trench is counted: where more
// than two circuits share a stretch the trenches run side by side, so trench-km can exceed the route. Cable is single
// core (three per circuit, with slack and tails); circuit-km is a third of it.
export const SECTION_WORDS = Object.freeze({ [SECTION_FOR.one]: 'one 33 kV circuit, farmland (0.91 m cover)',
  [SECTION_FOR.two]: 'two 33 kV circuits', [SECTION_FOR.crossing]: 'road crossings, ducted' });
export function trenchRows(e, fmt = v => v.toFixed(2)) {
  const k = m => fmt(m / 1000), types = Object.entries(e.trenchByType || {}).filter(([, m]) => m > 0), total = types.reduce((t, [, m]) => t + m, 0);
  const rows = [['MV trenches', `${k(total)} trench-km, along ${k(e.trenchM)} km of route`]];
  for (const [id, m] of types) rows.push(['', `${SECTION_WORDS[id] || 'other trench'}: ${k(m)} trench-km`]);
  rows.push(['MV cable', `${k(e.cableM / CABLE_ALLOW.cores)} circuit-km (${k(e.cableM)} km of single-core cable)`]);
  for (const [a, m] of Object.entries(e.cableBySize || {}).sort((x, y) => x[0] - y[0])) rows.push(['', `${a} mm² aluminium: ${k(m / CABLE_ALLOW.cores)} circuit-km`]);
  return { rows, trenchKm: total / 1000 };
}