GLOBALGRID2050 / EXPLORE CODE

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

Plant Template and 1 more file (part 2)

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

469 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 192 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 / solar-design-studio/202609271853-site-world/world/plant-piles.mjs lines 1–204
  2. Plant Template electrical · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-template.mjs lines 1–265

Plant Piles

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

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-piles.mjs · lines 1–204 of 204 · version 2026-09-27 18:53 · 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 sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 3 files: Build Geom (globalgrid2050); Plant Layout (globalgrid2050); Plant UI (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It 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 Build Geom, Plant Layout and Plant UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Piles (import), Pile Rules (import)
Used by
imported by Build Geom (import), imported by Plant Layout (import), imported by Plant UI (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 solar-design-studio/202609271853-site-world/world/plant-piles.mjs:1-204 · blob 170d55a05d148fecb0b9d29007cef175b139babb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// plant-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 world folder of GlobalGrid2050 that works with transformers, cables, solar and 33kV, using IEC 60287 and IEC 60949.

electricalglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-template.mjs · lines 1–265 of 265 · version 2026-09-27 18:53 · 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 sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers, cables, solar, 33kV, 400kV, 1500V.
Inputs & outputs
Voltage levels named: 400kV, 33kV, 1500V.
Downstream impact
Used directly by 5 files: Block MV (globalgrid2050); Single-Line Diagram (SLD) Plant (globalgrid2050); Cmd Model (globalgrid2050); Plant Layout (globalgrid2050); and 1 more. Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It 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 5 files, including Block MV, Single-Line Diagram (SLD) Plant and Cmd Model.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Cable Rating (import), Module Catalogue (import)
Used by
imported by Block MV (import), imported by Single-Line Diagram (SLD) Plant (import), imported by Cmd Model (import), imported by Plant Layout (import), imported by Plant UI (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 solar-design-studio/202609271853-site-world/world/plant-template.mjs:1-265 · blob d8f96697e2b0cd2976493b41be0125781ede2d00 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// 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 }) }));
}