In this section
- Cmd Model transform · energy-transition-simulator / prototype/mod/engine/cmd-model.mjs lines 1–357
- Connect Here electrical · energy-transition-simulator / prototype/mod/engine/connect-here.mjs lines 1–135
- Elec Style transform · energy-transition-simulator / prototype/mod/engine/elec-style.mjs lines 1–36
- Fault Level electrical · energy-transition-simulator / prototype/mod/engine/fault-level.mjs lines 1–14
- Journey render · energy-transition-simulator / prototype/mod/engine/journey.mjs lines 1–90
Cmd Model
A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, 33kV and the Renewable Energy Planning Database (REPD) register.
Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609271853-site-world/world/cmd-model.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Cmd Model; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9775 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/cmd-model.mjs:1-350 0a057d5aea18a1f93740361db9287bba767e120b
- sha256 c7fe2cd46addce46a3418ee39a782a224a7d6b28bd102ec0adf09f468913475f
- target sha256 320b541921fc5d67ccef81a8b6b5c4c8cffb524c2701f77fb6183c925d0fa597
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformenergy-transition-simulator / prototype/mod/engine/cmd-model.mjs · lines 1–357 of 357 · Not reached from any entry point (candidate for review) · pattern createSession (shared by 3 files)
- What it does
- It calculates cables, 33kV and the REPD register. Defines 27 functions or classes, including STRUCT, PACK, moduleOf, tplOpts, f.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, 33kV, the REPD register, 1500V.
- Inputs & outputs
- Voltage levels named: 33kV, 1500V.
- What it achieves
- It applies set (`applySet`), creates session (`createSession`) and runs layout (`runLayout`). The design as typed. A session holds the typed values, runs each command through an engine (the page's plant, block and layers, or a plain CPU layout in tests), echoes what changed in words, keeps an undo stack. Its code works with 33 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- Plant Feeders (import), Cmd Grammar (import), Plant Layout (import), Plant Template (import), String Design (import), Measure Format (import), Cmd Derive (import), Cmd Trench (import), and 2 more
- Used by
- mentioned in Standalone (comment link)
- Produces
- DEFAULTS, moduleOf, derive, postOf, TYPED_SECTION, spoilOf, echo, layoutInput, createSession, explain, summarize
- Defines here
- STRUCT, PACK, moduleOf, tplOpts, f, int, derive, postOf, spoilOf, echo, warnings, inWords, layoutInput, applySet, strOf, same, fmtPts, createSession, view, runLayout, exec, view_, undo, replay, canonical, explain, summarize
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/cmd-model.mjs:1-357 · blob 20654713cc52ecbf1457ce710f88eb1c003af0b8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/cmd-model.mjs) at v12 commit 3adcee9 (file last changed 0562d4f). Modular star family: public #148236 moduleOf.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-model.mjs: the design as typed. A session holds the typed values, runs each command through an engine (the page's
// plant, block and layers, or a plain CPU layout in tests), echoes what changed in words, keeps an undo stack, and keeps
// the script: the canonical lines that rebuild the design when replayed. Pure: the engine does all the world work.
//
// engine: { layout(input) -> Promise<summary | null>, openLand(input) -> Promise<[[e, n]...]>, drawnBoundary() -> pts | null,
// setBoundary(pts), clearPlant(), block({ stations, pocKv, at }) -> Promise<{ text, at }>, clearBlock(), piles() -> Promise<text>,
// show(arg) -> text, go(arg) -> text, constraints(summary, state) -> [text], avoid(state) -> [{ id, test }] }
// summary: { tables, mwp, mw, fits, rowsHa, trenchM, skipped, notes }
import { SECTION_FOR } from './plant-feeders.mjs';
import { parse, help, KEYS, guard } from './cmd-grammar.mjs';
import { tableGeometry, LAYOUT_DEFAULTS } from './plant-layout.mjs';
import { plantTemplate, moduleColdVoc, TEMPLATE_DEFAULTS as TD } from './plant-template.mjs';
import { STRING_ADVICE } from './string-design.mjs';
import { formatNumber, NONE } from './measure-format.mjs';
import { noonSun, rowShade, cableFor, bendOf, trenchOf, stringLoops } from './cmd-derive.mjs';
import { rateText, designText, TRENCH_KEYS, TRENCH_DEFAULTS, trenchEnv } from './cmd-trench.mjs';
import { structureById, catalogueText, formatRefusal, formatName, mpptCap, STRUCTURE_NOTE } from './structures.mjs';
import { presetById, presetText, PRESET_NOTE } from './structure-presets.mjs';
export const DEFAULTS = Object.freeze({
mw: null, layout: 'south', tilt: LAYOUT_DEFAULTS.tiltSouthDeg, tiltEw: LAYOUT_DEFAULTS.tiltEwDeg, pitch: null, gcr: LAYOUT_DEFAULTS.gcr,
edge: LAYOUT_DEFAULTS.lowEdgeM, mps: null, tempMin: -10, wp: null, voc: null, fence: LAYOUT_DEFAULTS.fenceSetbackM, water: LAYOUT_DEFAULTS.waterSetbackM,
slope: LAYOUT_DEFAULTS.slopeLimitPct, avoidOhl: true, depth: 1.11, width: 0.45, formation: 'trefoil', size: 300, metal: 'al',
wiring: 'standard', stations: 10, pocKv: null, soil: 1.2, load: 'continuous', ...TRENCH_DEFAULTS, boundary: null,
// structures (structures.mjs): format (null tiers: the layout's own), post lines, tracker strings, row gap, MPPT cap, post height
tiers: null, orient: 'portrait', tableCols: null, posts: 2, trackerStrings: 2, rowGap: 'slope', mppts: 12, stringsPerMppt: 2, postMax: 3,
gcrTracker: LAYOUT_DEFAULTS.gcrTracker,
// inverter class (plant-template.mjs), packing (plant-packing.mjs; band and run null: the packing's own), module size
inverterClass: 'string', inverterKVA: 300, invertersPerStation: 20, packing: LAYOUT_DEFAULTS.packing, bandM: null, runM: null,
hedge: LAYOUT_DEFAULTS.hedgeSetbackM, moduleLong: LAYOUT_DEFAULTS.moduleLongM, moduleShort: LAYOUT_DEFAULTS.moduleShortM
}); // depth/width/size/formation: the plant's typed 33 kV trench, 33kv-1-agri (data/trench-sections.json); the block's trenches are sized by rating
const LAYOUT_KEYS = ['mw', 'layout', 'tilt', 'tiltEw', 'pitch', 'gcr', 'edge', 'mps', 'tempMin', 'wp', 'voc', 'fence', 'water', 'slope', 'avoidOhl',
'tiers', 'orient', 'tableCols', 'posts', 'trackerStrings', 'rowGap', 'mppts', 'stringsPerMppt', 'postMax', 'gcrTracker',
'inverterClass', 'inverterKVA', 'invertersPerStation', 'packing', 'bandM', 'runM', 'hedge', 'moduleLong', 'moduleShort'];
const STRUCT = st => ({ tiers: st.tiers, orient: st.orient, tableCols: st.tableCols, trackerStrings: st.trackerStrings, gcrTracker: st.gcrTracker,
moduleLongM: st.moduleLong ?? LAYOUT_DEFAULTS.moduleLongM, moduleShortM: st.moduleShort ?? LAYOUT_DEFAULTS.moduleShortM });
const PACK = st => ({ packing: st.packing || LAYOUT_DEFAULTS.packing, hedgeSetbackM: st.hedge ?? LAYOUT_DEFAULTS.hedgeSetbackM,
...(st.bandM ? { bandTargetM: st.bandM } : {}), ...(st.runM ? { runTargetM: st.runM } : {}) });
// The module (one answer with the block, string-design.mjs): typed power and Voc win; else the selected module class
// (env.moduleClass() -> { wp, voc, coeffPctPerK }); else the template's default class A.
export function moduleOf(st, env = {}) {
const c = env.moduleClass?.() || null;
return { wp: st.wp ?? c?.wp ?? TD.moduleWp, voc: st.voc ?? c?.voc ?? TD.moduleVoc,
coeff: st.voc == null && c?.coeffPctPerK != null ? c.coeffPctPerK / 100 : TD.vocCoeffPerK, typed: st.voc != null };
}
const tplOpts = (st, env) => ({ moduleWp: moduleOf(st, env).wp, moduleVoc: moduleOf(st, env).voc, vocCoeffPerK: moduleOf(st, env).coeff,
minCellC: st.tempMin ?? -10, mppts: st.mppts, stringsPerMppt: st.stringsPerMppt,
inverterClass: st.inverterClass || 'string', inverterKVA: st.inverterKVA ?? 300, invertersPerStation: st.invertersPerStation ?? 20,
...(st.mps ? { modulesPerString: st.mps } : {}) });
// Typed settings keep their places (a pitch of 7.00 m); the one formatter underneath (measure-format.mjs), one dash for none.
const f = (v, d = 2) => (v == null || !Number.isFinite(v) ? NONE : formatNumber(v, d));
const int = v => f(v, 0);
/** The table, rows, cables and loops the typed values give. env: { latDeg, catalogue }; lay: the last layout summary. */
export function derive(st, env = {}, lay = null) {
const tpl = plantTemplate({ targetMW: st.mw || 50, ...tplOpts(st, env) });
const south = st.layout === 'south', base = { ...LAYOUT_DEFAULTS, tiltSouthDeg: st.tilt, tiltEwDeg: st.tiltEw, lowEdgeM: st.edge, ...STRUCT(st) };
const T0 = tableGeometry(st.layout, base, tpl);
const gcr = south ? (st.pitch ? T0.slope / st.pitch : st.gcr) : null, ewGapM = !south && st.pitch ? st.pitch - T0.depth : base.ewGapM;
const T = tableGeometry(st.layout, { ...base, ...(south ? { gcr } : { ewGapM }) }, tpl);
const sun = noonSun(env.latDeg ?? 51.8), shade = rowShade({ rise: T.rise, depth: T.depth, pitch: T.pitch, elevDeg: sun.winter });
const cable = cableFor(env.catalogue, st.size, st.metal), bend = bendOf(env.catalogue, cable);
const trench = trenchOf({ depth: st.depth, width: st.width, formation: st.formation, od: cable ? cable.od : 0.05 });
const mps = tpl.counts.modulesPerString, cv = moduleColdVoc(tpl.params), loops = stringLoops({ mps });
const voc = { module: cv.v, string: cv.v * mps, most: Math.floor(tpl.params.systemV / cv.v + 1e-9), rule: cv.rule, moduleVoc: tpl.params.moduleVoc };
return { st, T, gcr, ewGapM, sun, shade, cable, bend, trench, mps, voc, loops, lay, spoilM3: spoilOf(lay, st, env.sections), tpl, post: postOf(st, T) };
}
// The tallest post by design: south two lines at 0.2 / 0.8 of the depth (one line: mid depth); reveal = low edge + rise x f - rails 0.3 m.
export function postOf(st, T) {
if (T.tracker) return null;
const f = st.layout === 'south' ? (st.posts === 1 ? 0.5 : 0.8) : 0.5, reveal = st.edge + T.rise * f - 0.3;
return { reveal, over: reveal > st.postMax + 1e-9 };
}
// Bank spoil of the plant's MV trenches: each trench type's length x its section; the typed trench replaces the single-circuit
// section the layout routes (SECTION_FOR.one: 33kv-1-agri); two-circuit and ducted crossings keep their catalogue sections.
export const TYPED_SECTION = SECTION_FOR.one;
export function spoilOf(lay, st, sections = []) {
if (!lay?.trenchByType) return null;
let v = 0;
for (const [id, L] of Object.entries(lay.trenchByType)) {
const sec = (sections || []).find(x => x.id === id);
v += L * (id === TYPED_SECTION || !sec ? st.width * st.depth : sec.trench_width_m * sec.trench_depth_m);
}
return v;
}
// What an echo compares, in order: [label, value(d) as text].
const WATCH = [
['layout', d => d.st.layout], ['plant export', d => (d.st.mw ? `${int(d.st.mw)} MW` : NONE)],
['tilt', d => `${f(d.st.layout === 'south' ? d.st.tilt : d.st.tiltEw, 0)}°`], ['modules per string', d => int(d.mps)],
['coldest cell', d => `${f(d.st.tempMin ?? -10, 0)} °C`], ['string cold Voc', d => `${int(d.voc.string)} V`], ['row pitch', d => `${f(d.T.pitch)} m`], ['GCR', d => (d.gcr ? f(d.gcr) : NONE)],
['clear gap between rows', d => `${f(d.shade.gapM)} m`], ['midwinter noon shadow', d => `${f(d.shade.shadowM)} m`],
['lowest module edge', d => `${f(d.st.edge)} m`], ['top edge', d => `${f(d.st.edge + d.T.rise)} m`],
['slope limit', d => `${int(d.st.slope)} %`], ['watercourse setback', d => `${int(d.st.water)} m`], ['fence setback', d => `${f(d.st.fence, 1)} m`],
['overhead line zones', d => (d.st.avoidOhl ? 'kept clear' : 'not avoided')],
['trench depth', d => `${f(d.st.depth)} m`], ['trench width', d => `${f(d.st.width)} m`], ['formation', d => d.st.formation],
['cover to top cable', d => `${f(d.trench.cover)} m`], ['cable', d => (d.cable ? `${d.st.size} mm² ${d.st.metal === 'cu' ? 'Cu' : 'Al'}, OD ${f(d.cable.odMm, 1)} mm` : NONE)],
['bend radius (installation)', d => (d.bend?.installM ? `${f(d.bend.installM)} m` : NONE)],
['table', d => formatName(d.T.tiers, d.T.orient, d.T.cols)],
['post lines', d => (d.T.tracker ? 'one along each tube' : d.st.layout === 'east-west' ? 'one under each face' : d.st.posts === 1 ? 'single' : 'twin')],
['strings per tracker row', d => (d.T.tracker ? int(d.st.trackerStrings) : NONE)], ['tracker GCR', d => (d.T.tracker ? f(d.st.gcrTracker) : NONE)],
['row gap', d => (d.st.layout === 'south' ? (d.st.rowGap === 'slope' ? 'slope-aware' : 'flat') : NONE)],
['inverters', d => `${d.st.inverterClass || 'string'}, ${int(d.st.inverterKVA ?? 300)} kVA, ${int(d.st.invertersPerStation ?? 20)} a station`],
['strings per inverter', d => (d.st.inverterClass === 'central' ? `${int(d.tpl.counts.stringsPerInverter)} in ${int(d.tpl.counts.combiners / d.tpl.counts.inverters)} combiner boxes`
: `${int(d.tpl.counts.stringsPerInverter)} (cap ${mpptCap(d.st)}: ${d.st.mppts} MPPT × ${d.st.stringsPerMppt})`)],
['packing', d => `${d.st.packing || 'fields'}${d.st.bandM ? `, tracks every ${int(d.st.bandM)} m` : ''}${d.st.runM ? `, runs ${int(d.st.runM)} m` : ''}`],
['hedge setback', d => `${f(d.st.hedge ?? 5, 1)} m`], ['module size', d => `${f(d.st.moduleLong ?? 2.384, 3)} × ${f(d.st.moduleShort ?? 1.134, 3)} m`],
['tallest post by design', d => (d.post ? `${f(d.post.reveal)} m (limit ${f(d.st.postMax, 1)} m)` : NONE)],
['string wiring', d => d.st.wiring], ['loop area per string', d => `${f(d.loops[d.st.wiring].area, 1)} m²`],
['spoil (bank)', d => (d.spoilM3 ? `${int(d.spoilM3)} m³` : NONE)], ['soil', d => `${f(d.st.soil, 1)} K.m/W`], ['load profile', d => d.st.load],
['trenches side by side', d => ['Dc', 'Branch', 'Collector', 'Mv'].map(k => `${k.toLowerCase()} ${d.st['split' + k] || 'by rating'}`).join(', ')],
['trench cover', d => `dc ${f(d.st.coverDc)} m, lv ${f(d.st.coverLv)} m, 33 kV ${f(d.st.coverMv)} m`], ['cable drum', d => `${int(d.st.drumM)} m`],
['33 kV ring case', d => d.st.ring]
];
const COUNTS = [['tables', s => int(s.tables)], ['MWp', s => f(s.mwp, 1)], ['land under rows', s => `${f(s.rowsHa, 1)} ha`],
['built', s => `${int(s.mw)} MW${s.fits ? '' : ' (not all fits)'}`]];
/** "row pitch 11.97 m → 7.00 m; GCR 0.40 → 0.68; 1,402 tables → 1,402" */
export function echo(a, b) {
const parts = WATCH.map(([k, v]) => [k, v(a), v(b)]).filter(([, x, y]) => x !== y).map(([k, x, y]) => `${k} ${x} → ${y}`);
if (a.lay && b.lay && a.lay !== b.lay) parts.push(...COUNTS.map(([k, v]) => [k, v(a.lay), v(b.lay)]).filter(([, x, y]) => x !== y)
.map(([k, x, y]) => (k === 'tables' ? `${x} tables → ${y}` : `${k} ${x} → ${y}`)));
else if (!a.lay && b.lay) parts.push(`${int(b.lay.tables)} tables, ${f(b.lay.mwp, 1)} MWp, ${f(b.lay.rowsHa, 1)} ha under rows${b.lay.fits ? '' : ` (${int(b.lay.mw)} MW fits)`}`);
return parts.join('; ');
}
// Warnings the new values raise (never refusals: the owner decides).
function warnings(d) {
const w = [];
if (d.st.layout === 'south' && d.shade.shaded) w.push(`rows shade each other at midwinter noon (${f(d.shade.shadowM)} m shadow, ${f(d.shade.gapM)} m gap)`);
if (d.trench.cover < 0.91 - 1e-9) w.push(`cover ${f(d.trench.cover)} m is under the 0.91 m asked on good farmland (a network operator's cable standard)`);
// Owner, 27 Sept: modules in series are his to change; an over-voltage is said, never refused, with the advisory.
if (d.voc.string > 1500) w.push(`plant layout: ${d.mps} modules in a string reach ${int(d.voc.string)} V cold (module Voc ${f(d.voc.moduleVoc, 1)} V; `
+ `the stricter of ${f(d.st.tempMin ?? -10, 0)} °C and Voc × 1.15, here ${d.voc.rule}), over the 1500 V system limit; at most ${d.voc.most} `
+ `(type string ${d.voc.most}). ${STRING_ADVICE}`);
if (d.post?.over) w.push(`posts stand ${f(d.post.reveal)} m by design, over the ${f(d.st.postMax, 1)} m limit: lower the tilt, use fewer tiers, `
+ `a lower edge or a single post line (flagged on the HUD). ${STRUCTURE_NOTE}`);
const c = d.tpl.counts, dcac = c.stringsPerInverter * c.modulesPerString * d.tpl.params.moduleWp / 1000 / d.tpl.params.inverterKVA;
if (d.st.inverterClass !== 'central' && c.stringsPerInverter >= mpptCap(d.st) && dcac < d.tpl.params.dcAcRatio - 0.05) w.push(`DC/AC ${f(dcac)}: strings per inverter are capped at `
+ `${mpptCap(d.st)} by the MPPTs (${d.st.mppts} × ${d.st.stringsPerMppt}); more strings per input or longer strings raise it (mppt ${d.st.mppts} inputs `
+ `${Math.ceil(Math.round(d.tpl.params.inverterKVA * d.tpl.params.dcAcRatio / (c.modulesPerString * d.tpl.params.moduleWp / 1000)) / d.st.mppts)})`);
if (!d.trench.fits) w.push(`the ${d.st.formation} needs a ${f(d.trench.needWidth)} m trench; it is ${f(d.st.width)} m`);
return w;
}
/** The typed values as plant.run parameters. */
// A refusal in words: a fault inside the page (a JavaScript error) is never shown by its programming name.
const inWords = e => (e instanceof TypeError || e instanceof ReferenceError || e instanceof RangeError ? 'That did not run here (a fault in the page)' : e.message);
export function layoutInput(st, env = {}) {
const d = derive(st, env), south = st.layout === 'south';
return { mw: st.mw, layout: st.layout, slopeLimitPct: st.slope, fenceSetbackM: st.fence,
options: { tiltSouthDeg: st.tilt, tiltEwDeg: st.tiltEw, lowEdgeM: st.edge, waterSetbackM: st.water, ...STRUCT(st), ...PACK(st), rowGap: st.rowGap,
...(env.latDeg ? { latDeg: env.latDeg } : {}), ...(south ? { gcr: d.gcr } : st.layout === 'tracker' ? {} : { ewGapM: d.ewGapM }) },
template: tplOpts(st, env), piles: { posts: st.posts, rules: { revealFailM: st.postMax } } };
}
// Applies typed values; returns { st } or { why } (refused in words).
function applySet(st0, c, env) {
const set = { ...c.set }, st = { ...st0 };
if (c.arg.maybeEw && 'tilt' in set && st.layout === 'east-west') {
const g = guard('tiltEw', set.tilt); if (g) return { why: g }; set.tiltEw = set.tilt; delete set.tilt;
}
if ('gcr' in set && (set.layout || st.layout) === 'tracker') { set.gcrTracker = set.gcr; delete set.gcr; st.pitch = null; }
if ('gcr' in set) { if ((set.layout || st.layout) !== 'south') return { why: 'east-west rows are set by the gap between them: type pitch' }; st.pitch = null; }
Object.assign(st, set);
// A format kept from another layout that this one does not build goes back to the layout's own; one typed now is refused.
const bad = formatRefusal(st.layout, st.tiers || (st.layout === 'tracker' || st.layout === 'east-west' ? 1 : 2), st.orient);
if (bad && ('tiers' in set || 'orient' in set)) return { why: bad };
if (bad) Object.assign(st, { tiers: null, orient: 'portrait', tableCols: null });
if (st.posts === 1 && st.layout === 'east-west' && ('posts' in set || 'layout' in set)) {
if ('posts' in set) return { why: 'a single post line is built for south-facing tables here; east-west keeps one line under each face' };
st.posts = 2;
}
let d;
try { d = derive(st, env); } catch (e) { return { why: e.message.replace(/^plant template: /, '') }; } // an inverter class and rating that do not agree
if (st.layout === 'south' && st.pitch && !(d.gcr <= KEYS.gcr.max)) return { why: `row pitch ${f(st.pitch)} m leaves no room: the table is ${f(d.T.depth)} m deep in plan `
+ `and ${f(d.T.slope)} m up the slope, so the ground cover ratio would be ${f(d.T.slope / st.pitch)} (most ${KEYS.gcr.max}); the least pitch is ${f(d.T.slope / KEYS.gcr.max)} m` };
if (st.layout === 'east-west' && st.pitch && d.ewGapM < 0.5) {
return { why: `row pitch ${f(st.pitch)} m leaves ${f(d.ewGapM)} m between east-west tables; at least 0.5 m (least pitch ${f(d.T.pitch - d.ewGapM + 0.5)} m)` };
}
if (!d.cable) return { why: `no 33 kV ${st.metal === 'cu' ? 'copper' : 'aluminium'} single core of ${st.size} mm² in the cable catalogue` };
return { st };
}
// The typed string length and coldest cell go with every rebuild of the block, so a re-size never drops them.
const strOf = st => ({ ...(st.mps ? { modulesPerString: st.mps } : {}), ...(st.tempMin !== DEFAULTS.tempMin ? { tempMinC: st.tempMin } : {}) });
const same = (a, b, keys) => keys.every(k => JSON.stringify(a[k]) === JSON.stringify(b[k]));
const fmtPts = pts => pts.map(([e, n]) => `${Math.round(e)} ${Math.round(n)}`).join(', ');
const ANIM = [['tilt', ['tilt', 'tiltEw']], ['rows', ['pitch', 'gcr', 'layout', 'edge']], ['trench', ['depth', 'width', 'formation', 'size', 'metal']],
['loop', ['wiring', 'mps']]];
export function createSession({ engine, env = {} }) {
let st = { ...DEFAULTS }, lay = null, script = [], block = null, pending = false;
const hist = [];
const view = () => derive(st, env, lay);
async function runLayout() {
if (!st.boundary) {
const drawn = engine.drawnBoundary?.();
// Whole metres, as the script writes it, so a replay packs the very same boundary (the fields packing starts at its edges).
const got = drawn || await engine.openLand(layoutInput(st, env));
st = { ...st, boundary: got && got.map(([e, n]) => [Math.round(e), Math.round(n)]) };
if (!st.boundary) return { why: 'no boundary: draw one (Plant > Draw boundary) or stand on open land' };
script.splice(Math.max(0, script.length - 1), 0, `boundary ${fmtPts(st.boundary)}`); // before the line that asked for it
}
await engine.setBoundary?.(st.boundary);
const s = await engine.layout({ ...layoutInput(st, env), avoid: st.avoidOhl ? engine.avoid?.(st) || [] : [] });
if (!s) return { why: 'the layout did not run (see the Plant readout)' };
lay = s; pending = false;
return { s };
}
async function exec(line, { replay = false } = {}) {
const c = parse(line);
if (!c.ok) return { ok: false, text: c.why, line };
if (c.act === 'help') return { ok: true, text: help(c.arg.topic), line, quiet: true };
if (c.act === 'script') {
const typed = new Set(script.flatMap(l => Object.keys(parse(l).set || {})));
const plantTrench = new Set(['depth', 'width', 'formation', 'size']); // the plant's 33 kV feeder trench, not the block's
const assumed = ['tilt', 'gcr', 'edge', 'tempMin', 'wp', 'voc', 'fence', 'water', 'slope', 'depth', 'width', 'formation', 'size', 'wiring', ...TRENCH_KEYS]
.filter(k => !typed.has(k) && !(k === 'gcr' && typed.has('pitch')))
.map(k => `${plantTrench.has(k) ? 'plant 33 kV feeder ' : ''}${KEYS[k].label} ${st[k] ?? moduleOf(st, env)[k]}${KEYS[k].unit ? ' ' + KEYS[k].unit : ''}`);
if (block) assumed.push('block trenches: LV 400 mm² Al and DC 6 mm² Cu, each trench sized by rating (type trench design)');
return { ok: true, line, quiet: true, text: `${script.length ? script.join('\n') : 'Nothing typed yet.'}`
+ `\nTYPED: ${[...typed].map(k => KEYS[k]?.label || k).join(', ') || 'nothing'}\nASSUMED (defaults): ${assumed.join(', ')}` };
}
if (c.act === 'undo') return undo();
if (c.act === 'structure' && !c.arg.id) return { ok: true, text: c.arg.preset ? presetText() : catalogueText(), line, quiet: true };
if (c.act === 'structure') { // a preset of typed values, echoed and undone like any other line
const S = structureById(c.arg.id) || presetById(c.arg.id), bad = Object.entries(S.set).map(([k, v]) => (v === null ? null : guard(k, v))).filter(Boolean);
if (bad.length) return { ok: false, text: bad.join('; ') + '. Nothing was changed.', line };
c.set = { ...S.set }; c.act = null; c.structure = S;
}
const view_ = async fn => { try { return { ok: true, text: await fn(), line, quiet: true }; } catch (e) { return { ok: false, text: inWords(e) + '.', line }; } };
if (c.act === 'show') return view_(() => engine.show(c.arg));
if (c.act === 'rate') return view_(() => rateText(c.arg, st));
if (c.act === 'xray') return view_(() => (engine.xray ? engine.xray(c.arg.on) : 'X-ray is not in this build.'));
if (c.act === 'trench-design' && !Object.keys(c.set).length) return view_(async () => designText(st, await engine.trenchRows?.()));
if (c.act === 'explain') { const d = view(); return { ok: true, text: explain(c.arg.what, d), line, quiet: true, anim: c.arg.what === 'bend' ? 'trench' : 'loop', d, before: d }; }
// Earthing (earth-mount.mjs): its settings live in the cartridge; the typed line joins the script so a replay rebuilds it.
if (c.act === 'earthing') {
const r = await view_(async () => { if (!engine.earthing) throw Error('earthing is not in this build'); return engine.earthing(c.arg); });
if (r.ok) script.push(canonical(c));
return r;
}
if (c.act === 'binoculars') return view_(async () => { if (!engine.binoculars) throw Error('the binoculars are not in this build'); return engine.binoculars(c.arg); });
if (c.act === 'hud') return view_(async () => { if (!engine.hud) throw Error('the check HUD is not in this build'); return engine.hud(c.arg); });
if (c.act === 'repd') return replay ? { ok: true, text: 'REPD flight not replayed.', line, quiet: true } // a flight is not part of the design
: view_(async () => { if (!engine.repd) throw Error('REPD flights are not in this build'); return engine.repd(c.arg); });
if (c.act === 'journey') return view_(async () => { if (!engine.journey) throw Error('The journey is not in this build'); return engine.journey(c.arg); });
if (c.act === 'connect') return replay ? { ok: true, text: 'Connection plan not replayed.', line, quiet: true } // connect here (connect-mount.mjs)
: view_(async () => { if (!engine.connect) throw Error('connect here is not in this build'); return engine.connect(c.arg); });
if (c.act === 'find') return view_(async () => { if (!engine.find) throw Error('Find is not in this build'); return engine.find(c.arg); });
if (c.act === 'go') return view_(async () => { if (pending) await runLayout(); return engine.go(c.arg, lay); });
// Follow the power and the single-line diagram read the world; they change no typed value and stay out of the script.
if (c.act === 'follow') return view_(async () => { if (pending) await runLayout(); if (!engine.follow) throw Error('Follow is not in this build'); return engine.follow(c.arg, lay); });
if (c.act === 'sld') return view_(async () => { if (pending) await runLayout(); if (!engine.sld) throw Error('the single-line diagram is not in this build'); return engine.sld(c.arg, lay); });
const before = { st, lay, script: script.slice(), block, d: view() };
const a = applySet(st, c, env);
if (a.why) return { ok: false, text: a.why + '. Nothing was changed.', line };
if (!c.act && same(st, a.st, Object.keys(DEFAULTS))) return { ok: true, text: `No change: ${c.line} is already set.`, line, quiet: true }; // not an undo step
st = a.st;
let extra = [];
try {
if (c.act === 'boundary') {
st = { ...st, boundary: c.arg.open ? null : c.arg.points };
if (st.boundary) await engine.setBoundary?.(st.boundary);
if (lay && st.boundary) { if (replay) pending = true; else { const r = await runLayout(); if (r.why) throw Error(r.why); } }
} else if (c.act === 'fill' && !st.boundary && !engine.drawnBoundary?.()) {
throw Error('fill needs a boundary: draw one (Plant > Draw boundary), or type plant 50mw to use the open land around you');
}
if (c.act === 'fill' && !st.mw) throw Error('fill needs a capacity first: plant 50mw, or fill 50mw');
if (c.act === 'layout' && !st.mw) throw Error('plant needs a capacity, such as plant 50mw south');
const redo = c.act === 'layout' || c.act === 'fill' || (lay && !same(before.st, st, LAYOUT_KEYS));
script.push(canonical(c));
if (redo) {
if (replay) pending = true;
else { const r = await runLayout(); if (r.why) throw Error(r.why); extra = engine.constraints?.(lay, st) || []; }
}
if (c.act === 'block') {
if (pending) await runLayout();
const at = c.arg.at || block?.at || null, b = await engine.block({ stations: st.stations / 10, pocKv: st.pocKv, at, trench: trenchEnv(st), frame: !replay, ...strOf(st) });
block = { at: b.at, stations: st.stations }; extra.push(b.text);
script[script.length - 1] = `block ${st.stations}mva${st.pocKv ? ` poc ${st.pocKv}` : ''}${b.at ? ` at ${Math.round(b.at.e)} ${Math.round(b.at.n)}` : ''}`;
}
if (('mps' in c.set || 'tempMin' in c.set) && engine.strings) { const t = await engine.strings({ mps: st.mps, tempMinC: st.tempMin }); if (t) extra.push(t); }
if (c.act === 'piles') { if (pending) await runLayout(); extra.push(await engine.piles(lay)); }
if (block && c.act !== 'block' && !same(before.st, st, TRENCH_KEYS)) { // soil, load or split typed: the block's trenches re-sized
await engine.block({ stations: st.stations / 10, pocKv: st.pocKv, at: block.at, trench: trenchEnv(st), ...strOf(st) }); extra.push('Block trenches re-sized.');
}
if (c.act === 'trench-design') extra.push(designText(st, await engine.trenchRows?.()));
} catch (e) {
st = before.st; lay = before.lay; script = before.script; block = before.block;
return { ok: false, text: inWords(e) + '. Nothing was changed.', line };
}
const after = view(), said = echo(before.d, after);
hist.push({ line: c.line, before });
const warn = warnings(after).filter(w => !before.d.lay !== !after.lay || !warnings(before.d).includes(w)); // all of them on a new layout
const keys = Object.keys(c.set), anim = (ANIM.find(([, ks]) => ks.some(k => keys.includes(k))) || [null])[0];
if (c.structure) extra.unshift(`${c.structure.evidence ? 'Preset' : 'Structure'} ${c.structure.id}: ${c.structure.label}. Class ranges: ${c.structure.ranges}.`
+ (c.structure.evidence ? ` Evidence: ${c.structure.evidence}. ${PRESET_NOTE}` : ` ${STRUCTURE_NOTE}`));
const text = [said || (c.act ? '' : `${c.line}: set (the same as before, to the precision shown)`), ...extra, ...warn.map(w => 'Note: ' + w)].filter(Boolean).join('\n');
return { ok: true, text, line, anim, d: after, before: before.d };
}
async function undo() {
const h = hist.pop();
if (!h) return { ok: false, text: 'Nothing to undo.', line: 'undo' };
const now = view(), b = h.before, layoutChanged = b.lay !== lay || !same(b.st, st, [...LAYOUT_KEYS, 'boundary']);
st = b.st; script = b.script;
if (block && !b.block) engine.clearBlock?.();
else if (b.block && (block !== b.block || !same(now.st, b.st, TRENCH_KEYS))) {
await engine.block({ stations: b.block.stations / 10, pocKv: b.st.pocKv, at: b.block.at, trench: trenchEnv(b.st), ...strOf(b.st) });
}
block = b.block;
if (engine.strings && !same(b.st, now.st, ['mps', 'tempMin'])) await engine.strings({ mps: st.mps, tempMinC: st.tempMin });
if (layoutChanged) {
if (b.lay) { const r = await runLayout(); if (r.s) lay = r.s; } else { lay = null; engine.clearPlant?.(); if (st.boundary) await engine.setBoundary?.(st.boundary); }
}
const said = echo(now, view());
return { ok: true, text: `Undid "${h.line}"${said ? ': ' + said : '.'}`, line: 'undo', anim: null, d: view() };
}
// Replays a script from the start: values are set line by line, the layout runs once where it is needed and at the end.
async function replay(lines) {
st = { ...DEFAULTS }; lay = null; script = []; block = null; pending = false; hist.length = 0;
const out = [];
for (const l of lines) { if (!String(l).trim() || /^\s*#/.test(l)) continue; out.push(await exec(l, { replay: true })); }
if (pending) { const r = await runLayout(); out.push(r.why ? { ok: false, text: r.why } : { ok: true, text: echo(derive(st, env), view()) }); }
hist.length = 0;
return out;
}
return { exec, undo, replay, script: () => script.slice(), state: () => ({ ...st }), layout: () => lay, derived: view, history: () => hist.length };
}
// The line kept in the script: the typed words, in the language's own spelling.
function canonical(c) {
if (c.act === 'boundary') return c.arg.open ? 'boundary open' : `boundary ${fmtPts(c.arg.points)}`;
return c.line.replace(/\s+/g, ' ').trim();
}
/** Words for "bend radius" and "loop area". */
export function explain(what, d) {
if (what === 'bend') {
if (!d.bend?.installM) return 'No bend rule in the catalogue for this cable.';
return `${d.st.size} mm² ${d.st.metal === 'cu' ? 'Cu' : 'Al'} (OD ${f(d.cable.odMm, 1)} mm): bend radius ${f(d.bend.installM)} m while pulling`
+ ` (${d.bend.installX} × OD), ${f(d.bend.finalM)} m set in place (${d.bend.finalX} × OD). ${d.bend.source}`;
}
const L = d.loops;
return `Loop between + and − of one ${d.mps}-module string: standard ${f(L.standard.area, 1)} m², leapfrog ${f(L.leapfrog.area, 1)} m²`
+ ` (${f(100 * (1 - L.leapfrog.area / L.standard.area), 0)} % less). Routes on the table assumed; wiring ${d.st.wiring}.`;
}
/** The counts an echo compares, from a plant layout (plant-layout.mjs result). */
export const summarize = r => (r ? { tables: r.built.tables, mwp: r.built.mwp, mw: r.built.mw, fits: r.fits,
rowsHa: r.built.tables * r.table.pitch * (r.table.lenU + r.params.tableGapM) / 1e4, trenchM: r.electrical?.trenchM ?? 0,
trenchByType: { ...(r.electrical?.trenchByType || {}) }, crossReview: r.crossReview || 0, rowGap: r.rowGap ? { ...r.rowGap } : null,
skipped: { ...r.skipped }, notes: r.notes.slice() } : null);Connect Here
A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, solar, 33kV and substations, using IEC 60287 and IEC 60287-1-1.
Set aside from the main view: 98% of its lines are the same as energy-transition-simulator/202609280014/mod/engine/connect-here.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Connect Here; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9821 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/connect-here.mjs:1-135 fd08ce5ed7ec651a19681143005e6d321a768272
- sha256 de42c6699943e82f23f9dbedab3d9b1ec849e74009f4d7328540946a8df5e811
- target sha256 c155ea3e4281dbc01ef64e1fb801df083d64e258e923fc5e0aca337dcd29c94d
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
electricalenergy-transition-simulator / prototype/mod/engine/connect-here.mjs · lines 1–135 of 135 · Not reached from any entry point (candidate for review) · pattern planConnection (shared by 2 files)
- What it does
- It calculates cables, solar, 33kV and substations. Defines 6 functions or classes, including refuse, parseConnect, connectKv, cableOpts, fmtLen.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, solar, 33kV, substations, 132kV, 1kV.
- Inputs & outputs
- Voltage levels named: 132kV, 33kV, 1kV.
- What it achieves
- It parses connect (`parseConnect`) and is built from the refuse step (`refuse`) and the connect kV helper (`connectKv`). The third step of the journey (owner direction 8.3): "connect here solar 50 at 132" drops a site where you stand and plans an illustrative cable back to the nearest substation at that voltage. Its code works with 33 kV and 1 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- Cable Route (import), Cable Rating (import), Single-Line Diagram (SLD) Connect (import)
- Used by
- none found
- Produces
- CONNECT_KV, CONNECT_PF, DROP_TARGET_PCT, MAX_CIRCUITS, CONNECT_LABEL, CLAUSES, parseConnect, connectKv, cableOpts, planConnection
- Defines here
- refuse, parseConnect, connectKv, cableOpts, fmtLen, planConnection
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/connect-here.mjs:1-135 · blob 8d637668d74e08ba09dd9b0d0d7a556e14df8b5e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/connect-here.mjs) at v12 commit 3adcee9 (file last changed 0562d4f). 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.
// connect-here.mjs: the third step of the journey (owner direction 8.3): "connect here solar 50 at 132" drops a site where
// you stand and plans an illustrative cable back to the nearest substation at that voltage: route length, current, cable
// size, voltage drop and losses, each check cited by clause only. Pure: no DOM, no WebGL.
//
// Reuses, never rewrites: routeCable (cable-route.mjs) for the length, sizeFor / rating / impedance / dropPercent
// (cable-rating.mjs, the IEC 60287 steady-state rating) for the cable, and kvForMW (sld-connect.mjs) when no voltage is
// typed. Star families: no family found for an MV connection sizer; the parts above are the existing ones.
//
// What it is NOT: the route is a straight line from here to the substation's fence landing (the road and field-edge
// route is the next step), the cable build above 33 kV is scaled from the 33 kV one (own estimate), and the network
// operator decides the real connection. Every figure is early-design and says so.
import { routeCable } from './cable-route.mjs';
import { sizeFor, rating, dropPercent, RATING_DEFAULTS } from './cable-rating.mjs';
import { kvForMW } from './sld-connect.mjs';
export const CONNECT_KV = [11, 33, 66, 132, 275, 400];
export const CONNECT_PF = 0.95; // assumed plant power factor at the point of connection (own assumption)
export const DROP_TARGET_PCT = 3; // own early-design target, not a limit from any standard
export const MAX_CIRCUITS = 6;
export const CONNECT_LABEL = 'Illustrative early design: straight-line route, estimated cable build; the network operator decides the real connection.';
// Clauses cited, never copied.
export const CLAUSES = Object.freeze({
rating: 'IEC 60287-1-1 cl. 2.1 (conductor a.c. resistance), IEC 60287-2-1 cl. 2.2 (external thermal resistance)',
drop: 'ESQCR 2002 reg. 27(3) (declared voltage tolerance)',
conductor: 'IEC 60228 (conductor classes; resistance estimated, not tabled)',
lv: 'BS 7671 Reg. 525 applies at 1 kV and below only; not used for this MV/HV cable'
});
// Insulation thickness by voltage, own illustrative scaling from the 33 kV build (8 mm); a maker's data replaces it.
const INSULATION_MM = { 11: 3.4, 33: 8.0, 66: 11.0, 132: 18.0 };
const TECH = ['solar', 'bess', 'battery', 'load'];
const refuse = (msg, line) => ({ ok: false, error: msg, line: String(line || '').trim() });
// Pure: a typed line -> { ok, act: 'connect', arg: { tech, mw, kv } } | { ok: false, error } | null (not a connect line).
// connect here · connect here 132 · connect here solar 50 · connect here bess 40 at 132 kv · connect here 50 mw 33 kv
export function parseConnect(line) {
const text = String(line || '').toLowerCase().replace(/#.*$/, '').replace(/\s+/g, ' ').trim();
const m = text.match(/^connect(?: here)?(?: (.*))?$/);
if (!m) return null;
let rest = (m[1] || '').replace(/(\d)\s*(mw|kv)\b/g, '$1 $2').replace(/\bat\b/g, ' ').trim();
const arg = { tech: null, mw: null, kv: null };
const ws = rest.split(/\s+/).filter(Boolean);
const nums = [];
for (let i = 0; i < ws.length; i++) {
const w = ws[i];
if (TECH.includes(w)) { arg.tech = w === 'battery' ? 'bess' : w; continue; }
if (/^\d+(\.\d+)?$/.test(w)) {
const v = Number(w), unit = ws[i + 1];
if (unit === 'kv') { arg.kv = v; i++; } else if (unit === 'mw') { arg.mw = v; i++; } else nums.push(v);
continue;
}
return refuse(`connect here does not know "${w}": try connect here solar 50 at 132`, line);
}
// Bare numbers: with a technology the first is MW (connect here solar 50 132); a lone voltage word is kV.
for (const v of nums) {
if (arg.tech && arg.mw == null) arg.mw = v;
else if (arg.kv == null && CONNECT_KV.includes(v)) arg.kv = v;
else if (arg.mw == null) arg.mw = v;
else return refuse(`connect here has one MW and one kV, not ${v} as well`, line);
}
if (arg.kv != null && !CONNECT_KV.includes(arg.kv)) return refuse(`${arg.kv} kV is not a connection voltage here (${CONNECT_KV.join(', ')})`, line);
if (arg.mw != null && !(arg.mw > 0 && arg.mw <= 5000)) return refuse(`${arg.mw} MW is out of range`, line);
if (arg.kv == null && arg.mw == null) return refuse('connect here takes a voltage or a size: connect here 132, or connect here solar 50', line);
return { ok: true, verb: 'connect', act: 'connect', set: {}, line: String(line).trim(), arg };
}
/** The voltage to use: the typed one, else by plant size (sld-connect kvForMW). */
export const connectKv = ({ kv, mw }) => kv ?? kvForMW(mw);
/** The IEC 60287 rating options for a voltage: the 33 kV build with insulation scaled (own estimate). */
export function cableOpts(kv, extra = {}) {
return { ...RATING_DEFAULTS, kv, u0Kv: kv / Math.sqrt(3), insulationMm: INSULATION_MM[kv] ?? RATING_DEFAULTS.insulationMm, ...extra };
}
const fmtLen = m => (m >= 1000 ? `${(m / 1000).toFixed(2)} km` : `${Math.round(m)} m`);
/**
* planConnection({ from: {e,n}, to: {e,n}, kv, mw?, pf?, groundAt?, circuitGroupFactor? }) ->
* { length, route, kv, mw, amps, cable: { area, circuits, amps, utilisation } | null, dropPct, lossKw, lossPct,
* checks: [{ id, pass, text, clause }], lines: [text], label }
* The route runs from the site (here) to the substation's landing on its fence.
*/
export function planConnection({ from, to, kv, mw = null, pf = CONNECT_PF, groundAt = () => 0, circuitGroupFactor = 0.8 }) {
if (!from || !to || ![from.e, from.n, to.e, to.n].every(Number.isFinite)) throw Error('planConnection needs two points in metres');
if (!CONNECT_KV.includes(kv)) throw Error(`no connection voltage of ${kv} kV`);
const ox = from.e, oy = from.n; // work local to the site so the route keeps its precision
const r = routeCable({ points: [[0, 0], [to.e - ox, to.n - oy]], depthBelowGround: 1.0, groundAt: (x, y) => groundAt(x + ox, y + oy), step: 25 });
const length = r.length3d ?? r.length2d ?? Math.hypot(to.e - ox, to.n - oy);
const out = { length, route: 'straight line (roads and field edges not yet followed)', kv, mw, pf, amps: null, cable: null,
dropPct: null, lossKw: null, lossPct: null, checks: [], lines: [], label: CONNECT_LABEL };
out.lines.push(`${kv} kV connection, ${fmtLen(length)} to the substation (straight line; a real route is longer)`);
if (!(mw > 0)) { out.lines.push('Add a size to rate the cable: connect here solar 50 at ' + kv); return out; }
const mva = mw / pf;
out.amps = mva * 1e6 / (Math.sqrt(3) * kv * 1000);
if (kv >= 275) {
out.lines.push(`${Math.round(out.amps)} A at ${kv} kV: transmission cable sizing is not modelled here (a bay by ducted, unjointed cable)`);
return out;
}
// Size: one circuit if one carries it, else parallel circuits with a stated grouping factor (own assumption).
let pick = null;
for (let n = 1; n <= MAX_CIRCUITS && !pick; n++) {
const opts = cableOpts(kv, n > 1 ? { groupFactor: circuitGroupFactor } : {});
const s = sizeFor(mva / n, opts);
if (s) pick = { ...s, circuits: n, opts };
}
if (!pick) {
out.checks.push({ id: 'rating', pass: false, clause: CLAUSES.rating, text: `No ${kv} kV cable here carries ${Math.round(out.amps)} A in ${MAX_CIRCUITS} circuits: connect at a higher voltage` });
out.lines.push(out.checks[0].text);
return out;
}
const { area, circuits, opts } = pick;
const rr = rating(area, opts);
out.cable = { area, circuits, amps: rr.amps, utilisation: pick.utilisation, metal: 'Al', insulation: 'XLPE', formation: 'trefoil' };
out.dropPct = dropPercent(area, length, mva / circuits, { ...opts, pf });
const iC = out.amps / circuits;
out.lossKw = 3 * iC * iC * rr.R * length * circuits / 1000; // I^2 R at the rated conductor temperature (upper bound)
out.lossPct = out.lossKw / (mw * 1000) * 100;
const statutory = kv >= 132 ? 10 : 6;
out.checks.push(
{ id: 'rating', pass: pick.utilisation <= 1, clause: CLAUSES.rating,
text: `${Math.round(iC)} A per circuit on ${circuits} x ${area} mm² Al XLPE trefoil rated ${Math.round(rr.amps)} A (${Math.round(pick.utilisation * 100)}%)` },
{ id: 'drop', pass: out.dropPct <= DROP_TARGET_PCT, clause: 'own early-design target',
text: `voltage drop ${out.dropPct.toFixed(2)}% against a ${DROP_TARGET_PCT}% design target` },
{ id: 'statutory', pass: out.dropPct <= statutory, clause: CLAUSES.drop,
text: `drop ${out.dropPct.toFixed(2)}% against the ±${statutory}% declared-voltage tolerance at ${kv} kV` });
out.lines.push(
`${mw} MW at pf ${pf}: ${Math.round(out.amps)} A; illustrative cable ${circuits > 1 ? circuits + ' x ' : ''}${area} mm² Al XLPE, trefoil, direct buried`,
`voltage drop ${out.dropPct.toFixed(2)}% · losses ${out.lossKw.toFixed(0)} kW (${out.lossPct.toFixed(2)}%) at full output`,
...out.checks.filter(c => !c.pass).map(c => `FAIL ${c.text} (${c.clause})`));
if (circuits > 1) out.lines.push(`grouping factor ${circuitGroupFactor} assumed for ${circuits} circuits (own assumption, not a tabled value)`);
return out;
}Elec Style
A JavaScript module in the engine folder of Energy Transition Simulator that works with elec CSS (`elecCss`).
Set aside from the main view: 93% of its lines are the same as solar-design-studio/202609271740-site-world/world/elec-style.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Elec Style; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9333 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/elec-style.mjs:1-34 0e2c74587200e9d9a9ecc7507e8836d3a231c59e
- sha256 cdafd5a17253fd9afe607a94c9c12d9b7da2c5b1e16c5fce66f55bfdc7c36c0e
- target sha256 cd214222fb0bae349b928c5841eb51e5ebdb03427b7706919fe2862ce6d9d150
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformenergy-transition-simulator / prototype/mod/engine/elec-style.mjs · lines 1–36 of 36 · Not reached from any entry point (candidate for review) · pattern elecCss (shared by 3 files)
- What it does
- It calculates its inputs. Defines rgba, elecCss.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 33kV, 1.5kV.
- Inputs & outputs
- Voltage levels named: 400kV, 33kV, 1.5kV.
- Downstream impact
- Used directly by 1 file: Single-Line Diagram (SLD) Rules (energy-transition-simulator).
- What it achieves
- It is built from the rgba step (`rgba`) and the elec CSS helper (`elecCss`). One table for what an electrical line looks like, by voltage level (e4 UI spec, section 3). Its code works with 1.5 kV, 33 kV and 400 kV.
- Why it matters
- Imported by Single-Line Diagram (SLD) Rules.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- none found
- Used by
- imported by Single-Line Diagram (SLD) Rules (import)
- Produces
- ELEC_CLASSES, ELEC, ELEC_FOOTER, rgba, elecCss
- Defines here
- rgba, elecCss
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/elec-style.mjs:1-36 · blob b451e7d789517af42e3270f24f476d6e3792cc16 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/elec-style.mjs) at v12 commit 3adcee9 (file last changed fdfcbc4). Modular star family: public #148422 rgba.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// elec-style.mjs: one table for what an electrical line looks like, by voltage level (e4 UI spec, section 3). The 3D
// symbols (sld-symbols.mjs), the solar block's cables (block-ui.mjs, block-gpu.mjs), the SLD panel's classes
// (sld-view.mjs) and the legend (legend-ui.mjs) all read it; no hex colour for an electrical class lives anywhere else.
// Colour means voltage level; red means only "open" or "check". Earth has its own colour and always a dash as well, so it
// reads without colour (colour-blind, print). Conductor-core identification colours are for core labels in text only.
// Pure: no DOM.
// key, words for the legend, colour, SVG dash (null: solid), SLD class.
export const ELEC_CLASSES = Object.freeze([
{ key: 'hv', label: 'HV AC, 132 / 275 / 400 kV', hex: '#9cdbff', dash: null, cls: 'ln' },
{ key: 'mv', label: '33 kV collection', hex: '#ffa050', dash: null, cls: 'mv' },
{ key: 'lv', label: 'LV AC, inverter to station', hex: '#8cffa0', dash: null, cls: 'lv' },
{ key: 'dc', label: 'DC strings and home runs, 1.5 kV class', hex: '#d59cff', dash: null, cls: 'dc' },
{ key: 'earth', label: 'Earth conductors and electrodes', hex: '#d8d89a', dash: '6 3', cls: 'ea' },
{ key: 'bond', label: 'Bonding links', hex: '#d8d89a', dash: '2 3', cls: 'bd' },
{ key: 'open', label: 'Normally-open point, open switch', hex: '#ff5a4a', dash: '5 4', cls: 'op' },
{ key: 'glow', label: 'Follow path', hex: '#c0ffff', dash: null, cls: 'hl' }
].map(Object.freeze));
export const ELEC = Object.freeze(Object.fromEntries(ELEC_CLASSES.map(c => [c.key, c])));
// Every electrical readout ends with this line (re-exported by sld-rules.mjs for the earthing and SLD readouts).
export const ELEC_FOOTER = 'Illustrative — early design, no warranty; confirm with a qualified engineer.';
/** rgba('dc', 0.9) -> [r, g, b, a] in 0..1, for a line batch. */
export function rgba(key, a = 1) {
const h = ELEC[key]?.hex;
if (!h) throw Error('elec-style: no class ' + key);
return [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16) / 255).concat(a);
}
/** CSS for an SVG drawing under `scope`: each class's stroke and dash, from the table. */
export const elecCss = scope => ELEC_CLASSES.filter(c => c.key !== 'glow')
.map(c => `${scope} .${c.cls} { stroke: ${c.hex};${c.dash ? ` stroke-dasharray: ${c.dash};` : ''} }`).join('\n');Fault Level
A JavaScript module in the engine folder of Energy Transition Simulator that works with transformers. It is built from the transformer fault ka helper (`transformerFaultKA`).
electricalenergy-transition-simulator / prototype/mod/engine/fault-level.mjs · lines 1–14 of 14 · Not reached from any entry point (candidate for review) · pattern transformerFaultKA (shared by 3 files)
- What it does
- It calculates transformers. Defines transformerFaultKA.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: transformers.
- Downstream impact
- Used directly by 2 files: Cmd Trench (energy-transition-simulator); LV DC Sizing (energy-transition-simulator).
- What it achieves
- Prospective fault current at a solar block's LV board, by the impedance method. Its code works with 5 MVA.
- Why it matters
- Imported by Cmd Trench and LV DC Sizing.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- none found
- Used by
- imported by Cmd Trench (import), imported by LV DC Sizing (import)
- Produces
- TX_FAULT, transformerFaultKA
- Defines here
- transformerFaultKA
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/fault-level.mjs:1-14 · blob a3f94b86a817e66889d6c2d5e1681230ddce48a7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// COPIED UNCHANGED from the v12 world (web/world/fault-level.mjs) at v12 commit 3adcee9 (file last changed a36f410). Modular star family: public #148423 transformerFaultKA.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// fault-level.mjs: prospective fault current at a solar block's LV board, by the impedance method. Pure: no imports, no DOM.
// The transformer alone gives S / (sqrt3 U z); the inverters add their own limited contribution (1.2 x rated, assumed).
// zPct is an assumption (typical for a 5 MVA unit) until the maker's test certificate gives it. Own formula, no table.
export const TX_FAULT = Object.freeze({ mva: 5, volts: 800, zPct: 7, inverters: 14, inverterKva: 352, inverterMult: 1.2, seconds: 0.2 });
/** transformerFaultKA(o) -> kA at the LV board (transformer plus inverters). */
export function transformerFaultKA(o = {}) {
const p = { ...TX_FAULT, ...o }, tx = p.mva * 1e6 / (Math.sqrt(3) * p.volts * p.zPct / 100);
const inv = p.inverters * p.inverterKva * 1000 / (Math.sqrt(3) * p.volts) * p.inverterMult;
return (tx + inv) / 1000;
}Journey
A JavaScript module in the engine folder of Energy Transition Simulator that works with go to (`goTo`) and calculates planar distances (units: kV), covering substations.
Set aside from the main view: 97% of its lines are the same as energy-transition-simulator/202609280014/mod/engine/journey.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Journey; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9737 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/journey.mjs:1-90 929480be644a8b9c66cdcbf209f6aaf2a971aca6
- sha256 f03dd0a486f397c2ffa263d03e1b4fd2e1d9f16f233013dd83a9218d020a29f2
- target sha256 e76d490c3ebc01b6279d013047af04d646c5c226d4aeb2504090052b36968850
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
renderenergy-transition-simulator / prototype/mod/engine/journey.mjs · lines 1–90 of 90 · Not reached from any entry point (candidate for review) · pattern createJourney (shared by 2 files)
- What it does
- It lists and searches substations. Defines 9 functions or classes, including parseJourney, standAt, kvText, cardText, createJourney. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: substations, 132kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 132kV.
- Downstream impact
- Used directly by 1 file: Sub Grammar (energy-transition-simulator).
- What it achieves
- It is built from the stand at helper (`standAt`), the kV text helper (`kvText`) and the card text helper (`cardText`). The first step of the journey (owner direction 8): "go substation 132" goes to the nearest substation that works at 132kV (or 400, 275, 66, 33, 11) and stands you outside its real compound fence (the footprints, lib.compound). Its code works with 132 kV.
- Why it matters
- Imported by Sub Grammar.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- Bng (import)
- Used by
- imported by Sub Grammar (import)
- Produces
- STAND_BACK_M, STAND_PITCH, KV_WORDS, parseJourney, standAt, cardText, createJourney
- Defines here
- parseJourney, standAt, kvText, cardText, createJourney, here, $, show, goTo
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/journey.mjs:1-90 · blob 2ae3b28bcd448f530a09a80b8d844096e90fafdb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/journey.mjs) at v12 commit 3adcee9 (file last changed f0fe9c2). Modular star family: public #133195 cardText.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// journey.mjs: the first step of the journey (owner direction 8): "go substation 132" goes to the nearest substation that
// works at 132 kV (or 400, 275, 66, 33, 11) and stands you outside its real compound fence (the footprints, lib.compound),
// looking in; "next substation" goes on to the next nearest at the same voltage. The place card says what it is: its
// levels, its network tier and where the outline came from. No names: the national index holds none, and the card shows
// voltages and the tier only. Levels come from OSM voltage tags (surveyed 27 Sept, ODbL); where a substation was not
// surveyed only the index's top voltage is known, and the card says so.
import { gridRef } from './bng.mjs';
export const STAND_BACK_M = 20; // stand this far outside the fence point, looking in
export const STAND_PITCH = -0.3; // radians below level: about 6 m eye height at 20 m back
export const KV_WORDS = [400, 275, 220, 132, 66, 33, 22, 11];
const CONF_WORDS = {
measured: 'outline confirmed by LiDAR', operator: 'outline from the network operator', osm: 'outline from OpenStreetMap',
'os-building': 'outline from an OS building only (weak)', assumed: 'size assumed for the voltage'
};
// Pure: a typed line -> { kv } | { next: true } | { error } | null (not a journey line).
export function parseJourney(line) {
const t = String(line || '').toLowerCase().replace(/\s+/g, ' ').trim();
if (/^next (substation|sub)$/.test(t)) return { next: true };
const m = t.match(/^(?:go|go to|fly to|goto) (?:substation|sub)(?: (\d+(?:\.\d+)?) ?(kv)?)?$/);
if (!m) return null;
if (!m[1]) return { error: `go substation takes a voltage in kV: ${KV_WORDS.join(', ')} (e.g. go substation 132)` };
const kv = Number(m[1]);
return kv > 0 && kv < 1000 ? { kv } : { error: `${m[1]} is not a voltage in kV` };
}
// Pure: where to stand for substation s (s.e, s.n, s.fp) given the landing on its fence (lib.compound landing(), or the
// index point where there is no outline): flyTo(e, n, opts) looks at the fence point from STAND_BACK_M outside it.
export function standAt(s, land) {
const lx = land?.e ?? s.e, ly = land?.n ?? s.n;
let dx = s.e - lx, dy = s.n - ly;
if (Math.hypot(dx, dy) < 0.5) { dx = 0; dy = 1; } // no fence point: look north at the index point
const yaw = Math.atan2(dx, dy); // heading from the fence point to the centre
return { e: lx, n: ly, opts: { yaw, back: STAND_BACK_M, pitch: STAND_PITCH },
eye: { e: lx - STAND_BACK_M * Math.sin(yaw), n: ly - STAND_BACK_M * Math.cos(yaw) } };
}
const kvText = v => (Number.isInteger(v) ? String(v) : String(Math.round(v * 10) / 10));
// Pure: the card's two lines for substation s reached at kv: { name, detail }.
export function cardText(s, kv, d, land) {
const lv = Array.isArray(s.levels) && s.levels.length ? s.levels : null;
const name = lv && lv.length > 1 ? `${kvText(kv)} kV substation (${lv.map(kvText).join('/')} kV)` : `${kvText(kv)} kV substation`;
let ref = '';
try { ref = gridRef(s.e, s.n, 8); } catch { /* off the national grid */ }
const bits = [ref, s.tier ? `${s.tier} tier` : '', lv ? 'levels from OSM voltage tags' : 'top voltage only (not surveyed)',
s.fp ? (CONF_WORDS[s.fp.conf] || 'outline') + (land?.fence ? `, at the ${land.side ? land.side + ' ' : ''}fence` : '') : 'no outline: at the index point',
Number.isFinite(d) ? `${d >= 1000 ? (d / 1000).toFixed(1) + ' km' : Math.round(d) + ' m'} from where you were` : '',
'© OpenStreetMap contributors, ODbL'];
return { name, detail: bits.filter(Boolean).join(' · ') };
}
// deps: { world (window.world), grid () -> the live grid layer, doc }. Keeps the voltage and the substations visited, so
// "next substation" moves on without going back.
export function createJourney({ world, grid, doc = globalThis.document }) {
let kv = null, seen = [], last = null;
const here = () => { const s = world.state(), o = world.origin(); return { e: o.e + s.pos[0], n: o.n + s.pos[1] }; };
const $ = id => doc?.getElementById?.(id);
function show(card) {
if (!$('place')) return;
$('place-name').textContent = card.name; $('place-grid').textContent = card.detail; $('place-terrain').textContent = '';
$('place').hidden = false;
}
async function goTo(v, fresh) {
const G = grid();
if (!G?.substationsAtKv) return 'The grid layer is not loaded here: turn on Grid in Layers, then try again.';
const from = here();
const [hit] = await G.substationsAtKv(from.e, from.n, v, { skip: fresh ? [] : seen });
if (!hit) return fresh ? `No ${kvText(v)} kV substation in the national index.` : `No more ${kvText(v)} kV substations to visit.`;
const s = hit.s, C = G.compoundLib?.();
const land = C && s.fp ? C.landing(s, from.e, from.n) : null;
const st = standAt(s, land);
kv = v; seen = fresh ? [s.id] : [...seen, s.id];
last = { id: s.id, e: s.e, n: s.n, kv: v, levels: s.levels || null, tier: s.tier, conf: s.fp?.conf || null,
fence: !!land?.fence, side: land?.side || null, stand: st, d: hit.d };
world.flyTo(st.e, st.n, st.opts);
const card = cardText(s, v, hit.d, land);
show(card);
return `${card.name}: ${card.detail}.`;
}
return {
go: v => goTo(v, true),
next: () => (kv == null ? 'Type go substation 132 (or 400, 275, 66, 33, 11) first.' : goTo(kv, false)),
last: () => (last ? { ...last } : null), visited: () => [...seen]
};
}