GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / energy-transition-simulator/202609280014/mod/engine

Piles and 2 more files (part 3)

A JavaScript module in the engine folder of GlobalGrid2050 that fits top line (`fitTopLine`) and calculates planar distances and angles.

448 lines of JavaScript from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 847 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. Pile Rules render · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/pile-rules.mjs lines 1–122
  2. Piles transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/piles.mjs lines 1–278
  3. Plant Central transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/plant-central.mjs lines 1–48

Pile Rules

A JavaScript module in the engine folder of GlobalGrid2050 that works with tracker hub (`trackerHub`) and reveal band (`revealBand`).

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

Evidence
  • line-jaccard 0.9789 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/pile-rules.mjs:1-120 16c3cea0ee098709b4cf32073c6ea7b32fc1ded3
  • sha256 3410ba01ff365af706a0587191edff92d1328f5380922defc646f39e27cd50a0
  • target sha256 7c92ca68729657a9d06db87891f96cb0ccc58d48d7cb7bc4e43e871a70b5cee7
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/pile-rules.mjs · lines 1–122 of 122 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern heightFlags (shared by 3 files)

What it does
Defines 8 functions or classes, including rulesFor, revealAt, trackerHub, revealBand, heightFlags. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 3 files: Block Build (globalgrid2050); Piles (globalgrid2050); Plant Piles (globalgrid2050).
What it achieves
It is built from the rules for helper (`rulesFor`), the reveal at helper (`revealAt`) and the tracker hub helper (`trackerHub`). The one set of pile rules shared by the pile row tool (`piles.mjs`), the plant layout (`plant-piles.mjs`) and the solar block (`block-build.mjs`), with two profiles: fixed tilt and single-axis tracker.
Why it matters
Imported by Block Build, Piles and Plant Piles.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Block Build (import), imported by Piles (import), imported by Plant Piles (import)
Produces
SOILS, PROFILES, PILE_RULES, TRACKER_RULES, rulesFor, revealAt, trackerHub, revealBand, heightFlags, withSoil, tableLines, twistDeg
Defines here
rulesFor, revealAt, trackerHub, revealBand, heightFlags, withSoil, tableLines, twistDeg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/pile-rules.mjs:1-122 · blob 87f034a63d24882038848165fac4ce153fdaf145 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 pile-rules.mjs at v12 commit 3adcee9 (file last changed f52e11f). Modular star family: public #147905 revealAt.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// pile-rules.mjs: the one set of pile rules shared by the pile row tool (piles.mjs), the plant layout (plant-piles.mjs)
// and the solar block (block-build.mjs), with two profiles: fixed tilt and single-axis tracker.
//
// Every figure here is ILLUSTRATIVE and EDITABLE (world.piles.auto({ rules }) and the typed "piles" command): a generic
// starting point to be replaced by the chosen product's datasheet, the project spec and the site's
// geotechnical report (pile load tests set the embedment). None is a design value. Values follow the generic piling
// rules study (pile-rules.json v1, ids as PILING-RULES.md: R reveal, F fixed and K tracker tolerances, S slopes,
// E embedment by soil, L testing); the head adjustment (0.25 m) is the GPU prototype's.
//
// FIXED TILT. Reveal (how far a post stands out of the ground) is DERIVED from the table:
//   module surface at a fraction f up the slope = lowEdge + rise * f; rails hang railDepth below the modules, so
//   reveal = lowEdge + rise * f - railDepth.
// One post at mid-slope: 0.8 m low edge, 2P portrait at 25 deg (rise 2.02 m), 0.3 m rails -> 1.51 m. Two posts at 0.2
// and 0.8 of the depth: 0.90 m front, 2.12 m rear. A fixed rafter keeps its tilt: front and rear are fitted as one rigid
// frame (rear top = front top + the difference in nominal reveal) and the posts take the cross slope.
// Tolerances: a post more than revealAdjust from its nominal is outside the head adjustment (flagged); outside the band
// [nominal - below, nominal + above] the ground is graded. Twist: the change of the rafter angle from one end of the
// table to the other that the ground under the front and rear lines asks for (their least-squares slopes); over
// twistTolDeg the table cannot be warped to follow, so the posts and grading take it.
//
// TRACKER. Posts stand along the torque tube, one line per row, running north-south. The tube height clears the
// ground by clearance at the largest rotation: hub = clearance + (module length / 2) sin(maxRotation); the post reveal is
// the axis height less the bearing offset (R5, R7). A terrain-following tracker bends at its bearings: the tube may
// change slope from bay to bay by at most bayChangeMaxDeg (S5) and slope along the row by at most alongMaxPct (S3).
// Post reveals must sit inside the hard reveal window (R7); head height and plumb are installation tolerances (K1-K6),
// tighter than fixed tilt, stated, not computed.
// A row the tube cannot follow within those limits is flagged: it needs grading.
// Pure: no imports, no DOM.

// Embedment by soil (E, default of each range), fixed and tracker; the soil is chosen per site (default stiff clay).
export const SOILS = Object.freeze({ stiff_clay: [1.6, 2.3], soft_clay_alluvium: [2.6, 3.2], peat_organic: [4.0, 4.5], dense_sand: [1.8, 2.4],
  loose_sand: [2.4, 3.0], gravel_till: [1.6, 2.2], chalk: [1.7, 2.3], weak_rock: [1.2, 1.8] });
const COMMON = {
  label: 'Illustrative pile rules (editable): replace with the product datasheet, the project spec and the geotechnical report.',
  soil: 'stiff_clay',
  embedGpuM: Object.freeze({ min: 1.2, nominal: 1.6 }), // the GPU prototype's figures, for comparison
  proofTestPct: 1.0,       // production proof tests, % of piles (L3, range 0.5-2)
  revealAdjustM: 0.25,     // head adjustment: +/- from nominal without a different post
  embedToReveal: 0.75,     // lateral load, a rule of thumb: embedment at least 0.75 x the post's reveal (longer post)
  gradingWidthM: 2.0,      // width graded along a pile line
  lowEdgeClearM: 0.5,      // lowest module edge over the ground: flagged below this
  pileSpacingM: Object.freeze({ fixed: 5, tracker: 7 }),
  grading: Object.freeze({ dropOverM: 0.6, mergeGapM: 2 }) // deeper than 0.6 m of grading: suggest dropping the table
};

export const PROFILES = Object.freeze({
  fixed: Object.freeze({ ...COMMON, system: 'fixed', embedM: SOILS.stiff_clay[0], embedMinM: 1.0, // E, E-min
    revealBelowM: 0.4, revealAboveM: 0.6,  // band about nominal; outside it the ground is graded
    // R4, relative: warn when a post stands more than revealWarnAboveM over ITS design height (the rear posts of a 2P
    // table stand 2.12 m by design, so a fixed 2.0 m line flagged every one); revealFailM is a hard maximum for any post.
    revealWarnAboveM: 0.5, revealFailM: 3.0,
    twistTolDeg: 3.0,                      // F6: rafter angle change end to end the table can take
    headTolMm: 30, plumbTolDeg: 2.0,       // F4, F3: installation, stated
    railDepthM: 0.3, pivot: 0.5, twoPost: Object.freeze([0.2, 0.8]) }),
  tracker: Object.freeze({ ...COMMON, system: 'tracker', embedM: SOILS.stiff_clay[1], embedMinM: 1.5,
    axisHeightM: 1.4, bearingDropM: 0.15,  // R5, R7: 1P axis height, bearing offset
    revealWindowM: Object.freeze([0.95, 1.45]), // R7: hard window for every post
    headTolMm: 20, plumbTolDeg: 1.5,       // K: standard pile (drive piles 10 mm, 0.5 deg east-west), installation, stated
    alongMaxPct: 15, crossMaxPct: 7, bayChangeMaxDeg: 0.5, // S3, S4, S5
    maxRotationDeg: 60, moduleLongM: 2.384, lowEdgeFullTiltM: 0.5, twistTolDeg: Infinity })
});
export const PILE_RULES = PROFILES.fixed; // the fixed-tilt profile, the default everywhere
export const TRACKER_RULES = PROFILES.tracker;
export const rulesFor = system => PROFILES[system === 'tracker' ? 'tracker' : 'fixed'];

/** Nominal reveal of a fixed-tilt post at fraction f up the slope of a table: lowEdge + rise f - railDepth. */
export function revealAt({ lowEdgeM, rise, f, railDepthM = PILE_RULES.railDepthM }) {
  if (!(lowEdgeM >= 0) || !(rise >= 0) || !(f >= 0 && f <= 1)) throw new Error('pile rules: need lowEdge >= 0, rise >= 0 and 0 <= f <= 1');
  return lowEdgeM + rise * f - railDepthM;
}

/** Tracker: axis (hub) height, post reveal, and the lowest module edge at full tilt. */
export function trackerHub(R = TRACKER_RULES) {
  const hub = R.axisHeightM;
  return { hub, reveal: hub - R.bearingDropM, lowEdgeFullTilt: hub - R.moduleLongM / 2 * Math.sin(R.maxRotationDeg * Math.PI / 180) };
}

/** The reveal band about a nominal: { min, nominal, max }; a tracker's is its hard window. */
export function revealBand(nominal, rules = PILE_RULES) {
  if (rules.revealWindowM) return { min: rules.revealWindowM[0], nominal, max: rules.revealWindowM[1] };
  return { min: nominal - rules.revealBelowM, nominal, max: nominal + rules.revealAboveM };
}

/**
 * Height checks of one post against its design (nominal) reveal: { high: stands more than revealWarnAboveM above its design
 * height, overMax: stands over the hard maximum revealFailM }. A rule left out never fires.
 */
export function heightFlags(reveal, design, rules = PILE_RULES) {
  const up = rules.revealWarnAboveM, max = rules.revealFailM;
  return { high: Number.isFinite(up) && reveal > design + up + 1e-9, overMax: Number.isFinite(max) && reveal > max + 1e-9 };
}

/** Rules with the embedment of a soil (SOILS) in place of the default. */
export function withSoil(rules, soil) {
  const e = SOILS[soil];
  return e ? { ...rules, soil, embedM: e[rules.system === 'tracker' ? 1 : 0] } : rules;
}

/**
 * Pile lines of a table: [{ f (fraction of the plan depth from the low edge), nominal }].
 * fixed: posts 1 (the pivot) or 2 (front and rear); east-west (ridge): one line per face at the face's pivot;
 * tracker: one line under the tube (f = 0.5).
 */
export function tableLines({ lowEdgeM, rise, posts = 2, eastWest = false, tracker = false, rules = PILE_RULES }) {
  if (tracker) return [{ f: 0.5, nominal: trackerHub(rules.system === 'tracker' ? rules : TRACKER_RULES).reveal }];
  const rd = rules.railDepthM;
  if (eastWest) return [0.25, 0.75].map(f => ({ f, nominal: revealAt({ lowEdgeM, rise, f: rules.pivot, railDepthM: rd }) }));
  const fs = posts === 1 ? [rules.pivot] : rules.twoPost;
  return fs.map(f => ({ f, nominal: revealAt({ lowEdgeM, rise, f, railDepthM: rd }) }));
}

/**
 * Twist, degrees: the change of the rafter angle from one end of a table of length len to the other, when the rear line
 * is dz above the front across the plan distance depth at the first end and the lines' slopes differ by bRear - bFront.
 * With dz = 0 it is the rotation of a flat section.
 */
export function twistDeg(bFront, bRear, len, depth, dz = 0) {
  if (!(depth > 0)) return 0;
  return Math.abs(Math.atan((dz + (bRear - bFront) * len) / depth) - Math.atan(dz / depth)) * 180 / Math.PI;
}

Piles

A JavaScript module in the engine folder of GlobalGrid2050 that fits top line (`fitTopLine`) and calculates planar distances and angles.

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

Evidence
  • line-jaccard 0.9914 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/piles.mjs:1-276 1795fce86a634da83eaa08325d686215ac9289c4
  • sha256 e20b04d6ad03a153f81356fc530e6b79df329fc9ee867d10ff3b4a6062f2fc03
  • target sha256 24eadeae9652609f6eceb501e7a760f9173683f64200e8cac6f190c51617cef7
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

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

What it does
It calculates its inputs. Defines 9 functions or classes, including pileStations, spreadAt, fitTopLine, clip, slopeAt.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 2 files: Block Build (globalgrid2050); Plant Piles (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 Block Build and Plant Piles.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Pile Rules (import)
Used by
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 energy-transition-simulator/202609280014/mod/engine/piles.mjs:1-278 · blob 2a128762724345971a30d85f3b592c7cd2d259ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 piles.mjs at v12 commit 3adcee9 (file last changed 8903e78). Modular star family: public #145217 pileStations.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// 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 Central

A JavaScript module in the engine folder of GlobalGrid2050 that works with transformers. It is built from the central items helper (`centralItems`) and the item solids helper (`itemSolids`).

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

What it does
It calculates transformers. Defines centralItems, itemSolids.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: transformers.
What it achieves
What a central-inverter plant adds to the drawing.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Station (import)
Used by
none found
Produces
CENTRAL_EQUIPMENT, centralItems, itemSolids
Defines here
centralItems, itemSolids
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/plant-central.mjs:1-48 · blob 09ec548bac499df53242bd0d85fc3740da67b0ab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 plant-central.mjs at v12 commit 3adcee9 (file last changed a83209f). Modular star family: not known to star-find.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// plant-central.mjs: what a central-inverter plant adds to the drawing. Each central station (plant-template.mjs,
// inverterClass 'central') is one container on its pad: the central inverters, the MV transformer and switchgear
// together (a 40 ft container, the generic class; a skid is drawn the same size). Its strings reach it through DC
// combiner boxes, one per group of tables: the station's tables in layout order are split into as many groups as it
// has boxes, and each box stands on a post just south of the low edge of its group's middle table.
// Sizes are generic and rounded, not any product; illustrative only. Pure: imports only the placer.

import { placer } from './station.mjs';

export const CENTRAL_EQUIPMENT = Object.freeze({
  skid: { w: 12.2, d: 2.5, h: 2.9, label: 'central inverter station: inverters, MV transformer and switchgear in a 40 ft container (generic)' },
  combiner: { w: 0.9, d: 0.35, h: 1.1, label: 'DC combiner box on a post (generic)' }
});

/**
 * Items of a laid-out plant's central stations in the layout frame: [{ kind: 'skid' | 'combiner', u, v, id, station }].
 * r: plant-layout.mjs result. Tables are stored station by station (each station's r.stations[k].tables in turn).
 */
export function centralItems(r) {
  const out = [], T = r?.table, t = r?.tables;
  if (!T || !t) return out;
  let q0 = 0;
  for (const st of r.stations || []) {
    const n = st.tables || 0;
    if (st.central) {
      out.push({ kind: 'skid', u: st.u, v: st.v, id: st.id, station: st.id });
      const boxes = Math.max(1, Math.min(st.combiners || 1, n));
      for (let b = 0; b < boxes && n; b++) {
        const a = q0 + Math.floor(b * n / boxes), z = q0 + Math.floor((b + 1) * n / boxes) - 1, m = Math.floor((a + z) / 2);
        const L = r.tableLen?.[m] ?? T.lenU;
        out.push({ kind: 'combiner', u: t[m * 6] + L / 2, v: t[m * 6 + 1] - 0.6, id: `${st.id}-CB${b + 1}`, station: st.id });
      }
    }
    q0 += n;
  }
  return out;
}

/** Solids of one item at a placed point (national-grid offsets and ground height), as mv-network.mjs draws them. */
export function itemSolids(kind, at = [0, 0, 0], id = kind, heading = 0) {
  const e = CENTRAL_EQUIPMENT[kind];
  if (!e) throw new Error(`plant central: unknown item ${kind}`);
  const P = placer(at, heading), out = [P.box({ kind, part: 'body', id, min: [-e.w / 2, -e.d / 2, kind === 'combiner' ? 0.5 : 0], max: [e.w / 2, e.d / 2, e.h] })];
  if (kind === 'combiner') out.push(P.box({ kind, part: 'post', id, min: [-0.04, -0.04, 0], max: [0.04, 0.04, 0.5] }));
  return out;
}