GLOBALGRID2050 / EXPLORE CODE

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

Plant Template and 3 more files (part 2)

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

595 lines of JavaScript from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 849 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. Plant Piles transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/plant-piles.mjs lines 1–206
  2. Plant Template electrical · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/plant-template.mjs lines 1–267
  3. Renewable Energy Planning Database (REPD) Grammar energy-data · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/repd-grammar.mjs lines 1–72
  4. Site Checks transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/site-checks.mjs lines 1–50

Plant Piles

A JavaScript module in the engine folder of GlobalGrid2050 that works with ls slope (`lsSlope`) and plan tables (`planTables`).

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

Evidence
  • line-jaccard 0.9884 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/plant-piles.mjs:1-204 170d55a05d148fecb0b9d29007cef175b139babb
  • sha256 3344edc92ef1d2d95e8e063e6494b06d74e4006f306d93451e86ee572e6f6784
  • target sha256 cea4b033ccd0afcdb3fa5bd7024467cca519e61b764a6365a5a23b396ad0de23
  • 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/plant-piles.mjs · lines 1–206 of 206 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern gradingSuggestions (shared by 3 files)

What it does
It calculates its inputs. Defines 18 functions or classes, including lsSlope, planTables, gq, gs, at.
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 1 file: Plant Layout (globalgrid2050).
What it achieves
It is built from the ls slope helper (`lsSlope`), the plan tables helper (`planTables`) and the clear step (`clear`). The piles of every table of a laid-out plant (`plant-layout.mjs`), fixed tilt or single-axis tracker, worked out automatically on the measured ground.
Why it matters
Imported by Plant Layout.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Piles (import), Pile Rules (import)
Used by
imported by Plant Layout (import)
Produces
PILES_LABEL, planTables, STRIDE, gradingSuggestions, pileSummary, pileBoqItems, layoutTables, pilesForLayout
Defines here
lsSlope, planTables, gq, gs, at, sm, clear, tableResult, surf, has, gradingSuggestions, act, pileSummary, acts, pct, pileBoqItems, layoutTables, pilesForLayout
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-piles.mjs:1-206 · blob d6f8cbd38477e1eceaa81ee13b00ad5f55895171 · 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-piles.mjs at v12 commit 3adcee9 (file last changed b484f9f). Modular star family: public #147944 planTables.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// plant-piles.mjs: the piles of every table of a laid-out plant (plant-layout.mjs), fixed tilt or single-axis tracker,
// worked out automatically on the measured ground. Nobody places a pile: piles are an output of the tables.
//
// Each table gets its pile lines from its geometry (pile-rules.mjs tableLines).
// FIXED TILT: a south-facing two-post table has a front and a rear line at 0.2 and 0.8 of its depth, each with its own
// nominal reveal (lowest module edge + rise x fraction - rails); an east-west table has one line under each face.
// The table is one rigid frame, so its tilt never changes: all its posts are fitted together (fitTopLine: the straight
// top within the along-row slope limit with the least reveal spread; ties in slope go to the one nearest the
// least-squares slope, so the fit is unique), the rear top the difference in nominal reveal above the front. The posts
// take the cross slope. Checks: reveal band and head adjustment (planPiles), the twist the ground asks for (from the
// least-squares slopes of the ground, smoothed over 4 m, under the front and rear lines, as a change of rafter angle),
// the lowest module edge's clearance, reveal over the warn and fail heights.
// TRACKER: one line of posts along the torque tube; the tube follows the ground within the bay-to-bay slope change
// (followTopLine); posts off the tube line by more than the height tolerance mean the tracker cannot follow: grading.
// Every table whose ground is not measured under some posts is flagged, never silently filled in.
// gradingSuggestions groups the tables that need grading into patches: regrade, raise, or drop the table.
// Figures are ILLUSTRATIVE (pile-rules.mjs); embedment is provisional. Pure: no DOM. Runs as a generator in chunks.

import { planPiles, fitTopLine, followTopLine, pileStations, LIMITS } from './piles.mjs';
import { PILE_RULES, rulesFor, tableLines, revealBand, twistDeg, withSoil, heightFlags } from './pile-rules.mjs';

export const PILES_LABEL = 'Piles from the tables, automatic, on illustrative rules: embedment provisional (pile tests set it).';
const CHUNK = 8; // tables per planPiles call: a short step on a slow phone (measured ground is slower to sample than a formula)
const SMOOTH_M = 2; // twist is read from the ground averaged over a 4 m cross at each post

function lsSlope(s, g) {
  const n = s.length, ms = s.reduce((a, v) => a + v, 0) / n, mg = g.reduce((a, v) => a + 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; }
  return sxx > 0 ? sxy / sxx : 0;
}

/**
 * planTables(tables, { groundAt(e, n), system, posts, rules, along, pileSpacing, railDepthM }) -> generator; returns
 * { tables: [result per table], unmeasured, rules, system }. A table in: { lineAt(f) -> [[e0, n0], [e1, n1]] (its pile
 * line at fraction f of the depth from the low edge), length, depth, rise, lowEdgeM, eastWest, key: [lane, start, end] }.
 */
export function* planTables(tablesIn, { groundAt, system = 'fixed', posts = 2, rules, along = 'ew', pileSpacing, railDepthM } = {}) {
  const tracker = system === 'tracker', R = { ...(rules || rulesFor(system)), ...(railDepthM != null ? { railDepthM } : {}) };
  const sp = pileSpacing ?? R.pileSpacingM[tracker ? 'tracker' : 'fixed'];
  let last = 0, missing = 0, unmeasured = 0;
  const gq = (e, n) => { const h = groundAt(e, n); if (Number.isFinite(h)) { last = h; return h; } missing++; return last; };
  const gs = (e, n) => { const h = groundAt(e, n); return Number.isFinite(h) ? h : last; };
  const alongMax = tracker ? R.alongMaxPct / 100 : along === 'ns' ? LIMITS.fixed.nsMax : LIMITS.fixed.ewMax;
  const out = [];
  for (let c = 0; c < tablesIn.length; c += CHUNK) {
    // Tables of one length are planned together: a half table closing a row end is planned at its own length.
    const part = tablesIn.slice(c, c + CHUNK), groups = new Map(), meta = [];
    for (const T of part) {
      if (!groups.has(T.length)) groups.set(T.length, []);
      const rows = groups.get(T.length);
      const lines = tableLines({ lowEdgeM: T.lowEdgeM, rise: T.rise, posts: T.eastWest ? 2 : posts, eastWest: T.eastWest, tracker, rules: R });
      const s = pileStations(T.length, T.length, sp, 0).stations.map(p => p.s), m0 = missing, flags = [], base = rows.length;
      const at = (f, v) => { const [[x0, y0], [x1, y1]] = T.lineAt(f), k = v / T.length; return [x0 + (x1 - x0) * k, y0 + (y1 - y0) * k]; };
      const gl = lines.map(L => s.map(v => gq(...at(L.f, v))));
      let twist = 0;
      if (tracker) {
        const tops = followTopLine(s, gl[0], lines[0].nominal, Math.tan(R.bayChangeMaxDeg * Math.PI / 180));
        rows.push({ id: base, line: T.lineAt(0.5), reveal: revealBand(lines[0].nominal, R), tops });
        if (tops.some((z, i) => i && Math.abs(z - tops[i - 1]) / (s[i] - s[i - 1]) > alongMax + 1e-9)) flags.push('slope along the row over the tracker limit');
      } else {
        const fit = fitTopLine(lines.flatMap(() => s), gl.flat(), revealBand(lines[0].nominal, R), alongMax);
        lines.forEach((L, i) => { const d = L.nominal - lines[0].nominal;
          rows.push({ id: base + i, line: T.lineAt(L.f), reveal: revealBand(L.nominal, R), top: [fit.a + d, fit.a + d + fit.b * T.length] }); });
        if (lines.length > 1) {
          const dd = (lines[1].f - lines[0].f) * T.depth, dz = T.eastWest ? 0 : lines[1].nominal - lines[0].nominal;
          // On ground smoothed over a 4 m cross (SMOOTH_M each way), so 1 m LiDAR texture does not read as twist.
          const sm = f => s.map(v => { const [x, y] = at(f, v); return (gs(x, y) + gs(x + SMOOTH_M, y) + gs(x - SMOOTH_M, y) + gs(x, y + SMOOTH_M) + gs(x, y - SMOOTH_M)) / 5; });
          twist = twistDeg(lsSlope(s, sm(lines[0].f)), lsSlope(s, sm(lines[1].f)), T.length, dd, dz);
          if (twist > R.twistTolDeg + 1e-9) flags.push('ground twist over tolerance');
        }
        // Lowest module edge over the ground at the posts' chainages: south the front edge, east-west both eaves.
        const k = R.railDepthM - T.rise * (T.eastWest ? R.pivot : lines[0].f);
        const clear = f => Math.min(...s.map(v => fit.a + fit.b * v + k - gq(...at(f, v))));
        if (Math.min(clear(0), T.eastWest ? clear(1) : Infinity) < R.lowEdgeClearM - 1e-9) flags.push('lowest module edge under clearance');
      }
      if (missing > m0) { flags.push('ground not measured under some posts'); unmeasured++; }
      meta.push({ T, lines, base, twist, flags });
    }
    const plans = new Map([...groups].map(([len, rows]) => [len, planPiles({ rows, groundAt: gs, system: tracker ? 'tracker' : 'fixed', tableLength: len, tableGap: 0,
      pileSpacing: sp, embedMin: R.embedM, embedToReveal: R.embedToReveal, gradingWidth: R.gradingWidthM, revealAdjust: R.revealAdjustM, twistTolDeg: Infinity, limits: { along } })]));
    for (const { T, lines, base, twist, flags } of meta) out.push(tableResult(T, lines, lines.map((_, i) => plans.get(T.length).rows[base + i]), twist, flags, R, tracker));
    yield { phase: 'piles', tables: out.length };
  }
  return { tables: out, unmeasured, rules: R, system: tracker ? 'tracker' : 'fixed' };
}

// Piles kept compact: STRIDE numbers each [e, n, ground, top, bottom (ground or finished, the lower), length, embedment,
// reveal before grading, finished reveal] and a flag byte (1 reveal high, 2 reveal low, 4 outside the head adjustment,
// 8 lengthened past the soil embedment by the lateral-load rule (embedToReveal), 16 stands more than revealWarnAboveM over its design height, 32 over the hard
// maximum revealFailM).
export const STRIDE = 9;
function tableResult(T, lines, lr, twist, extra, R, tracker) {
  const piles = lr.flatMap(r => r.tables[0]?.piles || []), tb = lr.map(r => r.tables[0]).filter(Boolean);
  const flags = new Set([...tb.flatMap(t => t.flags), ...extra]);
  if (tracker && tb.some(t => !t.feasible)) flags.add('tracker cannot follow without grading');
  // Module surface at the table ends from a line's top: top + rails + rise x (fraction up the face - the line's).
  const surf = (i, ff) => { const t = tb[i], k = R.railDepthM + T.rise * (ff - (T.eastWest ? R.pivot : lines[i].f));
    return t ? [t.topLevelStart + k, t.topLevelEnd + k] : [NaN, NaN]; };
  const last = lines.length - 1, tube = tb[0] ? [tb[0].topLevelStart + R.bearingDropM, tb[0].topLevelEnd + R.bearingDropM] : [NaN, NaN];
  const edges = tracker ? [tube, tube, tube] : T.eastWest ? [surf(0, 0), surf(0, 1).map((z, j) => (z + surf(1, 1)[j]) / 2), surf(1, 0)]
    : [surf(0, 0), surf(0, 0.5).map((z, j) => (z + surf(last, 0.5)[j]) / 2), surf(last, 1)];
  const pa = new Float64Array(piles.length * STRIDE), pf = new Uint8Array(piles.length);
  let cut = 0, fill = 0, depth = 0, maxCut = 0, maxFill = 0;
  piles.forEach((p, i) => {
    pa.set([p.x, p.y, p.ground, p.top, Math.min(p.ground, p.finishedGround), p.length, p.embed, p.reveal, p.finishedReveal], i * STRIDE);
    const hf = heightFlags(p.finishedReveal, p.reveal - p.adjust, R); // design height: the post's nominal reveal
    pf[i] = (p.flags.includes('reveal-high') ? 1 : 0) | (p.flags.includes('reveal-low') ? 2 : 0) | (p.outsideAdjust ? 4 : 0)
      | (p.embed > R.embedM + 1e-9 ? 8 : 0) | (hf.high ? 16 : 0) | (hf.overMax ? 32 : 0);
    depth = Math.max(depth, p.cut, p.fill); maxCut = Math.max(maxCut, p.cut); maxFill = Math.max(maxFill, p.fill);
  });
  for (const t of tb) { cut += t.cutM3; fill += t.fillM3; }
  const has = f => flags.has(f);
  return { T, flags: [...flags], twistDeg: twist, twisted: has('ground twist over tolerance'), cannotFollow: has('tracker cannot follow without grading'),
    lowEdge: has('lowest module edge under clearance'), unmeasured: has('ground not measured under some posts'), edges, pa, pf, n: piles.length,
    cutM3: cut, fillM3: fill, maxDepth: depth, grading: tb.some(t => !t.feasible), maxCut, maxFill };
}

/**
 * gradingSuggestions(tables, opts): the tables that need grading, as patches sorted by volume. A patch is a run of
 * neighbouring tables (same pile line, ends within mergeGapM) with the same action:
 *   'drop table'  the grading under it is deeper than dropOverM: leave the position empty;
 *   'raise table' lifting the table by its deepest cut leaves every other post at most the head adjustment above
 *                 the band (maxCut + maxFill <= revealAdjust): longer posts, no earthworks;
 *   'regrade'     cut and fill to the finished levels.
 */
export function gradingSuggestions(tables, { rules = PILE_RULES, key = t => t.T.key } = {}) {
  const G = rules.grading, out = [];
  const act = t => (t.maxDepth > G.dropOverM ? 'drop table'
    : t.maxCut + t.maxFill <= rules.revealAdjustM + 1e-9 ? 'raise table' : 'regrade');
  const flagged = tables.map((t, i) => ({ t, i })).filter(x => x.t.grading)
    .sort((a, b) => key(a.t)[0] - key(b.t)[0] || key(a.t)[1] - key(b.t)[1]);
  for (const { t, i } of flagged) {
    const a = act(t), k = key(t), p = out[out.length - 1];
    if (p && p.action === a && p.lane === k[0] && k[1] - p.end <= G.mergeGapM + 1e-9) {
      p.tables.push(i); p.cutM3 += t.cutM3; p.fillM3 += t.fillM3; p.maxDepth = Math.max(p.maxDepth, t.maxDepth); p.end = k[2];
      if (a === 'raise table') p.raiseM = Math.max(p.raiseM, t.maxCut);
    } else out.push({ action: a, tables: [i], cutM3: t.cutM3, fillM3: t.fillM3, maxDepth: t.maxDepth, lane: k[0], end: k[2],
      ...(a === 'raise table' ? { raiseM: t.maxCut } : {}) });
  }
  return out.map(({ lane, end, ...p }) => p).sort((a, b) => (b.cutM3 + b.fillM3) - (a.cutM3 + a.fillM3) || a.tables[0] - b.tables[0]);
}

/** Totals for readouts and the bill: counts, pile metres (embedment provisional), flags, suggestions. */
export function pileSummary(res, { mwp = 0, rules = res.rules || PILE_RULES } = {}) {
  const t = res.tables, sug = gradingSuggestions(t, { rules }), n = k => t.filter(x => x[k]).length;
  const acts = a => sug.filter(x => x.action === a).reduce((m, x) => m + x.tables.length, 0);
  const s = { system: res.system || 'fixed', tables: t.length, piles: t.reduce((m, x) => m + x.n, 0), totalPileLengthM: 0, embeddedM: 0,
    revealedM: 0, revealAdjust: 0, revealHigh: 0, revealLow: 0, embedBelowReveal: 0, twistTables: n('twisted'), cannotFollow: n('cannotFollow'),
    lowEdgeTables: n('lowEdge'), gradingTables: n('grading'), cutM3: 0, fillM3: 0, drop: acts('drop table'), raise: acts('raise table'),
    regrade: acts('regrade'), unmeasured: res.unmeasured, revealWarn: 0, revealFail: 0 };
  const tw = t.map(x => x.twistDeg).sort((a, b) => a - b);                // twist at table level
  s.twistP50Deg = tw.length ? tw[Math.floor((tw.length - 1) / 2)] : 0; s.twistMaxDeg = tw.length ? tw[tw.length - 1] : 0;
  const H = new Uint32Array(1501), HF = new Uint32Array(1501), bin = v => Math.max(0, Math.min(1500, Math.round((v + 5) * 100))); // 1 cm, -5..10 m
  for (const x of t) {
    for (let i = 0; i < x.n; i++) {
      const o = i * STRIDE, f = x.pf[i];
      s.totalPileLengthM += x.pa[o + 5]; s.embeddedM += x.pa[o + 6]; s.revealedM += x.pa[o + 8]; H[bin(x.pa[o + 7])]++; HF[bin(x.pa[o + 8])]++;
      if (f & 4) s.revealAdjust++;
      if (f & 8) s.embedBelowReveal++;
      if (f & 32) s.revealFail++; else if (f & 16) s.revealWarn++;
      if (f & 1) s.revealHigh++; else if (f & 2) s.revealLow++;
    }
    s.cutM3 += x.cutM3; s.fillM3 += x.fillM3;
  }
  const pct = h => [0, 50, 100].map(q => {                            // nearest rank, to the centimetre
    const want = Math.max(1, Math.ceil(q / 100 * s.piles)); let c = 0;
    for (let b = 0; b < h.length; b++) if ((c += h[b]) >= want) return b / 100 - 5;
    return NaN;
  });
  // revealP: the ground as found (before grading; may be negative where the ground stands above the post top);
  // finishedP: how far the posts stand out once graded, never below the band (user test H5).
  s.revealP = pct(H); s.finishedP = pct(HF);
  s.perMWp = mwp > 0 ? s.piles / mwp : null;
  s.proofTests = Math.ceil(s.piles * (rules.proofTestPct ?? 1) / 100); // production proof tests (L3), spread evenly
  s.suggestions = sug.slice(0, 20);
  s.label = PILES_LABEL;
  return s;
}

/** Bill of quantities items (boq.mjs 'piles'): count and total embedded length, provisional. */
export function pileBoqItems(id, s, pileType = 'plant') {
  if (!s || !s.piles) return [];
  return [{ id, kind: 'piles', pileType, results: { count: s.piles, totalEmbedmentM: s.embeddedM, totalPileLengthM: s.totalPileLengthM } }];
}

/** The tables of a plant layout (plant-layout.mjs result) as planTables inputs, in national-grid e, n. */
export function layoutTables(r) {
  const F = r.frame, T = r.table, P = r.params, t = r.tables, out = [];
  for (let q = 0; q < t.length; q += 6) {
    const ua = t[q], va = t[q + 1], L = r.tableLen?.[q / 6] ?? T.lenU;   // a half table closing a row end is shorter
    out.push({ length: L, depth: T.depth, rise: T.rise, lowEdgeM: P.lowEdgeM, eastWest: !T.south && !T.tracker, key: [va, ua, ua + L],
      lineAt: f => [F.en(ua, va + f * T.depth), F.en(ua + L, va + f * T.depth)] });
  }
  return out;
}

/** Piles for a laid-out plant, as a generator (sliced between frames); returns { tables, summary, posts, system }. */
export function* pilesForLayout(r, groundAt, { posts = 2, rules, soil, mwp = r.built?.mwp ?? 0 } = {}) {
  const system = r.table.tracker ? 'tracker' : 'fixed', R = withSoil({ ...rulesFor(system), ...(rules || {}) }, soil);
  const res = yield* planTables(layoutTables(r), { groundAt, system, posts, rules: R, along: r.frame.swap ? 'ns' : 'ew' });
  yield { phase: 'piles', tables: res.tables.length };                   // the summary in a slice of its own (PERF.md 3)
  return { ...res, posts: r.table.south ? posts : r.table.tracker ? 1 : 2, summary: pileSummary(res, { mwp, rules: R }) };
}

Plant Template

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

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

Evidence
  • line-jaccard 0.9908 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/plant-template.mjs:1-265 d8f96697e2b0cd2976493b41be0125781ede2d00
  • sha256 1a6ad46949f05927814da2fdfcaa1d0016fc42ce8d316c797b7a833d59df15a3
  • target sha256 a31ba3353e3834b40f339e6ec8f6bdbc857cf6971b66e791e1c8c6fed05a6bde
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

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

What it does
It calculates transformers, cables, solar and 33kV. Defines 17 functions or classes, including up, r3, autoPocKv, moduleColdVoc, modulesPerString.
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, cables, solar, 33kV, 400kV, 1500V.
Inputs & outputs
Voltage levels named: 400kV, 33kV, 1500V.
Downstream impact
Used directly by 4 files: MV Network (globalgrid2050); Block MV (globalgrid2050); Cmd Model (globalgrid2050); Plant Layout (globalgrid2050).
What it achieves
It sizes feeder (`sizeFeeder`) and is built from the auto poc kV helper (`autoPocKv`) and the module cold voc helper (`moduleColdVoc`). A generic, parameterised solar plant block diagram, sized from engineering rules. Its code works with 33 kV, 10 MVA and 5000 kVA.
Why it matters
Imported by 4 files, including MV Network, Block MV and Cmd Model.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Cable Rating (import), Module Catalogue (import)
Used by
imported by MV Network (import), imported by Block MV (import), imported by Cmd Model (import), imported by Plant Layout (import)
Produces
STATION_MVA, CENTRAL_MVA, INVERTER_CLASSES, GRID_MVA, TEMPLATE_DEFAULTS, autoPocKv, moduleColdVoc, modulesPerString, faultMinArea, plantTemplate, gridChoice, pack
Defines here
up, r3, autoPocKv, moduleColdVoc, modulesPerString, faultMinArea, plantTemplate, node, link, check, gridChoice, maxLoad, pack, L, sizeFeeder, drop, layoutDiagram
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-template.mjs:1-267 · blob 28a4660e743d1d196c97c66dfc40ea8521101b6f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 plant-template.mjs at v12 commit 3adcee9 (file last changed 48f2a65). 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-template.mjs: a generic, parameterised solar plant block diagram, sized from engineering rules.
//
// Give it a target export in MW and any of the choices below; it works out the string length, strings per
// inverter, stations, 33 kV feeders (radial chains, or rings with a normally-open point), MV board sections with
// normally-open ties, grid transformers and the connection, then sizes each feeder cable segment from the load it
// carries (cable-rating.mjs, IEC 60287 method) and checks every level against its limit. Counts come out of the
// arithmetic, so no size reproduces any real plant. Illustrative: a real design is set by studies.
//
// Ranges (general practice; the defaults sit inside them):
//   string length: cold open-circuit voltage stays under the 1500 V system limit; 12 strings per inverter up to the MPPT
//   cap (MPPT inputs x strings per input, 12 x 2 = 24 by default; a given stringsMax overrides it)
//   string inverters 100-400 kVA; 8-30 per station, a smaller station takes any remainder
//   central inverters (inverterClass 'central'): 500-5000 kVA units, 1-4 per MV skid or container station; strings
//   gathered in DC combiner boxes (8-32 strings a box), so no MPPT cap on strings per inverter; skid transformers in
//   the 0.8-10 MVA steps. Generic class, illustrative: the central-inverter plants of the UK study run 1-3 MVA units
//   station transformers 2.5-10 MVA, ONAN, two LV windings (Dy11y11), one auxiliary transformer each
//   33 kV feeder 20-30 MVA and 2-4 stations; 2-6 solar feeders per board section plus spares
//   grid transformers 1.0-1.2 x the export in total (30-240 MVA steps); connection at 132, 275 or 400 kV (33 kV up to about 30 MW)
//   MV voltage drop 0.5 % or less; conductor short-circuit by the adiabatic rule (IEC 60949, k = 94 for Al XLPE)
// Pure: imports only the cable rating and the module catalogue's cold-Voc rule.

import { sizeFor, dropPercent, rating, SIZES } from './cable-rating.mjs';
import { coldVocOf } from './module-catalogue.mjs';

export const STATION_MVA = Object.freeze([2.5, 3.15, 4, 5, 6.3, 8, 10]);
export const CENTRAL_MVA = Object.freeze([0.8, 1, 1.25, 1.6, 2, 2.5, 3.15, 4, 5, 6.3, 8, 10]);
export const INVERTER_CLASSES = Object.freeze(['string', 'central']);
export const GRID_MVA = Object.freeze([20, 30, 40, 45, 60, 75, 90, 100, 120, 150, 180, 200, 240]);

export const TEMPLATE_DEFAULTS = Object.freeze({
  // The module: the default class A of data/modules.json (nominal 660 W, highest-bin Voc 46.1 V, β Voc -0.25 %/K), the same
  // class the solar block uses; a page passes the selected class or the typed values (tests/plant-network checks they agree).
  dcAcRatio: 1.25, moduleWp: 660, moduleVoc: 46.1, vocCoeffPerK: -0.0025, minCellC: -10, systemV: 1500,
  inverterClass: 'string', inverterKVA: 300, invertersPerStation: 20, stringsPerCombiner: 20, stringsMin: 12, stringsMax: null, mppts: 12, stringsPerMppt: 2, powerFactor: 0.95,
  feederLimitMVA: 25, stationsPerFeederMax: 4, feedersPerBoardMax: 6, spareWays: 1, topology: 'radial',
  gridFactor: 1.1, gridUnits: null, gridBank: 'three-phase', pocKv: null, harmonicFilter: false,
  headLengthM: 1500, linkLengthM: 300, vdropLimitPct: 0.5, maxUtilisation: 0.9, faultKA: 20, faultS: 1, soilKmW: 1.2
});

const up = (steps, v) => steps.find(s => s >= v - 1e-9) ?? null;
const r3 = v => (v == null ? v : Math.round(v * 1000) / 1000);

export const autoPocKv = mw => (mw <= 30 ? 33 : mw <= 150 ? 132 : 400);

/** The sizing cold Voc of one module: the stricter of the coldest cell and Voc x 1.15 (module-catalogue.mjs coldVocOf). */
export const moduleColdVoc = p => coldVocOf({ voc: p.moduleVoc, coeffPctPerK: p.vocCoeffPerK * 100, tC: p.minCellC });
// Modules per string: the typed length, else the most whose sizing cold Voc stays under the limit.
export function modulesPerString(p) {
  if (p.modulesPerString > 0) return p.modulesPerString; // typed (table 2P30); the string check below says if it is over
  return Math.floor(p.systemV / moduleColdVoc(p).v + 1e-9);
}

// Smallest conductor that survives the fault: A >= I * sqrt(t) / k, k = 94 for aluminium XLPE 90 to 250 C.
export const faultMinArea = (kA, s) => SIZES.find(a => a >= kA * 1000 * Math.sqrt(s) / 94) ?? SIZES.at(-1);

/**
 * plantTemplate({ targetMW, ...choices }) -> { params, counts, ratings, nodes, links, feeders, checks, ok, note }
 * nodes: { id, kind, label, rating } ; links: { from, to, kind, kv, mva, areaMm2?, lengthM?, normallyOpen? }
 */
export function plantTemplate(opts = {}) {
  const p = { ...TEMPLATE_DEFAULTS, ...opts }, mw = Number(p.targetMW);
  if (!(mw > 0 && mw <= 5000)) throw new Error('plant template: targetMW must be between 0 and 5000');
  const central = p.inverterClass === 'central';
  if (!INVERTER_CLASSES.includes(p.inverterClass)) throw new Error(`plant template: inverterClass must be ${INVERTER_CLASSES.join(' or ')}`);
  if (central) {
    if (!(p.inverterKVA >= 500 && p.inverterKVA <= 5000)) throw new Error('plant template: a central inverter is 500 to 5000 kVA');
    if (!(p.invertersPerStation >= 1 && p.invertersPerStation <= 4)) throw new Error('plant template: 1 to 4 central inverters per station');
    if (!(p.stringsPerCombiner >= 8 && p.stringsPerCombiner <= 32)) throw new Error('plant template: stringsPerCombiner must be 8 to 32');
  } else {
    if (!(p.inverterKVA >= 100 && p.inverterKVA <= 400)) throw new Error('plant template: inverterKVA must be 100 to 400');
    if (!(p.invertersPerStation >= 8 && p.invertersPerStation <= 30)) throw new Error('plant template: invertersPerStation must be 8 to 30');
  }
  const kvMv = 33, kvPoc = p.pocKv || autoPocKv(mw);
  const mps = modulesPerString(p), stringKWp = mps * p.moduleWp / 1000;
  // The MPPT cap: inputs x strings per input, unless stringsMax is given; central inverters take strings through combiner boxes.
  const sMax = p.stringsMax ?? (central ? Infinity : p.mppts * p.stringsPerMppt);
  const spi = Math.min(sMax, Math.max(p.stringsMin, Math.round(p.inverterKVA * p.dcAcRatio / stringKWp)));
  const inverters = Math.ceil(mw / p.powerFactor * 1000 / p.inverterKVA);

  // Stations: full ones of the chosen size; a smaller station takes the remainder.
  const full = Math.floor(inverters / p.invertersPerStation), rest = inverters % p.invertersPerStation;
  const stationInv = [...Array(full).fill(p.invertersPerStation), ...(rest ? [rest] : [])];
  const stations = stationInv.map((n, i) => ({ id: `S${i + 1}`, inverters: n, kva: n * p.inverterKVA,
    mva: up(central ? CENTRAL_MVA : STATION_MVA, n * p.inverterKVA / 1000) ?? n * p.inverterKVA / 1000 }));
  const combinersPerInverter = central ? Math.ceil(spi / p.stringsPerCombiner) : 0;

  // Feeders: as many stations as both the feeder limit and the cap allow.
  const stMax = Math.max(...stations.map(s => s.kva / 1000));
  const perFeeder = Math.max(1, Math.min(p.stationsPerFeederMax, Math.floor(p.feederLimitMVA / stMax)));
  const nFeeders = Math.ceil(stations.length / perFeeder);
  const cableOpts = { soilKmW: p.soilKmW, kv: kvMv };
  const minArea = faultMinArea(p.faultKA, p.faultS);
  const feeders = [];
  for (let f = 0, k = 0; f < nFeeders; f++) {
    const n = Math.floor(stations.length / nFeeders) + (f < stations.length % nFeeders ? 1 : 0);
    const chain = stations.slice(k, k + n); k += n;
    feeders.push(sizeFeeder(chain, p, cableOpts, minArea));
  }

  // Grid transformers, then feeders packed onto them by load, then board sections of at most N solar ways each.
  const gridTotal = mw * p.gridFactor;
  const grid = kvPoc === kvMv ? { units: 0, mva: null, smallest: false } : gridChoice(mw, gridTotal, p.gridUnits, feeders);
  const { units: gridUnits, mva: gridMVA } = grid;
  const txOf = pack(feeders, Math.max(1, gridUnits));
  const sections = [];                                     // [{ tx, feeders: [] }]
  for (let t = 0; t < Math.max(1, gridUnits); t++) {
    const mine = feeders.filter((f, i) => txOf[i] === t), n = Math.max(1, Math.ceil(mine.length / p.feedersPerBoardMax));
    for (let k = 0; k < n; k++) sections.push({ tx: t, feeders: mine.filter((f, j) => j % n === k) });
  }
  const boards = sections.length;
  const nodes = [], links = [];
  const node = (id, kind, label, rating = {}) => nodes.push({ id, kind, label, rating });
  const link = (from, to, kind, kv, mva, extra = {}) => links.push({ from, to, kind, kv, mva: r3(mva), ...extra });
  node('POC', 'poc', `Connection ${kvPoc} kV`, { kv: kvPoc, exportMW: mw });
  if (p.harmonicFilter && gridUnits) { node('HF', 'harmonic-filter', 'Harmonic filter (optional)', { kv: kvPoc }); link('POC', 'HF', 'hv-bus', kvPoc, 0); }
  for (let g = 0; g < gridUnits; g++) {
    node(`GT${g + 1}`, 'grid-transformer', `Grid transformer ${g + 1}: ${gridMVA} MVA ${kvPoc}/${kvMv} kV, ${p.gridBank}`,
      { mva: gridMVA, kv: [kvPoc, kvMv], bank: p.gridBank });
    link('POC', `GT${g + 1}`, 'hv-cable', kvPoc, gridMVA);
  }
  const boardWays = sections.map(x => x.feeders.length), txLoad = new Array(Math.max(1, gridUnits)).fill(0);
  sections.forEach((sec, b) => {
    node(`MVB${b + 1}`, 'switchboard', `${kvMv} kV board section ${b + 1}`, { kv: kvMv, spareWays: p.spareWays });
    if (gridUnits) link(`GT${sec.tx + 1}`, `MVB${b + 1}`, 'mv-bus', kvMv, gridMVA);
    else link('POC', `MVB${b + 1}`, 'mv-cable', kvMv, mw / p.powerFactor);
    if (b) link(`MVB${b}`, `MVB${b + 1}`, 'bus-tie', kvMv, 0, { normallyOpen: true });
    for (const f of sec.feeders) { f.board = `MVB${b + 1}`; txLoad[sec.tx] += f.loadMVA; }
  });
  feeders.forEach(f => {
    const bid = f.board;
    f.chain.forEach((s, k) => {
      node(s.id, 'station', `Station ${s.id.slice(1)}: ${s.inverters} x ${p.inverterKVA} kVA${central ? ' central' : ''}, ${s.mva} MVA`,
        { mva: s.mva, kva: s.kva, inverters: s.inverters, strings: s.inverters * spi, modulesPerString: mps, inverterClass: p.inverterClass,
          ...(central ? { combiners: s.inverters * combinersPerInverter } : {}) });
      node(`R${s.id.slice(1)}`, 'rmu', `Ring main unit ${s.id.slice(1)}`, { kv: kvMv, amps: 630 });
      node(`A${s.id.slice(1)}`, 'aux', `Auxiliary transformer ${s.id.slice(1)}`, {});
      link(`R${s.id.slice(1)}`, s.id, 'station-tee', kvMv, s.mva); link(s.id, `A${s.id.slice(1)}`, 'aux', 0.4, 0);
      const seg = f.segments[k];
      link(k ? `R${f.chain[k - 1].id.slice(1)}` : bid, `R${s.id.slice(1)}`, 'feeder-cable', kvMv, seg.loadMVA,
        { areaMm2: seg.area, lengthM: seg.lengthM });
    });
  });
  if (p.topology === 'ring') for (let i = 0; i + 1 < feeders.length; i += 2) {
    const a = feeders[i].chain.at(-1).id.slice(1), b = feeders[i + 1].chain.at(-1).id.slice(1);
    link(`R${a}`, `R${b}`, 'feeder-cable', kvMv, 0, { normallyOpen: true, areaMm2: feeders[i].segments.at(-1).area, lengthM: p.linkLengthM });
  }

  const check = (name, value, max, min = -Infinity) => ({ name, value: r3(value), min, max, ok: value <= max + 1e-9 && value >= min - 1e-9 });
  const checks = [
    // The string's cold Voc against the system voltage; fewer modules in series is never a fault here (no minimum).
    check(`string cold Voc V (${moduleColdVoc(p).rule}, ${mps} in series)`, mps * moduleColdVoc(p).v, p.systemV),
    central ? check('strings per DC combiner box', Math.ceil(spi / combinersPerInverter), p.stringsPerCombiner, 1)
      : check('strings per inverter (MPPT cap)', spi, sMax, Math.min(p.stringsMin, sMax)),
    check('DC/AC ratio', spi * stringKWp / p.inverterKVA, 1.4, 1.1),
    check('station load / transformer', Math.max(...stations.map(s => s.kva / 1000 / s.mva)), 1),
    check('feeder load MVA', Math.max(...feeders.map(f => f.loadMVA)), p.feederLimitMVA),
    check('cable utilisation (worst segment)', Math.max(...feeders.flatMap(f => f.segments.map(s => s.utilisation))), p.maxUtilisation),
    check('MV voltage drop % (worst feeder)', Math.max(...feeders.map(f => f.dropPct)), p.vdropLimitPct),
    check('solar feeders per board section', Math.max(...boardWays), p.feedersPerBoardMax),
    // 1.0-1.2 x export; above that only when no standard step fits (grid.smallest), and then it is said so.
    check(grid.smallest ? 'grid transformers / export (smallest standard size that carries the load)' : 'grid transformers / export',
      gridUnits ? gridUnits * gridMVA / mw : 1, grid.smallest ? Infinity : 1.2 + 1e-6, 1.0),
    check('load on each grid transformer', gridUnits ? Math.max(...txLoad) / gridMVA : 0, 1)
  ];
  const counts = { modulesPerString: mps, stringsPerInverter: spi, inverters, strings: inverters * spi, modules: inverters * spi * mps,
    stations: stations.length, combiners: inverters * combinersPerInverter, feeders: nFeeders, stationsPerFeederMax: perFeeder, boardSections: boards, gridTransformers: gridUnits };
  const ratings = { collectorKv: kvMv, pocKv: kvPoc, inverterClass: p.inverterClass, inverterKVA: p.inverterKVA, stationMVA: [...new Set(stations.map(s => s.mva))],
    gridMVA, feederLimitMVA: p.feederLimitMVA, faultMinAreaMm2: minArea, acMVA: r3(inverters * p.inverterKVA / 1000),
    dcMWp: r3(counts.strings * stringKWp / 1000), cableSizesMm2: [...new Set(feeders.flatMap(f => f.segments.map(s => s.area)))].sort((a, b) => a - b) };
  return { params: p, counts, ratings, nodes, links, feeders, checks, ok: checks.every(c => c.ok),
    note: 'Generic template from rating rules; illustrative, not a design for any site. Segment lengths are placeholders until set from a layout.' };
}

// Grid transformers: the least total standard MVA that carries the feeders as packed (fewer units on a tie).
// Within 1.0-1.2 x the export where a standard step allows it; below about 40 MW no step does, and the choice is
// flagged as the smallest standard size that carries the load (smallest: true), not forced up or down.
export function gridChoice(mw, total, fixedUnits = null, feeders = []) {
  const loadTotal = feeders.reduce((s, f) => s + f.loadMVA, 0) || total;
  const first = fixedUnits || Math.max(1, Math.ceil(loadTotal / GRID_MVA.at(-1)));
  const maxLoad = n => { const t = pack(feeders, n), load = new Array(n).fill(0);
    feeders.forEach((f, i) => { load[t[i]] += f.loadMVA; }); return feeders.length ? Math.max(...load) : loadTotal / n; };
  let best = null;
  for (let n = first; n <= (fixedUnits || first + 8); n++) {
    const mva = up(GRID_MVA, maxLoad(n));
    if (mva == null) continue;
    if (!best || n * mva < best.units * best.mva - 1e-9) best = { units: n, mva };
  }
  if (!best) best = { units: first, mva: GRID_MVA.at(-1) };
  best.smallest = best.units * best.mva > 1.2 * mw + 1e-9;
  return best;
}

// Feeders onto n transformers: largest first onto the least-loaded one, then single moves and pairwise swaps
// while they lower the heaviest transformer's load. Returns the transformer index per feeder.
export function pack(feeders, n) {
  const load = new Array(n).fill(0), out = new Array(feeders.length);
  feeders.map((f, i) => [f.loadMVA, i]).sort((a, b) => b[0] - a[0]).forEach(([l, i]) => {
    const t = load.indexOf(Math.min(...load)); out[i] = t; load[t] += l;
  });
  const L = i => feeders[i].loadMVA;
  for (let pass = 0, better = true; better && pass < 200; pass++) {
    better = false;
    const hi = load.indexOf(Math.max(...load));
    for (let i = 0; i < out.length && !better; i++) {
      if (out[i] !== hi) continue;
      for (let t = 0; t < n && !better; t++) {
        if (t === hi) continue;
        if (Math.max(load[hi] - L(i), load[t] + L(i)) < load[hi] - 1e-9) {        // move i to t
          load[hi] -= L(i); load[t] += L(i); out[i] = t; better = true; break;
        }
        for (let j = 0; j < out.length; j++) {                                    // swap i with j on t
          if (out[j] !== t || L(j) >= L(i)) continue;
          const d = L(i) - L(j);
          if (Math.max(load[hi] - d, load[t] + d) < load[hi] - 1e-9) {
            load[hi] -= d; load[t] += d; out[i] = t; out[j] = hi; better = true; break;
          }
        }
      }
    }
  }
  return out;
}

// Size each segment of a radial chain from the load it carries, then upsize from the head until the drop is met.
function sizeFeeder(chain, p, cableOpts, minArea) {
  const segments = chain.map((s, k) => {
    const loadMVA = chain.slice(k).reduce((t, x) => t + x.kva / 1000, 0);
    const pick = sizeFor(loadMVA / p.maxUtilisation, { ...cableOpts, minArea }) || { area: SIZES.at(-1) };
    return { loadMVA, area: pick.area, lengthM: k ? p.linkLengthM : p.headLengthM };
  });
  const drop = () => segments.reduce((t, s) => t + dropPercent(s.area, s.lengthM, s.loadMVA, { ...cableOpts, pf: p.powerFactor }), 0);
  for (let guard = 0; drop() > p.vdropLimitPct && guard < 40; guard++) {
    const s = segments.find(x => x.area < SIZES.at(-1));
    if (!s) break;
    // Upsize the segment that saves most drop per step: the most loaded, longest one still below the top size.
    const best = segments.filter(x => x.area < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
    best.area = SIZES[SIZES.indexOf(best.area) + 1];
  }
  for (const s of segments) s.utilisation = s.loadMVA * 1e6 / (Math.sqrt(3) * cableOpts.kv * 1000) / rating(s.area, cableOpts).amps;
  return { chain, segments, loadMVA: segments[0].loadMVA, dropPct: drop() };
}

/**
 * layoutDiagram(d) -> nodes with schematic positions { x, y } in panel units: connection at the top, grid
 * transformers, board sections, then each feeder as a column of ring main units with their stations beside them.
 */
export function layoutDiagram(d) {
  const pos = new Map(), boards = d.nodes.filter(n => n.kind === 'switchboard');
  const byBoard = boards.map(b => d.feeders.filter(f => f.board === b.id));
  let x = 0;
  boards.forEach((b, i) => {
    const w = Math.max(1, byBoard[i].length);
    pos.set(b.id, { x: x + (w - 1) / 2, y: 2 });
    byBoard[i].forEach((f, j) => f.chain.forEach((s, k) => {
      const n = s.id.slice(1);
      pos.set(`R${n}`, { x: x + j, y: 3 + k }); pos.set(s.id, { x: x + j + 0.4, y: 3 + k }); pos.set(`A${n}`, { x: x + j + 0.4, y: 3.4 + k });
    }));
    x += w + 1;
  });
  const gts = d.nodes.filter(n => n.kind === 'grid-transformer');
  gts.forEach((g, i) => { const b = pos.get(`MVB${i + 1}`) || { x: i * 2 }; pos.set(g.id, { x: b.x, y: 1 }); });
  const mid = (Math.max(0, ...[...pos.values()].map(v => v.x))) / 2;
  pos.set('POC', { x: mid, y: 0 }); pos.set('HF', { x: mid + 1, y: 0 });
  return d.nodes.map(n => ({ ...n, ...(pos.get(n.id) || { x: 0, y: 0 }) }));
}

Renewable Energy Planning Database (REPD) Grammar

A JavaScript module in the engine folder of GlobalGrid2050 that works with solar, the REPD register and battery storage (BESS). It parses REPD (`parseRepd`) and filters text (`filterText`).

energy-dataglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/repd-grammar.mjs · lines 1–72 of 72 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern filterText (shared by 2 files)

What it does
It calculates solar, the REPD register and battery storage (BESS). Defines refuse, parseRepd, filterText.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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: solar, the REPD register, battery storage (BESS).
Downstream impact
Used directly by 1 file: Cmd Grammar (globalgrid2050).
What it achieves
The typed words for flying between solar and battery projects on the public register (REPD). Its code works with 50 MW.
Why it matters
Imported by Cmd Grammar.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar (import)
Produces
REPD_COMMANDS, parseRepd, filterText
Defines here
refuse, parseRepd, filterText
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/repd-grammar.mjs:1-72 · blob f5db500587b9846076a33e2f5055bbc88bef0100 · 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: unreached_review
// COPIED UNCHANGED from world/v12 repd-grammar.mjs at v12 commit 3adcee9 (file last changed 954e27a). 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.
// repd-grammar.mjs: the typed words for flying between solar and battery projects on the public register (REPD).
// Pure: no imports, no DOM. cmd-grammar.mjs asks parseRepd(line) first; null means "not a REPD line" and the usual
// grammar carries on (so "go block 3" and "go Canterbury" are untouched).
//   go solar                 the nearest ground-mounted solar project, any status
//   go solar operational     ... operational  (also: construction, consented, planning, planned, current, other, all)
//   go solar planned         in planning or consented
//   go solar farm            the nearest operational solar farm (owner direction section 10)
//   go bess · go bess 50     the nearest battery project, of at least 50 MW
//   go roof                  rooftop solar on the register
//   next solar · previous solar · next bess      the next or previous one by distance, same filter as last typed
//   go repd 1234             a project by its REPD reference

// A second 'go' entry (help and search list both; parse takes the REPD words first) and the new verb 'next'.
export const REPD_COMMANDS = Object.freeze([
  { verb: 'go', usage: 'go solar  ·  go solar operational  ·  go solar planned  ·  go bess  ·  go bess 50  ·  go repd 1234',
    words: 'fly repd register solar farm battery bess storage operational planned consented planning nearest survey' },
  { verb: 'next', usage: 'next solar  ·  next bess  ·  previous solar', words: 'fly repd register next previous nearest solar battery bess' }
]);

const TECH = { solar: 'solar', pv: 'solar', bess: 'bess', battery: 'bess', batteries: 'bess', storage: 'bess', roof: 'roof', rooftop: 'roof' };
const CLS = { operational: 'operational', existing: 'operational', built: 'operational', live: 'operational',
  construction: 'construction', building: 'construction', consented: 'consented', approved: 'consented',
  planning: 'planning', submitted: 'planning', planned: 'planned', pipeline: 'planned', proposed: 'planned',
  current: 'current', other: 'other', refused: 'other', withdrawn: 'other', abandoned: 'other', all: 'all', any: 'all' };
const NOISE = new Set(['farm', 'farms', 'park', 'parks', 'site', 'sites', 'project', 'projects', 'the', 'nearest', 'a', 'mw', 'at', 'least', 'over', 'min']);
const LEAD = /^\s*(go\s+to|goto|fly\s+to|fly|go|next|previous|prev|back)\s+/i;

const refuse = (why, line) => ({ ok: false, why, line: String(line).trim() });

/** parseRepd(line) -> null | { ok: true, verb, act: 'repd', set: {}, arg: { op, tech, cls, minMw, ref }, line } | { ok: false, why, line } */
export function parseRepd(line) {
  const text = String(line || '').toLowerCase().replace(/#.*$/, '').trim();
  const m = text.match(LEAD);
  if (!m) return null;
  const lead = m[1].replace(/\s+/g, ' ');
  const op = lead === 'next' ? 'next' : ['previous', 'prev', 'back'].includes(lead) ? 'previous' : 'go';
  const ws = text.slice(m[0].length).replace(/(\d)\s*mw\b/g, '$1').replace(/>=?/g, ' ').split(/\s+/).filter(Boolean);
  if (!ws.length) return null;
  const out = { ok: true, verb: op === 'go' ? 'go' : 'next', act: 'repd', set: {}, line: String(line).trim(), arg: { op, tech: null, cls: null, minMw: 0, ref: null } };
  if (ws[0] === 'repd') {
    if (op !== 'go') return refuse(`${op} takes solar or bess, such as ${op} solar`, line);
    if (ws.length !== 2 || !/^\d{1,6}$/.test(ws[1])) return refuse('go repd takes one REPD reference number, such as go repd 1234', line);
    out.arg.op = 'ref'; out.arg.ref = ws[1];
    return out;
  }
  if (!TECH[ws[0]]) return op === 'go' ? null : refuse(`${op} takes solar, bess or roof, such as ${op} solar`, line);
  out.arg.tech = TECH[ws[0]];
  const nums = [];
  for (const w of ws.slice(1)) {
    if (/^\d+(\.\d+)?$/.test(w)) { nums.push(Number(w)); continue; }
    if (CLS[w]) { if (out.arg.cls && out.arg.cls !== CLS[w]) return refuse(`one status at a time: you typed ${out.arg.cls} and ${CLS[w]}`, line); out.arg.cls = CLS[w]; continue; }
    if (NOISE.has(w)) { if ((w === 'farm' || w === 'farms') && !out.arg.cls && out.arg.tech === 'solar') out.arg.cls = 'operational'; continue; }
    return refuse(`${op === 'go' ? 'go' : op} ${ws[0]} does not read "${w}"; it takes a status (operational, construction, consented, planning, planned, `
      + `current, other, all) and a smallest size in MW, such as go ${ws[0]} planned 50`, line);
  }
  if (nums.length > 1) return refuse(`one size at a time (the smallest MW); you typed ${nums.join(' and ')}`, line);
  if (nums.length) {
    if (!(nums[0] >= 0 && nums[0] <= 5000)) return refuse(`the smallest size is in MW, from 0 to 5000; you typed ${nums[0]}`, line);
    out.arg.minMw = nums[0];
  }
  if (out.arg.cls === 'all') out.arg.cls = null;
  return out;
}

/** The filter a line names, as words for the echo: "solar, operational, at least 50 MW". */
export function filterText({ tech, cls, minMw }) {
  const t = tech === 'bess' ? 'battery (BESS)' : tech === 'roof' ? 'rooftop solar' : 'solar';
  return [t, cls ? (cls === 'planned' ? 'planned (in planning or consented)' : cls === 'current' ? 'current (operational or being built)' : cls) : 'any status',
    minMw ? `at least ${minMw} MW` : ''].filter(Boolean).join(', ');
}

Site Checks

A JavaScript module in the engine folder of GlobalGrid2050 that works with survey check (`surveyCheck`) and survey note (`surveyNote`).

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

Evidence
  • line-jaccard 0.9487 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/site-checks.mjs:1-48 cba873b022cda27172f65ddae61250e7e84734c6
  • sha256 21efb59a643e96214effa5155c2d682b249cacf50e15a51179e105176961b065
  • target sha256 f0976c86b744c016f1ddd6909c4e530fd8433e48368b4fa5599cb1566a7ea752
  • 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/site-checks.mjs · lines 1–50 of 50 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern sourceConflict (shared by 3 files)

What it does
It calculates its inputs. Defines dayOf, surveyCheck, surveyNote, sourceConflict.
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 1 file: Plant Layout (globalgrid2050).
What it achieves
It is built from the day of helper (`dayOf`), the survey check helper (`surveyCheck`) and the survey note helper (`surveyNote`). A date field as a sortable day number (ms since 1970); '2020', '2020-11' and '' are all read.
Why it matters
Imported by Plant Layout.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Plant Layout (import)
Produces
dayOf, surveyCheck, surveyNote, sourceConflict
Defines here
dayOf, surveyCheck, surveyNote, sourceConflict
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/site-checks.mjs:1-50 · blob 5043d3e2b6cbc2c6591927312dc2301c3f388c82 · 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 site-checks.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.
// site-checks.mjs: two honesty checks on the data a plant is drawn from, raised as notes, never as refusals.
//
// SURVEY DATE  A ground survey (LiDAR) flown before a plant was planned or built shows the land, not the plant: its
//   surface has no rows, so it can never confirm what the layout draws. An open-data study of large operational UK
//   solar farms found this at most of them (the public 1 m survey predated the build). When the site's data gives the
//   survey date and a planning or commissioning date, a survey older than either is said: "Ground survey predates
//   this layout". Dates come from a data field (a site record or the terrain index); none given, nothing is said.
// CONFLICTING SOURCES  Two open sources that give one quantity (a capacity, a place) differently, beyond a tolerance,
//   are flagged with both values and the size of the gap, not settled by picking one.
// Pure: no DOM, no imports.

/** A date field as a sortable day number (ms since 1970); '2020', '2020-11' and '2020-11-05' are all read. */
export function dayOf(v) {
  if (v == null || v === '') return null;
  if (v instanceof Date) return Number.isFinite(v.getTime()) ? v.getTime() : null;
  const m = /^(\d{4})(?:-(\d{1,2}))?(?:-(\d{1,2}))?/.exec(String(v).trim());
  return m ? Date.UTC(Number(m[1]), (Number(m[2]) || 1) - 1, Number(m[3]) || 1) : null;
}

/**
 * surveyCheck({ groundDate, planningDate, commissionedDate }) -> { checked, predates, against, line }
 * checked is false when the survey date or both plant dates are missing.
 */
export function surveyCheck(s = {}) {
  const g = dayOf(s.groundDate), plan = dayOf(s.planningDate), built = dayOf(s.commissionedDate);
  if (g == null || (plan == null && built == null)) return { checked: false, predates: false, against: null, line: '' };
  const later = [['planning', plan, s.planningDate], ['commissioning', built, s.commissionedDate]].filter(([, d]) => d != null && g < d);
  if (!later.length) return { checked: true, predates: false, against: null, line: `Ground survey ${s.groundDate} is after the plant's dates: it can show what was built.` };
  const [what, , when] = later.at(-1);
  return { checked: true, predates: true, against: what,
    line: `Ground survey predates this layout: flown ${s.groundDate}, before ${what} (${when}). The survey shows the land, not a plant; `
      + 'rows drawn here are illustrative and no plant in the survey confirms them.' };
}
/** The note a layout carries for its survey, or '' (no dates, or a survey after the plant). */
export const surveyNote = s => { const c = surveyCheck(s || {}); return c.predates ? c.line : ''; };

/**
 * sourceConflict([{ source, value }], { tolerance = 0.1, unit = '' }) -> null | { values, spread, line }
 * spread: (largest - smallest) / smallest. Flagged over the tolerance; both ends named by their generic source label.
 */
export function sourceConflict(values = [], { tolerance = 0.1, unit = '' } = {}) {
  const v = values.filter(x => Number.isFinite(x?.value) && x.value > 0);
  if (v.length < 2) return null;
  const lo = v.reduce((a, b) => (b.value < a.value ? b : a)), hi = v.reduce((a, b) => (b.value > a.value ? b : a)), spread = (hi.value - lo.value) / lo.value;
  if (spread <= tolerance + 1e-12) return null;
  return { values: v, spread, line: `Sources disagree: ${hi.source} gives ${hi.value}${unit ? ' ' + unit : ''}, ${lo.source} gives ${lo.value}${unit ? ' ' + unit : ''} `
    + `(${Math.round(spread * 100)} % apart). Both are kept; neither is picked.` };
}