In this section
- Kuiper Programs render · globalgrid2050 / kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js lines 1121–1820
Kuiper Programs
A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.
Set aside from the main view: 99% of its lines are the same as kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9873 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js:1-4690 56db141d495fee7c1255ae88d29ac3f7a5fb8724
- sha256 daff29fbdd867ff327ebc8c6c1338405afe422e1722b551bf8a6898ccb31880f
- target sha256 71eba91ad4eea2f2602c4ca3427ad22b95e0514f9e9087cd231ed7dcf5fa4633
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
renderglobalgrid2050 / kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js · lines 1121–1820 of 4659 (continued from section 1392) · Not reached from any entry point (candidate for review) · pattern drawLocalSystem (shared by 2 files)
- What it does
- It draws interconnectors, london underground, grid 66kV and motorway services. Defines 253 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: interconnectors, 750kV, 400kV, 275kV, 132kV, 110kV.
- Inputs & outputs
- In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 110kV, 66kV, 50kV, 33kV.
- What it achieves
- It makes body (`makeBody`), sets tag (`setTag`) and draws tube map (`drawTubeMap`). A cartridge of the Kuiper shell. Its code works with 33 kV, 11 kV and 275 kV. It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · kuiper-grid/i0088/cartridges · script
- Uses
- Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
- Used by
- mentioned in Standalone (comment link)
- Produces
- reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
- Defines here
- mergeMenu, makeAppButtons, isolateNow, isolate, raiseTile, endIsolate, unisolate, appCard, closeCard, codeWindow, lh, padTop, place, rate, r, need, parse, fire, register, standardSite, add, mul, div, conj, rnd, solve, sitePulse, signed, mulberry32, network
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js:1121-1820 · blob d98009f128a079f2699fc0e940870cfd978bea61 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
}
// ===== GRID TUBE MAP: END =======================================================================
function mergeMenu(){
for (const m of MENU) {
if (m.override) { const a = apps.find(x => x.app === m.app.app), p = programs.find(x => x.name === m.program.name);
if (a) Object.assign(a, m.app); if (p && m.program.end) p.end = m.program.end;
if (a && m.program.says) whatItDoes[a.live] = m.program.says.replace(/\.$/, ''); continue; }
if (!apps.find(x => x.app === m.app.app)) apps.push(m.app);
if (!programs.find(x => x.name === m.program.name)) programs.push(m.program);
if (m.program.says && !whatItDoes[m.app.live]) whatItDoes[m.app.live] = m.program.says.replace(/\.$/, '');
if (!(appWork[m.app.app] || []).length) { const ri = repos.findIndex(r => r.name === m.program.select.repository);
appWork[m.app.app] = ri < 0 ? [] : commits.filter(c => c.repo === ri).map(c => c.sha); }
}
}
function makeAppButtons(){
mergeMenu();
const bar = document.getElementById('apps'); bar.replaceChildren();
for (const pr of programs) { const ap = apps.find(x => x.app === pr.select.app);
if (!ap || !(appWork[ap.app] || []).length) continue; // nothing of it on this record: no button
const b = el('button', null, pr.button); b.type = 'button'; b.setAttribute('data-app', pr.name);
b.addEventListener('click', e => { e.stopPropagation(); isolate(pr.name); }); bar.append(b); }
if (typeof layout === 'function') layout();
makeFireBar();
}
// THE STATE ITSELF, with no animation, so it can be arrived at by a link and asked for by a test.
function isolateNow(name, front){
const asData = programs.find(x => x.name === name); if (!asData) return null;
const prog = Object.assign({}, asData, { on:Object.assign({}, asData.on, { colour:FARADAY }) });
const ap = apps.find(x => x.app === prog.select.app); if (!ap) return null;
name = ap.app;
const idx = []; for (const sha of (appWork[name] || [])) { const i = bySha.get(sha); if (i !== undefined) idx.push(i); }
idx.sort((x, y) => x - y);
litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; litPath = null; target = null; arrow = null;
iso = { app:ap, prog, front:front === undefined ? 1e30 : front, idx, set:new Set(idx), lit:idx.length, dark:commits.length - idx.length,
first:idx.length ? commits[idx[0]].unix : 0, last:idx.length ? commits[idx[idx.length - 1]].unix : 0 };
raiseFlags(idx);
{ // A FEW SPARKS FOR EVERY PIECE OF WORK, spread through its own lines so a big piece of work is a
// scatter around its ring and a small one a point or two. Never more than the program allows.
const per = Math.max(1, Math.min(24, (prog.on.sparks | 0) || 8)), pts = [];
for (const i of idx) { const c0 = commits[i], len = Math.max(1, c0.k1 - c0.k0), take = Math.min(per, len);
for (let j = 0; j < take; j++) { const p = keyPlace(c0.k0 + Math.floor((j + 0.5) * len / take)); pts.push(p[0], p[1]); } }
ensureGlow();
iso.from = new Float32Array(pts); iso.pos = iso.from; iso.to = null;
glowCount = pts.length / 2; iso.sparks = glowCount; sparksTo(iso.from); }
body = makeBody(iso);
// arrived at by a link, or asked for outright: the END of the program, with no waiting
if (front === undefined && body) bodyJump(body.states.length - 1);
for (const b of document.querySelectorAll('#apps button')) b.classList.toggle('on', b.getAttribute('data-app') === prog.name);
if (front === undefined) raiseTile();
dirty = true;
return iso;
}
// PRESS: the pulse runs out through the record, which on this picture is forward through time, and
// where it has passed the rest goes dark. The pulse is the page's own; nothing new is animated.
function isolate(name){
const prog = programs.find(x => x.name === name); if (!prog) return;
closeCard(); { const fc = document.getElementById('firecard'); if (fc && name !== 'fire') fc.style.display = 'none'; } // the answer of a fired command leaves with it
unisolate(true); anim = null; flash = 0; newFrom = -1; target = null; arrow = null;
{ const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; atHome = true; }
// the selection is made at once and the FRONT starts at the origin with nothing switched; each dot
// switches when the front reaches it, so the darkening is seen to travel
if (!isolateNow(name, 0)) return;
bodyAnim = null; if (body) body.shown = false;
isoAnim = { name, t0:performance.now(), R:Math.sqrt(SPACE), ms:Math.max(200, (prog.pulse.seconds || 1.5) * 1000) }; dirty = true;
}
function raiseTile(){ if (!iso || !(iso.prog.end && iso.prog.end.tile)) return;
// A SYSTEM ENDS ON THE SAME CARD with its own plain words under it; everything else is unchanged.
if (iso.prog.end.tile === 'system' && systemShown) { systemCard(iso, systemShown);
if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; return; }
appCard(iso); if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; }
// ANY OTHER ACTION FIRST ENDS THE ISOLATE. Called by everything that shows something else, before it
// does anything, so the darkening can never outlive the thing it was for.
function endIsolate(){ if (iso || isoAnim || bodyAnim) { unisolate(true); closeCard(); } }
function unisolate(quiet){ labels(true); sldNow = null; sldNames = null; { const el = document.getElementById('sldnames'); if (el) el.replaceChildren(); }
if (typeof shapesGone === 'function') shapesGone();
if (sldLoop) { cancelAnimationFrame(sldLoop); sldLoop = 0; } iso = null; isoAnim = null; gatherAnim = null; homeAnim = null; body = null; bodyAnim = null; pulse = -1;
for (const b of document.querySelectorAll('#apps button')) b.classList.remove('on');
if (!quiet) dirty = true; }
// THE TILE OF AN ISOLATED APPLICATION: its name, what it does for a project, OPEN. Then how much of
// the record is lit and how much has gone dark, because the two must make the whole.
function appCard(st){
cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
card.classList.add('short');
const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
x.addEventListener('click', () => { card.style.display = 'none'; dirty = true; });
const t = el('a', 'cc-tile cc-app'); t.href = st.app.live; t.target = '_blank'; t.rel = 'noopener'; t.setAttribute('data-app', st.app.app);
t.append(el('div', 'cc-tile-name', st.app.button));
if (whatItDoes[st.app.live]) t.append(el('div', 'cc-tile-what', whatItDoes[st.app.live] + '.'));
t.append(el('span', 'cc-tile-open', 'OPEN ' + st.app.button));
const brand = el('div', 'scada-brand'), inner = el('div');
inner.append(el('div', 'scada-brand-main', 'Ventus'), el('div', 'scada-brand-sub', 'Cables & Connectivity\u00ae')); brand.append(inner);
const plain = el('div', 'cc-plain cc-count', fmt(st.lit) + ' pieces of work lit, ' + fmt(st.dark) + ' gone dark, '
+ fmt(st.lit + st.dark) + ' in all \u00b7 ' + day(st.first) + ' to ' + day(st.last));
card.append(x, t, brand, plain);
if (!ASM && asmWhy) card.append(el('div', 'cc-refuse', 'The gathering could not be loaded, so this work stays where it is: ' + asmWhy));
if (typeof layout === 'function') layout();
}
function closeCard(){ cardToken++; card.style.display = 'none'; card.replaceChildren();
target = null; cardShown = null; dirty = true; }
addEventListener('keydown', e => {
if (e.key === 'Escape' && card.style.display !== 'none') { e.preventDefault(); closeCard(); } });
function codeWindow(lines, a, b, at){
const pre = el('pre', 'cc-code');
pre.setAttribute('aria-label', 'the code around this line');
const bar = el('div', 'cc-hi cc-hi-target');
const out = [];
for (let i = a; i <= b; i++) out.push(String(i).padStart(6) + ' ' + lines[i - 1]);
pre.append(bar, document.createTextNode(out.join('\n')));
const lh = () => parseFloat(getComputedStyle(pre).lineHeight) || 16;
const padTop = () => parseFloat(getComputedStyle(pre).paddingTop) || 0;
const place = () => { bar.style.top = (padTop() + (at - a) * lh()) + 'px'; bar.style.height = lh() + 'px'; };
return { node:pre, bar, place, first:a, last:b, at,
scrollToTarget(){ place(); pre.scrollTop = Math.max(0, (at - a) * lh() - pre.clientHeight/2 + lh()/2); } };
}
// WHAT A TAP OPENS. One way in for every kind of answer: the work and the day it was done, a state
// chip saying how much of it is proved, and, where the code for that line is carried on this site,
// the code itself with the tapped line marked. Nothing here sends a reader to GitHub to READ code;
// the link is there for the detail and the history, which is what GitHub is good for.
// ===== THE COMMANDS THAT RUN ON THE VISITOR'S DEVICE: Ventusltd/faraday bench/fire.js and bench/fire_site.js, carried whole ==========
// Checked against every saved record by faraday bench/fire_check.mjs (2,278 of 2,278). Carried inside this file so the pointer's hash covers them.
// bench/fire.js - the pop commands that RUN IN THE VISITOR'S BROWSER. Plain JavaScript, no library, nothing leaves the device.
// Each function is a port of the Python in bench/*_cases.py and is checked against the saved records by bench/fire_check.mjs:
// same inputs, same numbers, or the port is wrong. A command is: fire <name> {inputs as JSON}
(function (root) {
const R20 = { al: { 50: 0.641, 70: 0.443, 95: 0.320, 120: 0.253, 150: 0.206, 185: 0.164, 240: 0.125, 300: 0.100, 400: 0.0778, 500: 0.0605, 630: 0.0469 },
cu: { 50: 0.387, 70: 0.268, 95: 0.193, 120: 0.153, 150: 0.124, 185: 0.0991, 240: 0.0754, 300: 0.0601, 400: 0.0470, 500: 0.0366, 630: 0.0283 } };
const K = { al: 94.0, cu: 143.0 }, ALPHA = { al: 0.00403, cu: 0.00393 };
const RATE_AL = { 50: 150, 70: 185, 95: 220, 120: 250, 150: 280, 185: 320, 240: 370, 300: 420, 400: 480, 500: 545, 630: 615 };
const rate = (m, s) => m === 'al' ? RATE_AL[s] : Math.round(RATE_AL[s] * 1.28);
// as Python's round(): the number as it is actually held decides; only an EXACT half goes to the even side
const r = (x, d) => { const up = Number(x.toFixed(d)), t = Math.abs(x).toFixed(d + 25), tail = t.slice(t.indexOf('.') + 1 + d);
if (!/^50*$/.test(tail)) return up;
const k = Math.pow(10, d), n = Math.round(Math.abs(up) * k); return n % 2 === 0 ? up : Number((up - Math.sign(x) / k).toFixed(d)); };
const need = (o, keys) => { for (const k of keys) if (o[k] === undefined) throw new Error('this command needs "' + k + '"'); };
const RUN = {
'cable-withstand': { family: 'CABLE CHECK', run(i) { need(i, ['metal', 'size_mm2', 'seconds', 'fault_ka']);
if (!K[i.metal]) throw new Error('metal is "al" or "cu"');
const limit = K[i.metal] * i.size_mm2 / Math.sqrt(i.seconds) / 1000, ok = i.fault_ka <= limit;
return { numbers: { withstand_ka: r(limit, 2), fault_ka: i.fault_ka, margin_pct: r((limit / i.fault_ka - 1) * 100, 1) },
said: 'withstands ' + limit.toFixed(2) + ' kA; asked for ' + i.fault_ka + ' kA: ' + (ok ? 'survives' : 'DOES NOT SURVIVE: a larger conductor or faster protection'),
how: 'adiabatic rule: k x area / square root of time, k = ' + K[i.metal] }; } },
'cable-run': { family: 'CABLE CHECK', run(i) { need(i, ['metal', 'size_mm2', 'amps', 'metres', 'kv', 'derate']);
if (!R20[i.metal] || !R20[i.metal][i.size_mm2]) throw new Error('sizes: ' + Object.keys(R20.al).join(', ') + ' mm2; metal "al" or "cu"');
const rh = R20[i.metal][i.size_mm2] * (1 + ALPHA[i.metal] * 70), x = 0.08;
const vd = Math.sqrt(3) * i.amps * (rh * 0.95 + x * Math.sqrt(1 - 0.95 * 0.95)) * i.metres / 1000, pct = vd / (i.kv * 1000) * 100;
const use = i.amps / (rate(i.metal, i.size_mm2) * i.derate) * 100, flags = [];
if (use > 100) flags.push('over its derated rating'); else if (use > 85) flags.push('within 15 per cent of its derated rating: commission a buried cable thermal study');
if (pct > 1.5) flags.push('voltage drop ' + pct.toFixed(2) + '% is over 1.5%');
return { numbers: { volt_drop_pct: r(pct, 3), loading_pct: r(use, 1), loss_kw: r(3 * i.amps * i.amps * rh * i.metres / 1000 / 1000, 2) },
said: 'drop ' + pct.toFixed(2) + '%, loaded to ' + use.toFixed(0) + '% of its derated rating; ' + (flags.length ? flags.join('; ') : 'inside both limits'),
how: 'resistance at 20 C raised to 90 C; drop = root three x amps x (r cos + x sin) x length; rating x derating (ratings are CANDIDATE round figures)' }; } },
'national-day': { family: 'NATIONAL DAY', run(i) { need(i, ['firm_gw', 'round_trip']);
const raw = []; for (let h = 0; h < 48; h++) raw.push(24.25 + 6.25 * Math.sin(Math.PI * (h / 2 - 7) / 12));
const k = 604 / (raw.reduce((a, b) => a + b, 0) / 2), d = raw.map(v => v * k);
const short = d.reduce((a, v) => a + Math.max(0, v - i.firm_gw), 0) / 2, spare = d.reduce((a, v) => a + Math.max(0, i.firm_gw - v), 0) / 2, inp = short / i.round_trip;
return { numbers: { storage_delivers_gwh: r(short, 1), must_be_put_in_gwh: r(inp, 1), spare_generation_that_day_gwh: r(spare, 1), day_low_gw: r(Math.min(...d), 1), day_high_gw: r(Math.max(...d), 1) },
said: 'storage delivers ' + short.toFixed(0) + ' GWh and needs ' + inp.toFixed(0) + ' GWh put in; the steady generation has ' + spare.toFixed(0) + ' GWh to spare that day: ' + (spare >= inp ? 'enough to refill it' : 'NOT enough to refill it'),
how: '48 half hours of a 604 GWh spring day; demand above the steady generation comes from storage' }; } },
'dc-traction-chain': { family: 'DC TRACTION', run(i) { need(i, ['inverter', 'transformer', 'rectifier', 'dc_converter']);
const ac = i.inverter * i.transformer * i.rectifier, s = i.dc_converter - ac;
return { numbers: { reaches_rail_by_ac_route_pct: r(ac * 100, 2), reaches_rail_by_dc_route_pct: r(i.dc_converter * 100, 2), saved_pct_of_the_solar: r(s * 100, 2) },
said: (ac * 100).toFixed(1) + '% arrives by the usual route, ' + (i.dc_converter * 100).toFixed(1) + '% by the direct route: ' + (s * 100).toFixed(1) + '% of the SOLAR is saved',
how: 'multiplied the efficiencies along each route' }; } },
'dc-traction-scale': { family: 'DC TRACTION', run(i) { need(i, ['solar_gwh', 'saving_share']);
const traction = 1216 * 0.825, saved = i.solar_gwh * i.saving_share;
return { numbers: { traction_gwh: r(traction, 1), saved_gwh: r(saved, 2), solar_share_of_traction_pct: r(i.solar_gwh / traction * 100, 1), average_kw_per_substation: Math.round(traction * 1e6 / 300 / 8760) },
said: 'saves ' + saved.toFixed(1) + ' GWh a year; the solar is ' + (i.solar_gwh / traction * 100).toFixed(1) + '% of traction energy',
how: 'traction = total x 82.5%; saving = solar x share saved' }; } },
};
function parse(text) {
const m = String(text).trim().match(/^fire\s+([a-z0-9-]+)\s*(\{[\s\S]*\})?\s*$/i);
if (!m) throw new Error('a command looks like: fire cable-withstand {"metal":"al","size_mm2":185,"seconds":1,"fault_ka":16}');
let inputs = {}; if (m[2]) { try { inputs = JSON.parse(m[2]); } catch (e) { throw new Error('the part in { } is not valid: ' + e.message); } }
return { name: m[1].toLowerCase(), inputs };
}
function fire(text) { const c = parse(text), f = RUN[c.name]; if (!f) return { name: c.name, inputs: c.inputs, ran: false }; const o = f.run(c.inputs); return Object.assign({ name: c.name, inputs: c.inputs, ran: true, family: f.family, boxes: f.inputs || null }, o); }
// another file may add commands: FIRE.register('site-pulse', 'SITE PULSE', inputs => ({ numbers, said, how }), boxes)
// EVERY COMMAND DECLARES ITS OWN INPUTS, and that declaration is part of the protocol, not an extra:
// { key, label, unit, kind:'number'|'choice', min, max, step, choices:[[value, words], ...] }
// The window builds a labelled box for each one, so a command written next year gets its boxes free.
function register(name, family, run, inputs) { RUN[name] = { family, run, inputs: inputs || null }; }
root.FIRE = { fire, parse, register, inputsOf: n => (RUN[n] && RUN[n].inputs) || null, get names() { return Object.keys(RUN); } };
if (typeof module !== 'undefined') module.exports = root.FIRE;
})(typeof window !== 'undefined' ? window : globalThis);
// bench/fire_site.js - SITE PULSE in the visitor's browser: a port of solve() and record() in bench/site_cases.py.
// Plain JavaScript, no library. JavaScript has no complex numbers, so every volt, amp and ohm is a pair [re, im].
// Checked against every saved SITE PULSE and SITE SURVEY record by bench/fire_check.mjs. Load after fire.js.
(function (root) {
const CANDIDATE = { kv: 11.0, grid_fault_mva: 150.0, grid_x_over_r: 10.0, hv_cable_r: 0.20, hv_cable_x: 0.09, tx_z_pct: 5.5, tx_x_over_r: 5.0,
load_pf: 0.90, gen_pf: 0.95, pv_pf: 1.0, volts_high_pu: 1.06, volts_low_pu: 0.94, inverter_fault_x_rated: 1.1, generator_subtransient_pu: 0.15 };
const SCENARIOS = { 1: ['no solar, no generator', 0.0, false, []], 2: ['no solar, generator running', 0.0, true, []],
3: ['solar at full output, no generator', 1.0, false, []], 4: ['solar at full output, generator running', 1.0, true, []],
5: ['solar at half output, no generator', 0.5, false, []], 6: ['solar at half output, generator running', 0.5, true, []],
7: ['solar at full output, the tenant substation disconnected', 1.0, false, ['tenant']],
8: ['solar at full output, the tenant substation and the load beside the solar both disconnected', 1.0, false, ['tenant', 'pvload']] };
const standardSite = () => ({ intake_cable_km: 0.6, export_limit_kw: 500.0, generator_kw: 500.0, pv_kw: 1000.0, pv_on: 4,
subs: [{ n: 1, kva: 1600, load_kw: 900, km: 0.15 }, { n: 2, kva: 1000, load_kw: 550, km: 0.25 }, { n: 3, kva: 1000, load_kw: 500, km: 0.35 },
{ n: 4, kva: 1000, load_kw: 350, km: 0.45 }, { n: 5, kva: 800, load_kw: 300, km: 0.30, tenant: true }] });
// pairs
const add = (a, b) => [a[0] + b[0], a[1] + b[1]], sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
const mul = (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
const div = (a, b) => { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; };
const conj = a => [a[0], -a[1]], scale = (a, k) => [a[0] * k, a[1] * k], mag = a => Math.hypot(a[0], a[1]);
const rnd = (x, d) => Number(x.toFixed(d)); // decimal rounding of the value held, as Python's round does
function solve(site, pvShare, genOn, off, loadShare, c, tol) {
c = c || CANDIDATE; tol = tol || 1e-9; off = off || []; if (loadShare === undefined) loadShare = 1.0;
const vb = c.kv * 1000 / Math.sqrt(3);
const zsMag = (c.kv ** 2) / c.grid_fault_mva, xr = c.grid_x_over_r, rs = zsMag / Math.sqrt(1 + xr * xr);
const Z = { poc: [rs, rs * xr], board: scale([c.hv_cable_r, c.hv_cable_x], site.intake_cable_km) };
const parent = { grid: null, poc: 'grid', board: 'poc' }, S = {}, kva = {};
const tanl = Math.tan(Math.acos(c.load_pf)), tang = Math.tan(Math.acos(c.gen_pf));
if (genOn) S.board = scale([site.generator_kw, site.generator_kw * tang], -1000 / 3);
for (const s of site.subs) {
if (off.includes('tenant') && s.tenant) continue; // a disconnected substation is not in the network at all
const hv = 'hv' + s.n, lv = 'lv' + s.n; parent[hv] = 'board'; parent[lv] = hv;
Z[hv] = scale([c.hv_cable_r, c.hv_cable_x], s.km);
const zt = c.tx_z_pct / 100 * (c.kv ** 2) / (s.kva / 1000), txr = c.tx_x_over_r, rt = zt / Math.sqrt(1 + txr * txr);
Z[lv] = [rt, rt * txr]; kva[lv] = s.kva;
const kw = (off.includes('pvload') && s.n === site.pv_on) ? 0.0 : s.load_kw * loadShare;
let p = [kw, kw * tanl];
if (s.n === site.pv_on) p = sub(p, [site.pv_kw * pvShare, 0]);
S[lv] = scale(p, 1000 / 3);
}
const kids = {};
for (const n of Object.keys(parent)) if (parent[n] !== null) (kids[parent[n]] = kids[parent[n]] || []).push(n);
const order = ['grid'];
for (let i = 0; i < order.length; i++) order.push(...(kids[order[i]] || []));
let V = {}; for (const n of order) V[n] = [vb, 0];
let rounds = 0, J;
for (;;) {
rounds++;
J = {}; for (const n of order) J[n] = S[n] ? conj(div(S[n], V[n])) : [0, 0];
for (let i = order.length - 1; i >= 0; i--) { const n = order[i]; if (parent[n] !== null) J[parent[n]] = add(J[parent[n]], J[n]); } // PULSE ONE: currents sum back toward the grid
const nv = { grid: [vb, 0] };
for (const n of order.slice(1)) nv[n] = sub(nv[parent[n]], mul(J[n], Z[n])); // PULSE TWO: volts fall (or rise) out from the grid
let step = 0; for (const n of order) step = Math.max(step, mag(sub(nv[n], V[n])));
V = nv;
if (step < tol || rounds > 300) break;
}
const sPoc = scale(mul(V.poc, conj(J.poc)), 3); // + import, - export, in volt amperes
let loss = 0; for (const n of order.slice(1)) loss += mag(J[n]) ** 2 * Z[n][0]; loss *= 3;
let net = 0; for (const n of Object.keys(S)) net += S[n][0]; net *= 3;
const source = mul(V.grid, conj(J.poc))[0] * 3;
const tx = {}; for (const n of Object.keys(kva)) tx[n] = mag(scale(mul(V[n], conj(J[n])), 3)) / 1000 / kva[n] * 100;
const lv = 'lv' + site.pv_on; let faultKa = null;
if (Z[lv]) {
const zpath = add(add(Z.poc, Z.board), add(Z['hv' + site.pv_on], Z[lv]));
const iGrid = vb / mag(zpath);
const iPv = c.inverter_fault_x_rated * site.pv_kw * pvShare * 1000 / (Math.sqrt(3) * c.kv * 1000);
const iGen = genOn ? (site.generator_kw / c.gen_pf * 1000 / (Math.sqrt(3) * c.kv * 1000) / c.generator_subtransient_pu) : 0.0;
faultKa = { grid_only: rnd(iGrid * c.kv / 0.4 / 1000, 2), with_sources: rnd((iGrid + iPv + iGen) * c.kv / 0.4 / 1000, 2) };
}
const Vpu = {}; for (const n of order) Vpu[n] = mag(V[n]) / vb;
return { V: Vpu, p_poc_kw: sPoc[0] / 1000, q_poc_kvar: sPoc[1] / 1000, loss_kw: loss / 1000, tx_loading_pct: tx, rounds,
balance: Math.abs(source - net - loss) / Math.max(Math.abs(net), 1.0), fault_ka: faultKa };
}
function sitePulse(i) {
if (i.scenario === undefined) throw new Error('this command needs "scenario" (1 to 8)');
const sc = SCENARIOS[i.scenario]; if (!sc) throw new Error('scenario is a number from 1 to 8');
const site = i.site || standardSite(), loadShare = i.load_share === undefined ? 1.0 : i.load_share, c = CANDIDATE;
const r = solve(site, sc[1], sc[2], sc[3], loadShare);
const exp = Math.max(0.0, -r.p_poc_kw), over = Math.max(0.0, exp - site.export_limit_kw);
const vs = Object.values(r.V), vmax = Math.max(...vs), vmin = Math.min(...vs), worst = Math.max(...Object.values(r.tx_loading_pct));
const flags = [];
if (over > 0) flags.push('export ' + exp.toFixed(0) + ' kW is ' + over.toFixed(0) + ' kW over the ' + site.export_limit_kw.toFixed(0) + ' kW limit: the solar must be held back');
if (vmax > c.volts_high_pu) flags.push('highest voltage ' + vmax.toFixed(3) + ' of nominal is over ' + c.volts_high_pu.toFixed(2));
if (vmin < c.volts_low_pu) flags.push('lowest voltage ' + vmin.toFixed(3) + ' of nominal is under ' + c.volts_low_pu.toFixed(2));
if (worst > 100) flags.push('a transformer is at ' + worst.toFixed(0) + '% of its rating');
const signed = (x) => (x < 0 ? '-' : '+') + Math.abs(x).toFixed(0);
return { numbers: { connection_point_kw: rnd(r.p_poc_kw, 1), connection_point_kvar: rnd(r.q_poc_kvar, 1), export_kw: rnd(exp, 1), over_limit_kw: rnd(over, 1),
losses_kw: rnd(r.loss_kw, 2), highest_volts_pu: rnd(vmax, 4), lowest_volts_pu: rnd(vmin, 4), worst_transformer_pct: rnd(worst, 1),
rounds: r.rounds, fault_level_beside_solar_ka: r.fault_ka },
said: sc[0] + ', load ' + Math.round(loadShare * 100) + '%: connection point ' + signed(r.p_poc_kw) + ' kW (plus is import), ' + signed(r.q_poc_kvar) + ' kvar; volts ' + vmin.toFixed(3) + ' to ' + vmax.toFixed(3) +
'; busiest transformer ' + worst.toFixed(0) + '%; ' + (flags.length ? flags.join('; ') : 'inside every limit'),
how: 'two pulses per round until the volts stop moving: currents summed back to the grid, volts dropped or raised out from it. A GENERIC site, no real one; every electrical figure is a CANDIDATE. An estimate, not a study.' };
}
const F = root.FIRE || (typeof require !== 'undefined' ? require('./fire.js') : null);
if (!F) throw new Error('fire_site.js needs fire.js loaded first');
F.register('site-pulse', 'SITE PULSE', sitePulse);
F.sitePulse = { solve, standardSite, SCENARIOS, CANDIDATE };
})(typeof window !== 'undefined' ? window : globalThis);
// bench/fire_topo.js - NETWORKS FROM A SEED, in the visitor's browser: the same generator and the same two pulse sweep as
// bench/topo.py, draw for draw and sum for sum. Checked against every Python case by bench/topo_check.mjs. Load after fire.js.
// fire network {"seed":123456,"solar":1,"generator":1,"load":0.3}
(function (root) {
const C = { kv: 11.0, grid_x_over_r: 10.0, hv_cable_r: 0.20, hv_cable_x: 0.09, tx_z_pct: 5.5, tx_x_over_r: 5.0, load_pf: 0.90, gen_pf: 0.95, volts_high_pu: 1.06, volts_low_pu: 0.94 };
const KVA = [500, 800, 1000, 1600, 2000], LIMITS = [0, 50, 200, 500, 1000], GENS = [0, 250, 500, 1000], FAULT = [100, 150, 250, 350, 500];
const SHAPES = ['star', 'chain', 'tree', 'sub-boards'];
const CASES = []; for (const ps of [0.0, 0.5, 1.0]) for (const g of [0, 1]) for (const ls of [1.0, 0.6, 0.3]) CASES.push([ps, g, ls]);
function mulberry32(a) { a |= 0; return () => { a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return (t ^ t >>> 14) >>> 0; }; }
function network(seed, variant) {
const g = mulberry32(Number((BigInt(seed) * 2654435761n + 777n) & 0xFFFFFFFFn)), pick = n => g() % n;
const shape = pick(4), n = 2 + pick(11), fault = FAULT[pick(5)], intake = (10 + pick(191)) / 100, limit = LIMITS[pick(5)], subs = [];
for (let k = 1; k <= n; k++) {
const kva = KVA[pick(5)], load = Math.floor(kva * (25 + pick(56)) / 100), km = (5 + pick(76)) / 100; let parent;
if (k === 1 || shape === 0) parent = 0; else if (shape === 1) parent = pick(10) < 8 ? k - 1 : 0; else if (shape === 2) parent = pick(k); else parent = k <= 3 ? 0 : 1 + pick(3);
const pv = pick(10) < 3 ? Math.floor(kva * (30 + pick(121)) / 100) : 0;
subs.push({ n: k, kva, load_kw: load, km, parent, pv_kw: pv });
}
const gen = GENS[pick(4)], genAt = pick(n + 1);
// the same networks asked a different way, exactly as bench/topo.py: 1 more solar, 2 a weak grid, 3 long cables, 4 smaller transformers
let fault2 = fault, intake2 = intake;
if (variant === 1) for (const s of subs) s.pv_kw = Math.floor(s.pv_kw * 3 / 2);
else if (variant === 2) fault2 = Math.floor(fault / 2);
else if (variant === 3) { intake2 = intake * 3; for (const s of subs) s.km = s.km * 3; }
else if (variant === 4) for (const s of subs) s.kva = KVA[Math.max(0, KVA.indexOf(s.kva) - 1)];
return { seed, variant: variant || 0, shape: SHAPES[shape], fault_mva: fault2, intake_km: intake2, export_limit_kw: limit, generator_kw: gen, generator_at: genAt, subs };
}
const add = (a, b) => [a[0] + b[0], a[1] + b[1]], sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
const mul = (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
const div = (a, b) => { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; };
const conj = a => [a[0], -a[1]], scale = (a, k) => [a[0] * k, a[1] * k], mag = a => Math.hypot(a[0], a[1]);
function solve(net, pvShare, genOn, loadShare, tol) {
tol = tol || 1e-9; const c = C, vb = c.kv * 1000 / Math.sqrt(3);
const zs = (c.kv ** 2) / net.fault_mva, xr = c.grid_x_over_r, rs = zs / Math.sqrt(1 + xr * xr), cable = [c.hv_cable_r, c.hv_cable_x];
const Z = { poc: [rs, rs * xr], board: scale(cable, net.intake_km) }, parent = { grid: null, poc: 'grid', board: 'poc' }, S = {}, kva = {};
const tanl = Math.tan(Math.acos(c.load_pf)), tang = Math.tan(Math.acos(c.gen_pf));
const gen = genOn ? [net.generator_kw, net.generator_kw * tang] : [0, 0];
if (genOn && net.generator_at === 0) S.board = scale(gen, -1000 / 3);
for (const s of net.subs) {
const hv = 'hv' + s.n, lv = 'lv' + s.n; parent[hv] = s.parent === 0 ? 'board' : 'hv' + s.parent; parent[lv] = hv;
Z[hv] = scale(cable, s.km);
const zt = c.tx_z_pct / 100 * (c.kv ** 2) / (s.kva / 1000), txr = c.tx_x_over_r, rt = zt / Math.sqrt(1 + txr * txr);
Z[lv] = [rt, rt * txr]; kva[lv] = s.kva;
const kw = s.load_kw * loadShare; let p = sub([kw, kw * tanl], [s.pv_kw * pvShare, 0]);
if (genOn && net.generator_at === s.n) p = sub(p, gen);
S[lv] = scale(p, 1000 / 3);
}
const kids = {}; for (const n of Object.keys(parent)) if (parent[n] !== null) (kids[parent[n]] = kids[parent[n]] || []).push(n);
const order = ['grid']; for (let i = 0; i < order.length; i++) order.push(...(kids[order[i]] || []));
let V = {}; for (const n of order) V[n] = [vb, 0]; let rounds = 0, J;
for (;;) {
rounds++; J = {}; for (const n of order) J[n] = S[n] ? conj(div(S[n], V[n])) : [0, 0];
for (let i = order.length - 1; i >= 0; i--) { const n = order[i]; if (parent[n] !== null) J[parent[n]] = add(J[parent[n]], J[n]); }
const nv = { grid: [vb, 0] }; for (let i = 1; i < order.length; i++) { const n = order[i]; nv[n] = sub(nv[parent[n]], mul(J[n], Z[n])); }
let step = 0; for (const n of order) step = Math.max(step, mag(sub(nv[n], V[n]))); V = nv;
if (step < tol || rounds > 300) break;
}
const sPoc = scale(mul(V.poc, conj(J.poc)), 3);
let loss = 0; for (let i = 1; i < order.length; i++) loss += mag(J[order[i]]) ** 2 * Z[order[i]][0]; loss *= 3;
let netP = 0; for (const n of Object.keys(S)) netP += S[n][0]; netP *= 3;
const source = mul(V.grid, conj(J.poc))[0] * 3;
let tx = -Infinity, amps = -Infinity; const txEach = {}, ampsEach = {}, vEach = {};
for (const n of Object.keys(kva)) { txEach[n] = mag(scale(mul(V[n], conj(J[n])), 3)) / 1000 / kva[n] * 100; tx = Math.max(tx, txEach[n]); }
for (let i = 1; i < order.length; i++) { const n = order[i]; if (!(n in kva)) { ampsEach[n] = mag(J[n]); amps = Math.max(amps, ampsEach[n]); } }
let vmax = -Infinity, vmin = Infinity; for (const n of order) { const v = mag(V[n]) / vb; vEach[n] = v; vmax = Math.max(vmax, v); vmin = Math.min(vmin, v); }
return { p: sPoc[0] / 1000, q: sPoc[1] / 1000, loss: loss / 1000, vmax, vmin, tx, amps, rounds, balance: Math.abs(source - netP - loss) / Math.max(Math.abs(netP), 1.0),
each: { volts: vEach, tx: txEach, amps: ampsEach }, parent };
}
const rnd = (x, d) => Number(x.toFixed(d));
function run(i) {
if (i.seed === undefined) throw new Error('this command needs "seed" (any whole number: each one is a different network)');
const net = i.network || network(i.seed, i.variant || 0), ps = i.solar === undefined ? 1 : i.solar, g = i.generator === undefined ? 0 : i.generator, ls = i.load === undefined ? 1 : i.load;
const r = solve(net, ps, !!g, ls), c = C, exp = Math.max(0, -r.p), over = Math.max(0, exp - net.export_limit_kw), flags = [];
if (r.rounds > 300 || r.balance >= 1e-6) flags.push('THE SWEEP DID NOT CONVERGE: this network is beyond the method, and no number here should be used');
if (over > 0) flags.push('export ' + exp.toFixed(0) + ' kW is ' + over.toFixed(0) + ' kW over the ' + net.export_limit_kw + ' kW limit');
if (r.vmax > c.volts_high_pu) flags.push('highest voltage ' + r.vmax.toFixed(3) + ' is over ' + c.volts_high_pu);
if (r.vmin < c.volts_low_pu) flags.push('lowest voltage ' + r.vmin.toFixed(3) + ' is under ' + c.volts_low_pu);
if (r.tx > 100) flags.push('a transformer is at ' + r.tx.toFixed(0) + '% of its rating');
const pv = net.subs.reduce((t, s) => t + s.pv_kw, 0), load = net.subs.reduce((t, s) => t + s.load_kw, 0);
return { numbers: { substations: net.subs.length, load_kw: rnd(load * ls, 0), solar_kw: rnd(pv * ps, 0), generator_kw: g ? net.generator_kw : 0, export_limit_kw: net.export_limit_kw,
connection_point_kw: rnd(r.p, 1), connection_point_kvar: rnd(r.q, 1), losses_kw: rnd(r.loss, 2), highest_volts_pu: rnd(r.vmax, 4), lowest_volts_pu: rnd(r.vmin, 4),
worst_transformer_pct: rnd(r.tx, 1), busiest_cable_amps: rnd(r.amps, 1), rounds: r.rounds },
said: 'A ' + net.shape + ' of ' + net.subs.length + ' substations behind a ' + net.fault_mva + ' MVA connection: ' + (r.p < 0 ? 'exports ' : 'imports ') + Math.abs(r.p).toFixed(0) + ' kW; volts ' + r.vmin.toFixed(3) + ' to ' + r.vmax.toFixed(3) +
'; busiest transformer ' + r.tx.toFixed(0) + '%; ' + (flags.length ? flags.join('; ') : 'inside every limit'),
how: 'network number ' + net.seed + ' from a stated generator (no real site); two pulses per round until the volts stop moving; every figure a CANDIDATE. An estimate, not a study.', net, solved: r };
}
const F = root.FIRE || (typeof require !== 'undefined' ? require('./fire.js') : null);
if (!F) throw new Error('fire_topo.js needs fire.js loaded first');
F.register('network', 'NETWORKS', run);
F.topo = { network, solve, CASES, C };
})(typeof window !== 'undefined' ? window : globalThis);
// ===== ONE SOLAR STRING, WIRED TWO WAYS: fire string {"wiring":"leapfrog"} =======================
// A row of modules in series. SEQUENTIAL joins each module to the next and needs one more cable the length of the row to bring the
// far end home. LEAPFROG joins every other module on the way out and the ones between on the way back, so both ends finish at the
// near end and that cable is not laid: the return travels in the modules' own leads. Whether the leads REACH is geometry: the two
// junction boxes sit a stated distance apart on every module, so a link on the way out is two pitches LESS that distance and a link
// on the way back is two pitches MORE. Every length here is counted from stated inputs; every figure is an estimate. No real site.
(function (root) {
const F = root.FIRE; if (!F) return;
const R20 = { 2.5: 8.21, 4: 5.09, 6: 3.39, 10: 1.95 }; // milliohm per metre at 20 C, tinned copper, class 5
const DEF = { modules: 30, width_m: 1.303, module_height_m: 2.384, cell_cols: 6, cell_rows: 22, module_vmp: 38.1, module_voc: 45.9,
// THE TABLE ITSELF. One module high in portrait on a fixed tilt is the old row, exactly.
// TWO VIEWS, DECLARED. MACRO is the whole string - every module and both home runs to the
// inverter - fitted to the width of the screen: fine outlines, boxes as dots, one thin line
// for each cable, and the only words are M1, M10, M20, M30 and the inverter. MICRO is M1 to
// M4 filling the screen, with the cells, the three boxes and their diode marks, and the
// connectors. A telephone opens on MICRO, because a whole row on a telephone is a grey
// smear; a desk opens on MACRO, because there is room for the shape of the thing. The view
// is a CAMERA and nothing else: what is drawn at any moment is decided by the zoom, so
// pinching between the two crosses the same thresholds as typing the word.
mounting: 'fixed', orientation: 'portrait', modules_high: 1, routing: '',
view: (typeof innerWidth === 'number' && innerWidth > 0 && innerWidth < 700) ? 'micro' : 'macro', sheet: 0,
// A RETURN TIER IS MOUNTED THE OTHER WAY ROUND, and that is not a detail. Going back along
// the upper row, the + box of one module has to reach the - box of the one to its LEFT, so
// the link is a pitch PLUS the box spacing instead of a pitch minus it: 2.16 m where 0.48 m
// was expected. Turning every module in the return rows end for end puts it back to 0.48 m,
// and that is what is actually done on a table. It is an input because it is a decision.
turn_alternate_rows: 0,
// A JUMPER IS WHAT IS REALLY DONE when two leads do not meet: a short cable is made up on
// site and spliced between them, which closes the circuit and costs cable and one more
// mated pair at that link. Without this the model says the string is open, which is the
// truth about the LEADS and not about the finished job. Off by default, because a jumper
// is a decision somebody has to take and pay for.
jumpers: 0,
gap_up_m: 0.02, ridge_gap_m: 0.15, tube_gap_m: 0.12,
gap_m: 0.02, box_spacing_m: 0.84, wiring: 'leapfrog', turn_every_second: 0,
leads: 'reach', lead_slack_m: 0.20, lead_plus_m: null, lead_minus_m: null, lead_mm2: 4, cable_mm2: 6, near_end_m: 59, amps: 17.35,
// TWO CONDUCTORS IN TWO PLACES AT TWO TEMPERATURES. A module lead is clipped to the back of a
// module in the sun; the site cable is in a tray or a trench. One figure for both was always a
// simplification, and it flattered whichever of the two was hotter. conductor_c is kept as the
// NAME FOR BOTH: give it and both take it, so every command ever written still means what it
// said, and equal temperatures reproduce the old model to the digit.
conductor_c: null, t_lead_c: 80, t_site_c: 55, rating_c: 90,
// HOW FAR APART THE TWO HOME RUNS ARE LAID. The array's own loop is one thing; the pair of
// cables running back to the inverter is another, and on a long home run it is the bigger of
// the two. It has NO DEFAULT, on purpose: nobody can know from a drawing whether that pair
// was bundled or run in two trays, and the difference moves the answer more than the wiring
// choice does. Until it is given, the home run loop and the total are NOT REPORTED. A model
// that guesses a number like that is worse than a model that says it does not know.
home_separation_m: null,
// SLACK AT EVERY LINK. A lead is not a straight line: it is clipped, it drops and it comes
// back. The distance a link has to span is the straight distance between the two boxes PLUS
// whatever allowance the installer is told to leave. Zero is the geometric case.
slack_m: 0,
contact_milliohm: 0.35, return_offset_m: 0.3, lead_gap_m: 0.05,
// ===== THE MODULE IS A CIRCUIT, AND EVERY PART OF IT IS AN INPUT ==========================
// These carry the tested parameter set of LIB/solar-params (38 parameters in six groups,
// 11 named rules, 89 assertions in its test.mjs) into this command. Real lengths vary with
// the design, the structure and the module, so none of them is a constant any more.
// Where a value would move a number this command has always reported, the DEFAULT HERE IS
// THE GEOMETRIC CASE (zero) and the library's own default is named in the box hint: give it
// and it is used in full.
module_class: '', // MODULE: preset, '' = whatever is typed
half_cut: 1, cell_cut: 2, // MODULE: laminate in two halves; cells per column strip
n_boxes: 3, // MODULE: one box (2011 type) or three
box_along_frac: 0.5, // MODULE: box line, as a fraction of the module LENGTH
box_across_frac_minus: null, // MODULE: - box across the module WIDTH; null = from box_spacing_m
box_across_frac_plus: null, // MODULE: + box across the module WIDTH
box_w_m: 0.064, box_h_m: 0.024, // MODULE: the box rectangle itself
connector_pair_m: 0, // MODULE: a mated pair eats this much lead (library 0.060)
tc_voc_pct_per_k: -0.25, // MODULE: open circuit temperature coefficient
max_system_voltage_v: 1500, // MODULE: the system voltage the class is built for
table_length_modules: 60, // STRUCTURE: columns before the row breaks
gap_table_m: 0.02, // STRUCTURE: the gap at that break, added to the run
clip_offset_m: 0, // STRUCTURE: clip line off the box line (library -0.120)
route_allowance_m: 0, // STRUCTURE: gland, bends, clip entry (library 0.080)
home_run_mm2: null, // HOME RUN: null = the site cable size
termination_extra_m: 0, // HOME RUN: added once per termination (library 1.0)
home_run_from: 'start', // HOME RUN: which end the two string ends are collected at
ohm_per_km_lead: null, ohm_per_km_site: null, // CABLE: null = the table for that mm2
t_min_c: -10, t_max_c: 40 }; // SITE: the cold end sets the longest string allowed
// ===== THE MODULE CLASSES, AS PRESETS ==========================================================
// Three real classes by nameless class label only, and one 2011-type single-box module which has NO
// datasheet behind it at all. Copied from LIB/solar-params/params.mjs PRESETS.
const PRESETS = {
'class-T660': { note: '2384 x 1303 mm, 660 Wp, 210 mm half cut, 6 x 22, three boxes on the transverse centre line',
values: { module_height_m: 2.384, width_m: 1.303, cell_cols: 6, cell_rows: 22, half_cut: 1, cell_cut: 2, n_boxes: 3,
box_along_frac: 0.5, box_across_frac_minus: 0.174443, box_across_frac_plus: 0.825557,
box_w_m: 0.064, box_h_m: 0.024, lead_minus_m: 0.280, lead_plus_m: 0.350, lead_mm2: 4,
module_voc: 45.9, module_vmp: 38.1, tc_voc_pct_per_k: -0.25, max_system_voltage_v: 1500 } },
'class-W760': { note: '2384 x 1303 mm, 760 Wp, third cut, 6 x 33. The two lead boxes sit near ONE END, not on the mid line',
values: { module_height_m: 2.384, width_m: 1.303, cell_cols: 6, cell_rows: 33, half_cut: 0, cell_cut: 3, n_boxes: 3,
box_along_frac: 0.053649, box_across_frac_minus: 0.174520, box_across_frac_plus: 0.825557,
box_w_m: 0.034, box_h_m: 0.079, lead_minus_m: 0.200, lead_plus_m: 0.400, lead_mm2: 4,
module_voc: 50.59, module_vmp: 42.3, tc_voc_pct_per_k: -0.22, max_system_voltage_v: 1500 },
landscape_leads: { lead_minus_m: 1.400, lead_plus_m: 1.400 } },
'class-J-650': { note: '2465 x 1134 mm, 650 Wp, half cut, 6 x 24, three boxes on the transverse centre line',
values: { module_height_m: 2.465, width_m: 1.134, cell_cols: 6, cell_rows: 24, half_cut: 1, cell_cut: 2, n_boxes: 3,
box_along_frac: 0.5, box_across_frac_minus: 0.175397, box_across_frac_plus: 0.823545,
box_w_m: 0.058, box_h_m: 0.024, lead_minus_m: 0.400, lead_plus_m: 0.300, lead_mm2: 4,
module_voc: 53.27, module_vmp: 44.6, tc_voc_pct_per_k: -0.25, max_system_voltage_v: 1500 },
landscape_leads: { lead_minus_m: 1.500, lead_plus_m: 1.500 } },
'small-2011-single-box': { note: '2011-type 60 cell, 1650 x 990 mm, full cells, ONE box near the top edge carrying both leads. NO DATASHEET: every value is assumed and must be confirmed before it is quoted',
values: { module_height_m: 1.650, width_m: 0.990, cell_cols: 6, cell_rows: 10, half_cut: 0, cell_cut: 1, n_boxes: 1,
box_along_frac: 0.06, box_across_frac_minus: 0.5, box_across_frac_plus: 0.5,
box_w_m: 0.115, box_h_m: 0.085, lead_minus_m: 0.900, lead_plus_m: 0.900, lead_mm2: 4,
module_voc: 37.0, module_vmp: 30.0, tc_voc_pct_per_k: -0.34, max_system_voltage_v: 1000, modules: 20 } }
};
// WHAT A SANE SITE ACTUALLY USES. Outside this the engine does not refuse; it asks "did you mean".
const PLAUSIBLE = { width_m:[0.5,1.5,'m'], module_height_m:[0.8,2.8,'m'], cell_cols:[4,12,'count'], cell_rows:[8,40,'count'],
box_w_m:[0.02,0.2,'m'], box_h_m:[0.01,0.2,'m'], lead_minus_m:[0.1,2.0,'m'], lead_plus_m:[0.1,2.0,'m'],
module_voc:[20,70,'V'], tc_voc_pct_per_k:[-0.45,-0.15,'%/K'],
max_system_voltage_v:[600,1500,'V'], modules_high:[1,4,'count'], gap_m:[0.005,0.1,'m'], gap_up_m:[0.005,0.3,'m'],
table_length_modules:[8,120,'count'], gap_table_m:[0.02,5,'m'], clip_offset_m:[-0.6,0.6,'m'],
route_allowance_m:[0,0.5,'m'], slack_m:[0,0.4,'m'], modules:[8,40,'count'], near_end_m:[2,600,'m'],
lead_mm2:[2.5,10,'mm2'], cable_mm2:[4,120,'mm2'], t_min_c:[-40,15,'C'], t_max_c:[20,55,'C'] };
const rnd = (x, n) => { const k = Math.pow(10, n); return Math.round(x * k) / k; };
const ROUTE_WORDS = { 'one-after-another':'one after another, with a cable to bring the far end home',
'serpentine':'along and back, out along one row and back along the next',
'leapfrog':'leapfrog inside each row', 'zigzag':'zigzag between two rows' };
const LAYOUT_WORDS = g => { const o = g.port ? 'portrait' : 'landscape';
const m = g.mount === 'east-west' ? 'east and west facing, ' + g.high + ' in ' + o + ' on each face'
: g.mount === 'tracker' ? 'a tracker, ' + g.rows + ' in ' + o
: 'fixed tilt, ' + g.rows + ' in ' + o + (g.rows > 1 ? ' high' : '');
return m; };
// ===== THE TABLE. A string is not a row; a row is a table one module high. =====================
// A module's two boxes sit at MID LENGTH OF ITS LONG SIDE, spread along its SHORT axis. That is one
// rule and it settles both orientations without a special case: in PORTRAIT the long side is upright,
// so the - and the + sit side by side ALONG the table; in LANDSCAPE the module is turned a quarter
// turn, the long side is now horizontal, and the two boxes sit one ABOVE the other. Everything else -
// where the modules are, how far a link has to reach, what is laid on site - follows from that and
// from the grid. A table one module high in portrait reproduces the old row model to the digit, which
// is asserted rather than hoped for.
function build(inp) {
// THE LIBRARY'S OWN MERGE ORDER: defaults <- preset <- what was typed. A preset is a module class and
// nothing else; every value it brings can still be typed over.
const typed = Object.assign({}, inp || {});
// the library's key names are accepted as names for this command's own
if (typed.module_width_m !== undefined) typed.width_m = typed.module_width_m;
if (typed.module_length_m !== undefined) typed.module_height_m = typed.module_length_m;
if (typed.cells_across !== undefined) typed.cell_cols = typed.cells_across;
if (typed.cells_up !== undefined) typed.cell_rows = typed.cells_up;
if (typed.n !== undefined) typed.modules = typed.n;
if (typed.voc_stc_v !== undefined) typed.module_voc = typed.voc_stc_v;
if (typed.home_run_m !== undefined) typed.near_end_m = typed.home_run_m;
if (typed.site_mm2 !== undefined) typed.cable_mm2 = typed.site_mm2;
const pre = PRESETS[String(typed.module_class || '')];
const c = Object.assign({}, DEF, pre ? pre.values : null,
(pre && pre.landscape_leads && String(typed.orientation || '').toLowerCase() === 'landscape') ? pre.landscape_leads : null,
typed);
const N = Math.max(2, Math.min(60, Math.round(c.modules)));
const port = String(c.orientation || 'portrait').toLowerCase() !== 'landscape';
const wX = port ? c.width_m : c.module_height_m, wY = port ? c.module_height_m : c.width_m;
const pitch = wX + c.gap_m, pitchY = wY + c.gap_up_m;
const mount = String(c.mounting || 'fixed').toLowerCase();
const high = Math.max(1, Math.min(6, Math.round(c.modules_high)));
const faces = mount === 'east-west' ? 2 : 1, rows = high * faces;
const cols = Math.max(1, Math.ceil(N / rows));
// WHAT STANDS BETWEEN TWO ROWS: nothing on a plain table, the ridge on an east west table, the torque
// tube down the middle of a tracker.
const extraAfter = r => (faces === 2 && r === high - 1) ? c.ridge_gap_m
: (mount === 'tracker' && r === Math.floor(rows / 2) - 1) ? c.tube_gap_m : 0;
const rowY = []; { let yy = 0; for (let r = 0; r < rows; r++) { rowY.push(yy); yy += pitchY + extraAfter(r); } }
// ROUTING is what the old "wiring" input was asking, and it is kept as a name for it.
let routing = String(c.routing || '').toLowerCase();
if (!routing) routing = String(c.wiring).toLowerCase() === 'sequential' ? 'one-after-another' : 'leapfrog';
if (routing === 'along-and-back' || routing === 'sequential-u') routing = 'serpentine';
if (routing === 'sequential') routing = 'one-after-another';
if (routing === 'zigzag' && rows < 2) routing = 'one-after-another';
if (routing === 'serpentine' && rows < 2) routing = 'one-after-another';
c.routing = routing;
const leap = routing === 'leapfrog';
// THE DEFAULT STRING IS A COMPLETE STRING. Nobody builds an array and leaves half its links open;
// a drawing that opens by default is a drawing of a mistake. So unless a lead length is typed, the
// leads are THE PAIR THAT REACHES for the wiring chosen - the longest link plus the slack allowance
// - and the answer says what pair that is, to be ordered against what the module is supplied with.
// Ask for "supplied" instead and you get the factory portrait leads and, with them, the shortfall.
const leadsAre = String(c.leads || 'reach').toLowerCase();
const typedLeads = c.lead_plus_m !== null || c.lead_minus_m !== null;
if (leadsAre === 'supplied' && !typedLeads) { c.lead_plus_m = 0.35; c.lead_minus_m = 0.28; }
const rowOf0 = k => Math.min(rows - 1, Math.floor((k - 1) / cols)), colOf = k => (k - 1) % cols;
const turned = k => (!!c.turn_every_second && k % 2 === 0) !== (!!c.turn_alternate_rows && rowOf0(k) % 2 === 1);
const rowOf = rowOf0;
// WHERE THE ROW BREAKS. A table is so many modules long and then there is a gap in the steel; a link
// that crosses the break has to cross the gap as well. Nothing to declare and nothing to guess: it is
// in the x of every module.
const tlm = Math.max(1, Math.round(+c.table_length_modules || 1)), gTab = +c.gap_table_m || 0;
const x0 = k => colOf(k) * pitch + Math.floor(colOf(k) / tlm) * gTab, y0 = k => rowY[rowOf(k)];
// THE BOXES ARE NOT AT THE MIDDLE OF ANYTHING UNLESS THE CLASS PUTS THEM THERE. Their positions are
// two fractions: ACROSS the module's short axis (u) and ALONG its long axis (v). box_spacing_m is kept
// as the name for the across pair, so every command ever written still means what it said.
const fM0 = c.box_across_frac_minus === null || c.box_across_frac_minus === undefined
? 0.5 - (c.box_spacing_m / 2) / c.width_m : +c.box_across_frac_minus;
const fP0 = c.box_across_frac_plus === null || c.box_across_frac_plus === undefined
? 0.5 + (c.box_spacing_m / 2) / c.width_m : +c.box_across_frac_plus;
const fV0 = Math.min(1, Math.max(0, +c.box_along_frac));
const boxSpanM = Math.round(Math.abs(fP0 - fM0) * c.width_m * 1e6) / 1e6;
const ptAt = (k, want, t) => { const u0 = want === '+' ? fP0 : fM0;
const u = t ? 1 - u0 : u0, v = t ? 1 - fV0 : fV0;
return port ? [x0(k) + u * wX, y0(k) + v * wY] : [x0(k) + v * wX, y0(k) + u * wY]; };
const minusPt = k => ptAt(k, '-', turned(k)), plusPt = k => ptAt(k, '+', turned(k));
const minus = k => minusPt(k)[0], plus = k => plusPt(k)[0]; // the drawing reads x from these
// THE ORDER THE STRING IS WIRED IN, over the grid of modules. The modules themselves never move.
const inRow = r => { const out = []; for (let k = 1; k <= N; k++) if (rowOf(k) === r) out.push(k); return out; };
const order = [];
if (routing === 'leapfrog') { for (let r = 0; r < rows; r++) { const q = inRow(r); if (!q.length) continue;
const fwd = r % 2 === 0 ? q : q.slice().reverse();
for (let i = 0; i < fwd.length; i += 2) order.push(fwd[i]);
for (let i = (fwd.length % 2 ? fwd.length - 2 : fwd.length - 1); i >= 1; i -= 2) order.push(fwd[i]); } }
else if (routing === 'serpentine') { for (let r = 0; r < rows; r++) { const q = inRow(r); if (!q.length) continue;
order.push(...(r % 2 === 0 ? q : q.slice().reverse())); } }
else if (routing === 'zigzag') { const a0 = inRow(0), a1 = inRow(1);
for (let i = 0; i < Math.max(a0.length, a1.length); i++) { const up = i % 2 === 0;
if (up) { if (a0[i] !== undefined) order.push(a0[i]); if (a1[i] !== undefined) order.push(a1[i]); }
else { if (a1[i] !== undefined) order.push(a1[i]); if (a0[i] !== undefined) order.push(a0[i]); } }
for (let r = 2; r < rows; r++) { const q = inRow(r); order.push(...(r % 2 === 0 ? q : q.slice().reverse())); } }
else for (let k = 1; k <= N; k++) order.push(k);
// HOW FAR EACH LINK HAS TO REACH IS GEOMETRY, and it does not depend on what lead is fitted: so the
// needs are measured first, and only then is the lead pair settled.
const links = [];
for (let i = 0; i + 1 < order.length; i++) { const from = order[i], to = order[i + 1];
const A = plusPt(from), B = minusPt(to);
// THE ROUTE IS NOT THE DIAGONAL when the cable is clipped: it leaves the box, drops to the clip line
// c.clip_offset_m away, runs along it and climbs back. Plus the gland exit, the bend radii and the
// clip entry, which no polyline draws: c.route_allowance_m. Both are zero by default, which is the
// geometric case this command has always reported; the library's own defaults are -0.120 and 0.080 m.
const routeExtra = 2 * Math.abs(+c.clip_offset_m || 0) + (+c.route_allowance_m || 0);
const need = Math.hypot(A[0] - B[0], A[1] - B[1]) + (+c.slack_m || 0) + routeExtra;
links.push({ from, to, need, back: to < from, cross: rowOf(from) !== rowOf(to),
x_from: A[0], x_to: B[0], y_from: A[1], y_to: B[1] }); }
const longest = links.length ? Math.max(...links.map(l => l.need)) : 0;
if (c.lead_plus_m === null || c.lead_minus_m === null) {
const want = longest + (c.lead_slack_m === undefined ? 0.20 : +c.lead_slack_m);
// the + lead keeps the box spacing it really has and the - lead makes up the rest, which is how
// a module maker quotes an unequal pair
const lpWant = Math.min(want * 0.5, boxSpanM);
if (c.lead_plus_m === null) c.lead_plus_m = Math.round(lpWant * 1000) / 1000;
if (c.lead_minus_m === null) c.lead_minus_m = Math.round((want - c.lead_plus_m) * 1000) / 1000; }
// A MATED PAIR EATS LEAD. What is left of the two leads is what can actually span the route.
const pair = c.lead_plus_m + c.lead_minus_m - (+c.connector_pair_m || 0);
for (const l of links) { l.reaches = pair + 1e-9 >= l.need;
l.jumper = !l.reaches && !!c.jumpers ? l.need - pair : 0; }
const last = order[order.length - 1], row = (cols - 1) * pitch + Math.floor((cols - 1) / tlm) * gTab + wX;
// HOW FAR A FREE END IS FROM THE NEAR CORNER, along the structure: a cable is clipped to steel, it
// does not fly. Both ends land at the near end when the + end is in the near half of the table.
const yBase = rowY[0] + wY / 2;
// WHICH END THE TWO STRING ENDS ARE COLLECTED AT is a decision, not a fact about the table.
const xRef = String(c.home_run_from || 'start').toLowerCase() === 'end' ? (cols - 1) * pitch + Math.floor((cols - 1) / tlm) * gTab : 0;
const run = q => Math.abs(q[0] - xRef) + Math.abs(q[1] - yBase);
const endRun = run(plusPt(last)), bothNear = endRun <= row / 2;
const ret = bothNear ? 0 : endRun;
// conductor_c, when it is given, is the name for both: it sets the lead and the site cable together.
if (c.conductor_c !== null && c.conductor_c !== undefined && c.conductor_c !== '') { c.t_lead_c = +c.conductor_c; c.t_site_c = +c.conductor_c; }
const fLead = 1 + 0.00393 * (c.t_lead_c - 20), fSite = 1 + 0.00393 * (c.t_site_c - 20);
// A JUMPER IS SITE CABLE AND ONE MORE MATED PAIR, at the link it is spliced into.
const jumpers = links.filter(l => l.jumper > 0), jumper_m = jumpers.reduce((t, l) => t + l.jumper, 0);
const lead_m = N * pair, field_m = 2 * c.near_end_m + 4 * (+c.termination_extra_m || 0) + run(minusPt(order[0])) + endRun + jumper_m;
const pairs = links.length + 2 + (bothNear ? 0 : 1) + jumpers.length;
// A SITE MADE END is a connector fitted to a cut cable by a person on the table: the two home runs
// always, and the far end return cable's two, when one is laid.
const siteEnds = 2 + (bothNear ? 0 : 2);
// THE COPPER'S OWN NUMBER IS AN INPUT TOO, and the home run may be a different size from the array's
// own cable: on a long run it is the bigger part of the loss.
const rLead = (c.ohm_per_km_lead === null || c.ohm_per_km_lead === undefined) ? (R20[c.lead_mm2] || 5.09) : +c.ohm_per_km_lead;
const rSite = (c.ohm_per_km_site === null || c.ohm_per_km_site === undefined) ? (R20[c.cable_mm2] || 3.39) : +c.ohm_per_km_site;
const hrSize = (c.home_run_mm2 === null || c.home_run_mm2 === undefined) ? c.cable_mm2 : c.home_run_mm2;
const rHome = (c.ohm_per_km_site === null || c.ohm_per_km_site === undefined) ? (R20[hrSize] || rSite) : rSite;
const home_m = 2 * c.near_end_m + 4 * (+c.termination_extra_m || 0), array_m = field_m - 2 * c.near_end_m - 4 * (+c.termination_extra_m || 0);
const ohmLead = rLead * lead_m * fLead / 1000;
const ohmSite = (rHome * home_m + rSite * array_m) * fSite / 1000;
const ohm = ohmLead + ohmSite + pairs * c.contact_milliohm / 1000;
const short = links.filter(l => !l.reaches && !l.jumper), needs = links.map(l => l.need);
// THREE LOOPS, NOT ONE. The array's own loop is what the wiring choice changes; the home run pair is
// its own loop and on a long run it is the larger; a nearby stroke couples into the SUM of them.
const arrayLoop = bothNear ? row * c.lead_gap_m : row * c.return_offset_m;
const sep = (c.home_separation_m === null || c.home_separation_m === undefined || c.home_separation_m === '') ? null : +c.home_separation_m;
const homeLoop = sep === null ? null : c.near_end_m * sep;
const loop = homeLoop === null ? null : arrayLoop + homeLoop;
// A CONDUCTOR OVER ITS RATING IS SAID IN WORDS AND NEVER QUIETLY COSTED.
const hot = [];
if (c.t_lead_c > c.rating_c) hot.push('the module leads at ' + c.t_lead_c + ' C are over the ' + c.rating_c + ' C the cable is rated for');
if (c.t_site_c > c.rating_c) hot.push('the site cable at ' + c.t_site_c + ' C is over the ' + c.rating_c + ' C it is rated for');
// WHAT IS NOT LAID ON SITE, against ONE stated baseline: the same row wired one after another, no
// module turned, with its far end brought home. Closed form, so it can be checked by hand:
// plain leapfrog saves (N-2) pitches; turning every second module saves (N-2) pitches and the box
// spacing as well, because the last module's + box has moved to the near side of its own module.
const baseEnd = Math.abs(ptAt(N, '+', false)[0]) + Math.abs(ptAt(N, '+', false)[1] - yBase);
const baseField = 2 * c.near_end_m + 4 * (+c.termination_extra_m || 0) + Math.abs(ptAt(1, '-', false)[0]) + Math.abs(ptAt(1, '-', false)[1] - yBase) + baseEnd;
const saved = baseField - field_m;
const smallest = needs.length ? Math.max(...needs) : 0;
// ===== THE ELEVEN SANITY RULES =================================================================
// Copied, words and all, from LIB/solar-params/params.mjs (RULES; its test.mjs asserts them in 89
// assertions). A rule that says no is not a failure: it is the engine refusing to draw something
// stupid, and the words it refuses in ARE the answer. Nothing wrong is ever drawn.
const vocCold = c.module_voc * (1 + (+c.tc_voc_pct_per_k) / 100 * (c.t_min_c - 25));
const stringVocCold = N * vocCold, nMaxCold = Math.floor(c.max_system_voltage_v / Math.max(1e-9, vocCold));
const checks = [];
const ok_ = (n, w) => checks.push({ name: n, ok: true, words: w });
const no_ = (n, w) => checks.push({ name: n, ok: false, words: w });
// 1
(() => { const nb = Math.round(+c.n_boxes);
if (nb !== 1 && nb !== 3) return no_('wiring_is_buildable', 'n_boxes is ' + c.n_boxes + '. A module carries one box or three; nothing else is drawn.');
if (N < 2 && routing !== 'one-after-another') return no_('wiring_is_buildable', 'N = ' + N + ': there is nothing to leapfrog over.');
if ((routing === 'serpentine' || routing === 'zigzag') && rows < 2) return no_('wiring_is_buildable', routing + ' goes out along one tier and back along the one above it, so it needs at least two tiers; modules high is ' + high + '. Use leapfrog on a single tier, or set modules high to 2.');
ok_('wiring_is_buildable', routing + ' is buildable on ' + rows + ' tier(s) with ' + nb + ' box(es) per module'); })();
// 2
(() => { if (Math.round(+c.n_boxes) === 1 && Math.abs(fP0 - fM0) > 1e-6)
return no_('lead_only_from_terminal_box', 'this module has ONE junction box, so both leads leave that box and the box spacing is zero; the + and the − are asked for ' + boxSpanM.toFixed(3) + ' m apart. A module lead can only leave a junction box that carries one.');
if (Math.round(+c.n_boxes) === 3 && Math.abs((fM0 + fP0) / 2 - 0.5) > 0.4)
return no_('lead_only_from_terminal_box', 'the two lead boxes are not the outer pair of the three: the middle box holds a bypass diode and the cross connection only, and no lead leaves it.');
ok_('lead_only_from_terminal_box', 'every lead leaves and lands on a box that carries a terminal'); })();
// 3
(() => { const bad = links.find(l => l.from === l.to);
if (bad) return no_('no_conductor_inside_one_module', 'a link has both ends on module ' + bad.from + '. A module is never wired to itself; that would short its own string.');
ok_('no_conductor_inside_one_module', 'no conductor has both ends on the same module'); })();
// 4