In this section
- Kuiper Programs electrical · globalgrid2050 / kuiper-grid/i0083/cartridges/008000000000-kuiper-programs.js lines 485–1184
Kuiper Programs
A JavaScript module in the cartridges folder of GlobalGrid2050 covering cables, solar, substations and transformers, using SHA-256, and uses data from the faraday repository.
electricalglobalgrid2050 / kuiper-grid/i0083/cartridges/008000000000-kuiper-programs.js · lines 485–1184 of 3063 (continued from section 1354) · Not reached from any entry point (candidate for review) · pattern segmentConductors (shared by 2 files)
- What it does
- It draws cables, solar, substations and transformers. Defines 197 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: cables, solar, substations, transformers, 400kV.
- Inputs & outputs
- In: data source: faraday data; JSON file current.json. Out: canvas drawing. Voltage levels named: 400kV.
- What it achieves
- It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). A cartridge of the Kuiper shell. Its code works with 400 kV, 50 kW and 500 kW. It responds to click, keydown and pointerdown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · kuiper-grid/i0083/cartridges · JavaScript module
- 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
- add, mul, div, conj, solve, rnd, run, rnd, LAYOUT_WORDS, build, extraAfter, rowOf0, turned, x0, ptAt, minusPt, minus, inRow, run, tempFactor, ohmPerKmAt, normalisePlan, segmentConductors, connectorPairs, collect, inputStatus, stringResistance, ampacity, resistanceAnswer, v
- 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/i0083/cartridges/008000000000-kuiper-programs.js:485-1184 · blob 6f65079a170876c16718f7e5c4705e6f35d4b2b6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
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.
mounting: 'fixed', orientation: 'portrait', modules_high: 1, routing: '', view: 'wiring', 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 };
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) {
const c = Object.assign({}, DEF, inp || {}), 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;
const x0 = k => colOf(k) * pitch, y0 = k => rowY[rowOf(k)];
const s2 = c.box_spacing_m / 2;
const ptAt = (k, want, t) => { const cxm = x0(k) + wX / 2, cym = y0(k) + wY / 2, d = (want === '+' ? 1 : -1) * (t ? -1 : 1) * s2;
return port ? [cxm + d, cym] : [cxm, cym + d]; };
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);
const need = Math.hypot(A[0] - B[0], A[1] - B[1]) + (+c.slack_m || 0);
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, c.box_spacing_m);
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; }
const pair = c.lead_plus_m + c.lead_minus_m;
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 * pitch;
// 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;
const run = q => Math.abs(q[0]) + 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 + 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);
const ohmLead = (R20[c.lead_mm2] || 5.09) * lead_m * fLead / 1000;
const ohmSite = (R20[c.cable_mm2] || 3.39) * field_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 + 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;
return { c, N, pitch, pitchY, wX, wY, port, rows, cols, rowY, mount, high, faces, routing, leap, order, links,
row, pair, lead_m, field_m, pairs, siteEnds, ohm, ohmLead, ohmSite, bothNear, endRun, ret,
short, needs, smallest, jumpers, jumper_m, loop, arrayLoop, homeLoop, sep, saved, hot, fLead, fSite,
minusPt, plusPt, minus, plus, rowOf, colOf, x0, y0, turned };
}
// ===== SERIES RESISTANCE AT THREE SCALES =======================================================
// IMPLANTED, function by function, from LIB/solar-resistance/resistance.mjs — a pure ES-module
// library that passes 73 of 73 self-tests (node test.mjs) and reproduces the farm bench totals
// exactly. What is copied here: the data tables (section 1), collectInputs / inputStatus
// (section 2), r20PerKm / tempFactor / ohmPerKmAt (section 3), normalisePlan + segmentConductors
// (section 4), connectorPairs (section 5), stringResistance (section 6), ampacity (section 7),
// blockResistance + farmScale (section 8). Nothing is re-derived and nothing is improved on.
// IT IS FED THE CONDUCTORS THE DRAWING ALREADY HAS — the module leads, the cable laid along the
// table, the two home runs — so there is one geometry and not two. EVERY NUMBER FROM HERE GOES
// TO THE ANSWER AND THE ONE LINE KEY. None of it is ever drawn.
const RES = (function () {
// --- 1. DATA, copied value for value ---------------------------------------------------------
const R20 = { 1.5:13.7, 2.5:8.21, 4:5.09, 6:3.39, 10:1.95, 16:1.24 }; // the conductor standard, class 5 tinned, maximum R20 ohm/km — by clause and value only
const ALPHA = 0.00393; // copper, from 20 C
const A3 = { single_free_in_air:{2.5:41,4:55,6:70,10:98,16:132},
single_on_a_surface:{2.5:39,4:52,6:67,10:93,16:125},
two_loaded_touching_on_a_surface:{2.5:33,4:44,6:57,10:79,16:107} }; // the PV cable standard, Table A.3, stated at 60 C ambient
const K_AMB = { 60:1.0, 70:0.92, 80:0.84, 90:0.75 }; // Table A.4. REFUSE above 90 C rather than extrapolate.
const IN_SUN = { 'frame-clip':true, 'c-rail':true, tray:true, 'conduit-duct':false, buried:false, 'free-air':true };
// The array standard wants + and − bundled to hold the loop area down, so the PAIRED column
// applies everywhere the pair is bundled — which is everywhere but a genuinely single free-air run.
const METHOD = { 'frame-clip':'two_loaded_touching_on_a_surface', 'c-rail':'two_loaded_touching_on_a_surface',
tray:'two_loaded_touching_on_a_surface', 'conduit-duct':'two_loaded_touching_on_a_surface',
buried:'two_loaded_touching_on_a_surface', 'free-air':'single_free_in_air' };
// THE PRESET PROPOSAL: what containment each kind of conductor gets before anybody types
// anything — leads clipped to the frame, the along-table run on C rail, the home run on tray to
// the edge of the block and then in duct to the inverter. The 60/40 split is ASSUMED. It is a
// declared input: pass containment:{site:'conduit-duct'} or a full per-kind plan to change it.
const PRESET = { lead:[{ containment:'frame-clip', frac:1 }], site:[{ containment:'c-rail', frac:1 }],
homerun:[{ containment:'tray', frac:0.6 }, { containment:'conduit-duct', frac:0.4 }] };
// One inverter block: 24 strings, home runs declared band by band. Mean 45 m, which is the
// practice mode and matches the 44.61 m a string the farm file implies. ASSUMED.
const BANDS = [{ strings:8, home_run_m:20 }, { strings:8, home_run_m:45 }, { strings:8, home_run_m:70 }];
// THE FARM IS READ, NOT RECOMPUTED. These km were summed block by block by the bench.
const FARM = { blocks:963, strings:20222, builds: {
sequential: { lead_km:382.196, site_km:2570.336 },
'leapfrog-turned': { lead_km:1216.960, site_km:1804.246 },
'leapfrog-two-lead-lengths': { lead_km:1726.554, site_km:1821.233 } } };
const FARM_BUILD = { sequential:'sequential', leapfrog:'leapfrog-two-lead-lengths', 'leapfrog-turned':'leapfrog-turned' };
const LABEL = { sequential:'sequential', leapfrog:'leapfrog', 'leapfrog-turned':'leapfrog rear-turned' };
// --- 3. CABLE MATHS --------------------------------------------------------------------------
const tempFactor = t => 1 + ALPHA * (t - 20);
const ohmPerKmAt = (mm2, t) => (R20[mm2] || R20[4]) * tempFactor(t);
// --- 4. SEGMENTS. Split every conductor's route into segments with a containment. -------------
function normalisePlan(plan, L) { // metres win over fractions
const steps = plan.map(s => Object.assign({}, s));
let fixed = 0, fracTotal = 0;
for (const s of steps) { if (typeof s.length_m === 'number') fixed += s.length_m; else fracTotal += (typeof s.frac === 'number' ? s.frac : 1); }
const left = Math.max(0, L - fixed);
for (const s of steps) if (typeof s.length_m !== 'number') { const f = typeof s.frac === 'number' ? s.frac : 1; s.length_m = fracTotal === 0 ? 0 : left * f / fracTotal; }
return steps;
}
function segmentConductors(conductors, opts) {
opts = opts || {}; const preset = opts.preset || PRESET, overrides = opts.overrides || {};
const segments = [];
for (const c of conductors) {
const L = c.length_m, plan = normalisePlan(overrides[c.id] || preset[c.kind] || [{ containment:'free-air', frac:1 }], L);
let acc = 0;
plan.forEach((step, i) => {
const segLen = i === plan.length - 1 ? L - acc : step.length_m; // the last step absorbs the crumbs so the sum is exact
segments.push({ id:c.id + '#' + i, conductor_id:c.id, kind:c.kind, index:i, containment:step.containment,
in_sun: IN_SUN[step.containment] === true, length_m:segLen, circuits_sharing:1,
run_id:(step.containment === 'tray' || step.containment === 'conduit-duct' || step.containment === 'buried')
? step.containment + ':block' : step.containment + ':string' });
acc += segLen;
});
}
const runs = new Map(); // circuits_sharing = conductors in the same containment run
for (const s of segments) { if (!runs.has(s.run_id)) runs.set(s.run_id, new Set()); runs.get(s.run_id).add(s.conductor_id); }
for (const s of segments) s.circuits_sharing = runs.get(s.run_id).size;
return { segments, total_length_m: segments.reduce((t, s) => t + s.length_m, 0) };
}
// --- 5. CONNECTOR COUNT ----------------------------------------------------------------------
// sequential N+2 mated pairs, leapfrog (either) N+1 — BENCH. The far end is the difference: a
// sequential string is joined to its return run out there, a leapfrog string is not.
const connectorPairs = (wiring, N) => ({ factory_mated:N - 1, site_made: wiring === 'sequential' ? 3 : 2,
total: N - 1 + (wiring === 'sequential' ? 3 : 2) });
// --- 2. INPUT STATUS. Every value is TYPED or ASSUMED and the count is reported. --------------
function collect(defaults, user) {
const out = {};
for (const k of Object.keys(defaults)) {
const d = defaults[k], has = user && user[k] !== undefined && user[k] !== null;
out[k] = { key:k, value: has ? user[k] : d.value, status: has ? 'TYPED' : 'ASSUMED', source: has ? 'typed by the user' : d.source };
}
return out;
}
function inputStatus(inputs) {
const all = Object.keys(inputs).map(k => inputs[k]), assumed = all.filter(v => v.status === 'ASSUMED');
return { n:all.length, assumed:assumed.length, typed:all.length - assumed.length,
words: assumed.length + ' of ' + all.length + ' inputs assumed', assumed_keys:assumed.map(v => v.key) };
}
// --- 6. SERIES RESISTANCE BUILD-UP, one string -----------------------------------------------
function stringResistance(o) {
const T = o.conductor_temp_c, n = Math.max(1, o.n_parallel);
const mm2 = { lead:o.lead_mm2, site:o.site_mm2, homerun:o.homerun_mm2 };
const parallelKinds = o.parallel_scope === 'all' ? ['lead','site','homerun'] : ['site','homerun'];
const seg = segmentConductors(o.conductors, { preset:o.preset, overrides:o.containment_overrides });
const by = { lead:0, site:0, homerun:0 }, r = { lead:0, site:0, homerun:0 };
for (const c of o.conductors) {
const kind = by[c.kind] !== undefined ? c.kind : 'site';
by[kind] += c.length_m;
const rr = c.length_m / 1000 * ohmPerKmAt(mm2[kind], T);
r[kind] += parallelKinds.indexOf(kind) >= 0 ? rr / n : rr; // n cables a pole divide the laid cable, never the module leads
}
const pairs = connectorPairs(o.wiring, o.modules_per_string);
const r_contact_ohm = pairs.total * o.contact_mohm_per_pair / 1000;
const r_cable_ohm = r.lead + r.site + r.homerun, r_total_ohm = r_cable_ohm + r_contact_ohm;
const imp = o.module_imp_a, vmp = o.modules_per_string * o.module_vmp_v, p = imp * vmp;
return { wiring:o.wiring, wiring_label:LABEL[o.wiring] || o.wiring, length_m:by.lead + by.site + by.homerun,
length_by_kind_m:by, segments:seg.segments,
resistance:{ r_lead_ohm:r.lead, r_site_ohm:r.site, r_homerun_ohm:r.homerun, r_cable_ohm, r_contact_ohm, r_total_ohm },
connectors:pairs, current_a:imp, vmp_string_v:vmp, p_string_w:p,
vdrop_v:imp * r_total_ohm, vdrop_pct:imp * r_total_ohm / vmp * 100,
loss_w:imp * imp * r_total_ohm, loss_pct:imp * imp * r_total_ohm / p * 100 };
}
// --- 7. AMPACITY. NO DEFAULT GROUP FACTOR, ON PURPOSE. ---------------------------------------
// The group factor decides the check, so a default would at once become an input divided by an
// input. Without one the verdict is null and the reason is: group factor must be typed. The
// SITUATION still comes back, because that is what a person needs in order to type the factor.
function ampacity(o) {
const method = METHOD[o.containment] || 'two_loaded_touching_on_a_surface';
const table_value_a = (A3[method] || {})[o.csa_mm2];
const k = K_AMB[o.ambient_c] !== undefined ? K_AMB[o.ambient_c] : null;
const design_current_a = o.module_isc_a * o.design_current_factor / Math.max(1, o.n_parallel);
const out = { containment:o.containment, csa_mm2:o.csa_mm2, ambient_c:o.ambient_c,
situation:{ circuits_sharing:o.circuits_sharing, containment:o.containment, installation_method:method,
words:o.circuits_sharing + ' conductor' + (o.circuits_sharing === 1 ? '' : 's') + ' sharing one ' + o.containment + ' run, ' + method.replace(/_/g, ' ') },
table_value_a: table_value_a === undefined ? null : table_value_a, k_ambient:k,
group_factor:null, group_factor_status:'NOT GIVEN', rating_a:null,
design_current_a, verdict:null, reason:'group factor must be typed' };
if (table_value_a === undefined) out.reason = 'no Table A.3 value for ' + o.csa_mm2 + ' mm2 in ' + method.replace(/_/g, ' ');
else if (k === null) out.reason = 'no Table A.4 ambient correction at ' + o.ambient_c + ' C; above 90 C it is refused, not extrapolated';
const gf = o.group_factor;
if (gf !== undefined && gf !== null && out.reason === 'group factor must be typed') {
out.group_factor = gf; out.group_factor_status = 'TYPED';
out.rating_a = Math.round(table_value_a * k * gf * 10) / 10;
out.verdict = out.rating_a >= design_current_a ? 'PASS' : 'FAIL';
out.reason = table_value_a + ' A x ' + k + ' ambient x ' + gf + ' grouping = ' + out.rating_a + ' A against a design current of ' + (Math.round(design_current_a * 100) / 100) + ' A';
}
return out;
}
return { R20, A3, K_AMB, PRESET, BANDS, FARM, FARM_BUILD, LABEL, METHOD, tempFactor, ohmPerKmAt,
segmentConductors, connectorPairs, collect, inputStatus, stringResistance, ampacity };
})();
// WHAT THE ANSWER SAYS ABOUT RESISTANCE, at one string, one inverter block of 24 strings, and the
// whole farm of 963 blocks and 20,222 strings. Fed from the drawing's own conductors. Never drawn.
function resistanceAnswer(g, inp) {
const c = g.c, u = inp || {};
const wiring = g.routing === 'one-after-another' ? 'sequential'
: (g.leap && c.turn_every_second) ? 'leapfrog-turned' : 'leapfrog';
// THE CONDUCTORS THE DRAWING ALREADY HAS. The two home runs are the pair to the inverter; what
// is left of the cable laid on site is the along-table run, the return if one is laid, and any
// jumper spliced in. Nothing new is measured here.
const homerun_m = 2 * c.near_end_m, site_m = Math.max(0, g.field_m - homerun_m);
const conductors = [];
for (let k = 1; k <= g.N; k++) conductors.push({ id:'lead' + k, kind:'lead', length_m:g.pair });
conductors.push({ id:'site', kind:'site', length_m:site_m });
conductors.push({ id:'homerun', kind:'homerun', length_m:homerun_m });
// EVERY INPUT IS TAGGED. Typed means the reader typed it in the command; assumed means we chose it.
const typedTemp = u.conductor_c !== undefined && u.conductor_c !== null || u.t_site_c !== undefined;
const D = {
modules_per_string:{ value:g.N, source:'BENCH: 30 modules to a string' },
module_vmp_v:{ value:c.module_vmp, source:'module class, large-format bifacial' },
module_imp_a:{ value:c.amps, source:'module class, large-format bifacial' },
module_isc_a:{ value:18.45, source:'module class, large-format bifacial' },
lead_mm2:{ value:c.lead_mm2, source:'module lead pair as supplied is 4 mm2' },
site_mm2:{ value:c.cable_mm2, source:'the order log: 4 and 6 mm2 are a dead heat' },
homerun_mm2:{ value:c.cable_mm2, source:'the order log: 4 and 6 mm2 are a dead heat' },
conductor_temp_c:{ value:c.t_site_c, source:'BENCH: a conductor temperature is a RESULT, not a rating' },
ambient_c:{ value:90, source:'the highest ambient the cable class is rated for — the honest worst case' },
contact_mohm_per_pair:{ value:c.contact_milliohm, source:'BENCH: 0.35 milliohm a mated pair. The weakest number here — measure it before quoting anything that turns on it.' },
n_parallel:{ value:1, source:'one cable a pole' },
parallel_scope:{ value:'site+homerun', source:'n a pole applies to the cable laid on site, not to the module leads' },
home_run_m:{ value:c.near_end_m, source:'the drawing: the near end of the table from the inverter' },
design_current_factor:{ value:1.375, source:'the array standard 1.25 on Isc times an ASSUMED 1.1 for bifacial rear gain' },
containment:{ value:'preset', source:'the proposal: leads frame-clipped, the along-table run on C rail, the home run 60% tray then 40% duct' },
home_run_bands_m:{ value:'20/45/70, eight strings each', source:'BENCH block_plan; mean 45 m matches the 44.61 m a string the farm file implies' },
group_factor:{ value:null, source:'NO DEFAULT, on purpose: it decides the ampacity check' },
};
const user = { modules_per_string:u.modules, module_vmp_v:u.module_vmp, module_imp_a:u.amps,
module_isc_a:u.module_isc_a, lead_mm2:u.lead_mm2, site_mm2:u.cable_mm2, homerun_mm2:u.cable_mm2,
conductor_temp_c: typedTemp ? c.t_site_c : undefined, ambient_c:u.ambient_c,
contact_mohm_per_pair:u.contact_milliohm, n_parallel:u.n_parallel, parallel_scope:u.parallel_scope,
home_run_m:u.near_end_m, design_current_factor:u.design_current_factor,
containment:u.containment ? 'typed' : undefined, home_run_bands_m:u.home_run_bands ? 'typed' : undefined,
group_factor:u.group_factor };
const inputs = RES.collect(D, user), status = RES.inputStatus(inputs);
const v = k => inputs[k].value;
// CONTAINMENT PER SEGMENT is a declared input. Typing containment:{site:'conduit-duct'} or a
// full plan per kind replaces the preset proposal for that kind and nothing else.
const preset = Object.assign({}, RES.PRESET);
if (u.containment && typeof u.containment === 'object') for (const k of Object.keys(u.containment)) {
const val2 = u.containment[k];
preset[k] = typeof val2 === 'string' ? [{ containment:val2, frac:1 }] : val2;
}
const bands = (u.home_run_bands && u.home_run_bands.length) ? u.home_run_bands : RES.BANDS;
// THE WHOLE PIPELINE AS A FUNCTION OF THE DECLARED INPUT VALUES. The default run is this fired
// once with the values as declared; the sensitivity below is this fired again with ONE value
// nudged. There is no second model and no derivative: it is the same code path, enumerated.
function scales(val) {
const cond = [];
for (let k = 1; k <= val.modules_per_string; k++) cond.push({ id:'lead' + k, kind:'lead', length_m:g.pair });
cond.push({ id:'site', kind:'site', length_m:site_m });
cond.push({ id:'homerun', kind:'homerun', length_m:2 * val.home_run_m });
const S2 = RES.stringResistance({ conductors:cond, wiring, preset,
modules_per_string:val.modules_per_string, module_vmp_v:val.module_vmp_v, module_imp_a:val.module_imp_a,
lead_mm2:val.lead_mm2, site_mm2:val.site_mm2, homerun_mm2:val.homerun_mm2,
conductor_temp_c:val.conductor_temp_c, contact_mohm_per_pair:val.contact_mohm_per_pair,
n_parallel:val.n_parallel, parallel_scope:val.parallel_scope });
// ONE INVERTER BLOCK: 24 strings, the home run declared band by band. Only the home run changes
// from band to band, so the band's string is this string with its home run put back.
const ohmHome = RES.ohmPerKmAt(val.homerun_mm2, val.conductor_temp_c) / 1000 / Math.max(1, val.n_parallel);
const rest = S2.resistance.r_total_ohm - S2.resistance.r_homerun_ohm;
const bandStrings = [];
for (const b of bands) for (let i = 0; i < b.strings; i++) {
const r_total = rest + 2 * b.home_run_m * ohmHome;
bandStrings.push({ home_run_m:b.home_run_m, r_total_ohm:r_total, vdrop_v:S2.current_a * r_total,
vdrop_pct:S2.current_a * r_total / S2.vmp_string_v * 100, loss_w:S2.current_a * S2.current_a * r_total });
}
const nS = bandStrings.length, sum = f => bandStrings.reduce((t, x) => t + f(x), 0);
const B2 = { n_strings:nS, home_run_bands:bands,
r_total_ohm_mean:sum(x => x.r_total_ohm) / nS,
r_total_ohm_min:Math.min.apply(null, bandStrings.map(x => x.r_total_ohm)),
r_total_ohm_max:Math.max.apply(null, bandStrings.map(x => x.r_total_ohm)),
vdrop_v_mean:sum(x => x.vdrop_v) / nS, vdrop_pct_mean:sum(x => x.vdrop_pct) / nS,
vdrop_pct_max:Math.max.apply(null, bandStrings.map(x => x.vdrop_pct)),
loss_w:sum(x => x.loss_w), p_w:nS * S2.p_string_w,
connectors:nS * S2.connectors.total };
B2.loss_pct = B2.loss_w / B2.p_w * 100;
// THE FARM IS READ, NOT RECOMPUTED: the km were summed block by block by the bench and are
// carried here as constants. The loss is this block's loss across 963 blocks.
const fb = RES.FARM.builds[RES.FARM_BUILD[wiring]];
const F2 = { blocks:RES.FARM.blocks, strings:RES.FARM.strings, build:RES.FARM_BUILD[wiring],
lead_km:fb.lead_km, site_km:fb.site_km, total_km:fb.lead_km + fb.site_km,
km_source:'BENCH constants, summed block by block — not recomputed from this drawing',
r_total_ohm_mean:B2.r_total_ohm_mean, vdrop_v_mean:B2.vdrop_v_mean, vdrop_pct_mean:B2.vdrop_pct_mean,
loss_w:B2.loss_w * RES.FARM.blocks, p_w:B2.p_w * RES.FARM.blocks,
connectors:B2.connectors * RES.FARM.blocks };
F2.loss_pct = F2.loss_w / F2.p_w * 100;
return { S:S2, B:B2, F:F2 };
}
const V0 = {}; for (const k of Object.keys(inputs)) V0[k] = inputs[k].value;
const base = scales(V0), S = base.S, B = base.B, F = base.F;
// --- SENSITIVITY BY ENUMERATION. Every numeric input is nudged in turn and the three scales are
// recomputed from scratch. A cross-section is a catalogue step, not a dial, so its nudge is the
// NEXT LISTED SIZE and it is labelled as such; everything else gets +10%. An input that moves
// nothing moves nothing — that is reported, not hidden.
const NEXT_CSA = { 1.5:2.5, 2.5:4, 4:6, 6:10, 10:16, 16:null };
const IS_CSA = { lead_mm2:1, site_mm2:1, homerun_mm2:1 };
const SHORT = { modules_per_string:'modules', module_vmp_v:'Vmp', module_imp_a:'Imp', module_isc_a:'Isc',
lead_mm2:'lead mm2', site_mm2:'site mm2', homerun_mm2:'homerun mm2', conductor_temp_c:'conductor C',
ambient_c:'ambient C', contact_mohm_per_pair:'contact mOhm', n_parallel:'n a pole', home_run_m:'home run m',
design_current_factor:'design factor' };
const movers = [];
for (const k of Object.keys(V0)) {
const v0 = V0[k];
if (typeof v0 !== 'number' || !isFinite(v0)) continue;
const v1 = IS_CSA[k] ? NEXT_CSA[v0] : v0 * 1.1;
if (v1 === null || v1 === undefined || v1 === v0) continue;
const alt = Object.assign({}, V0); alt[k] = v1;
let t; try { t = scales(alt); } catch (e) { continue; }
const rel = (a, b2) => a === 0 ? 0 : (b2 - a) / a * 100;
movers.push({ key:k, label:SHORT[k] || k, status:inputs[k].status,
how: IS_CSA[k] ? ('to ' + v1 + ' mm2') : '+10%', from:v0, to:v1,
string_pct:rel(base.S.loss_w, t.S.loss_w), block_pct:rel(base.B.loss_w, t.B.loss_w),
farm_pct:rel(base.F.loss_w, t.F.loss_w) });
}
const topBy = f => movers.slice().sort((a, b2) => Math.abs(f(b2)) - Math.abs(f(a))).slice(0, 3);
const sensitivity = { method:'each input nudged in turn, the whole answer fired again; no calculus',
nudge:'+10%, except a cross-section which steps to the next listed size',
measured:'change in I2R loss at that scale', all:movers,
string:topBy(m => m.string_pct), block:topBy(m => m.block_pct), farm:topBy(m => m.farm_pct) };
// THE AMPACITY SITUATION, run by run. The verdict is null everywhere until a group factor is typed.
const seenRuns = {}, amps = [];
for (const s of S.segments) {
if (seenRuns[s.run_id]) continue; seenRuns[s.run_id] = 1;
amps.push(RES.ampacity({ containment:s.containment, circuits_sharing:s.circuits_sharing,
csa_mm2: s.kind === 'lead' ? v('lead_mm2') : s.kind === 'site' ? v('site_mm2') : v('homerun_mm2'),
ambient_c:v('ambient_c'), module_isc_a:v('module_isc_a'), design_current_factor:v('design_current_factor'),
n_parallel:v('n_parallel'), group_factor:v('group_factor') }));
}
// THE TABLE, three scales side by side, as fixed-width text for the pop-up.
const pad = (s, w) => { s = String(s); return s.length >= w ? s : s + ' '.repeat(w - s.length); };
const rpad = (s, w) => { s = String(s); return s.length >= w ? s : ' '.repeat(w - s.length) + s; };
const row = (label, a, b2, d) => pad(label, 26) + rpad(a, 14) + rpad(b2, 16) + rpad(d, 18);
const oh = x => x.toFixed(4) + ' Ω';
// A MOVER CELL: the input's short name, how it was nudged, and what that did to this column.
const sgn = x => (x >= 0 ? '+' : '') + x.toFixed(2) + '%';
const mcell = (list, i, f) => list[i] ? list[i].label + ' ' + list[i].how + ' ' + sgn(f(list[i])) : '—';
const mrow = (label, i) => pad(label, 26) + pad(mcell(sensitivity.string, i, m => m.string_pct), 24)
+ pad(mcell(sensitivity.block, i, m => m.block_pct), 24)
+ pad(mcell(sensitivity.farm, i, m => m.farm_pct), 24);
const frow = (a, b2, d, e, f2) => pad(a, 30) + rpad(b2, 12) + rpad(d, 14) + rpad(e, 14) + ' ' + f2;
const lines = [
row('', 'PER STRING', 'PER BLOCK (24)', 'PER FARM (20,222)'),
row('module leads', oh(S.resistance.r_lead_ohm), '—', '—'),
row('cable along the table', oh(S.resistance.r_site_ohm), '—', '—'),
row('home run (2 x ' + v('home_run_m') + ' m)', oh(S.resistance.r_homerun_ohm), '—', '—'),
row('cable subtotal', oh(S.resistance.r_cable_ohm), '—', '—'),
row(S.connectors.total + ' pairs x ' + v('contact_mohm_per_pair') + ' mΩ', oh(S.resistance.r_contact_ohm), '—', '—'),
row('SERIES RESISTANCE', oh(S.resistance.r_total_ohm), oh(B.r_total_ohm_mean) + ' mean', oh(F.r_total_ohm_mean) + ' mean'),
row(' range over the bands', '—', oh(B.r_total_ohm_min) + '–' + B.r_total_ohm_max.toFixed(4), '—'),
row('volt drop', S.vdrop_v.toFixed(2) + ' V', B.vdrop_v_mean.toFixed(2) + ' V mean', F.vdrop_v_mean.toFixed(2) + ' V mean'),
row('volt drop %', S.vdrop_pct.toFixed(3) + ' %', B.vdrop_pct_mean.toFixed(3) + ' %', F.vdrop_pct_mean.toFixed(3) + ' %'),
row('loss', S.loss_w.toFixed(1) + ' W', (B.loss_w / 1000).toFixed(3) + ' kW', (F.loss_w / 1e6).toFixed(3) + ' MW'),
row('loss % of DC', S.loss_pct.toFixed(3) + ' %', B.loss_pct.toFixed(3) + ' %', F.loss_pct.toFixed(3) + ' %'),
row('conductor', (S.length_m).toFixed(1) + ' m', (S.length_m * 24 / 1000).toFixed(3) + ' km', (F.total_km).toFixed(3) + ' km'),
row('mated pairs', S.connectors.total, B.connectors, F.connectors),
'',
// WHICH INPUTS MATTER, scale by scale, sitting under the column each one belongs to.
'WHAT MOVES EACH COLUMN. ' + status.words + ', so here is which of them the answer actually',
'turns on: each input nudged in turn and the whole answer fired again — enumeration, not calculus.',
'Nudge: +10%, except a cross-section, which steps to the next listed size. Measured on I2R loss.',
row('', 'PER STRING', 'PER BLOCK (24)', 'PER FARM (20,222)'),
mrow('1st mover', 0), mrow('2nd mover', 1), mrow('3rd mover', 2),
' ' + (movers.filter(m => Math.abs(m.string_pct) < 1e-9).map(m => m.label).join(', ') || 'none') + ' move the loss not at all',
' the block and the farm cannot see the home run length: their home runs come from the bands',
'',
// THE FARM COLUMN, SAID PLAINLY: its km are constants, and all three builds are shown.
'THE FARM COLUMN IS NOT COMPUTED FROM THIS DRAWING. Its conductor km are BENCH CONSTANTS, summed',
'block by block over ' + F.blocks + ' blocks and ' + F.strings.toLocaleString('en-GB') + ' strings. The three builds as the bench left them:',
frow('build', 'lead km', 'site km', 'total km', ''),
].concat(Object.keys(RES.FARM.builds).map(k =>
frow(' ' + k, RES.FARM.builds[k].lead_km.toFixed(3), RES.FARM.builds[k].site_km.toFixed(3),
(RES.FARM.builds[k].lead_km + RES.FARM.builds[k].site_km).toFixed(3),
k === F.build ? '<-- this drawing' : ''))).concat([
' the loss and the resistance in that column ARE computed: this block, taken ' + F.blocks + ' times.',
'',
'n cables in parallel a pole: ' + v('n_parallel') + ' (' + inputs.n_parallel.status + '), applied to ' + v('parallel_scope'),
'containment: ' + S.segments.map(s => s.kind + ' ' + s.containment + ' ' + s.length_m.toFixed(1) + ' m').filter((x, i, a) => a.indexOf(x) === i).join('; '),
'ampacity: verdict null everywhere — group factor must be typed',
status.words + ' — the movers above say which of those assumptions are worth typing first',
]);
const key = 'STRING ' + S.resistance.r_total_ohm.toFixed(4) + ' Ω · ' + S.vdrop_v.toFixed(2) + ' V · '
+ S.vdrop_pct.toFixed(2) + '% · ' + S.loss_w.toFixed(0) + ' W | BLOCK ' + (B.loss_w / 1000).toFixed(2) + ' kW | FARM '
+ (F.loss_w / 1e6).toFixed(2) + ' MW · ampacity null, group factor must be typed · ' + status.words;
return { wiring, wiring_label:S.wiring_label, string:S, block:B, farm:F, ampacity:amps,
inputs, status, sensitivity, containment_preset:preset, table:lines, table_text:lines.join('\n'), key };
}
function run(inp) {
const g = build(inp), c = g.c, worst = g.short.length ? Math.max(...g.short.map(l => l.need - g.pair)) : 0;
const RE = resistanceAnswer(g, inp);
const name = LAYOUT_WORDS(g) + ', ' + (ROUTE_WORDS[g.routing] || g.routing)
+ (c.turn_every_second ? ', every second module turned end for end' : '');
// A SERIES CIRCUIT IS OPEN OR IT IS NOT. One pair of connectors that does not meet and the whole
// string carries nothing: not a warm link, not a derated string, NOTHING, anywhere in it.
const open = g.short.length > 0, amps = open ? 0 : c.amps;
// AN OPEN STRING IS NOT A DEAD STRING. No current flows, and that is the whole of what "open" means;
// the modules go on making their open circuit voltage, so the full string voltage stands across a
// break, and an open connector under that voltage is exactly where a direct current arc begins.
const voc = g.N * c.module_voc;
const order = g.order.map(k => 'M' + k).join(' → ');
const hotWords = g.hot.length ? ' RATING CHECK FAILED: ' + g.hot.join('; ') + '. ' : '';
const loopWords = g.sep === null
? ' The whole loop needs the home run separation: it moves the answer more than the wiring does, so only the array loop is given.'
: ' Loop ' + g.loop.toFixed(1) + ' m2 in all, of which the home run pair is ' + g.homeLoop.toFixed(1) + ' m2.';
const said = hotWords + name + ': ' + g.N + ' modules over ' + g.rows + (g.rows === 1 ? ' row' : ' rows') + ' of ' + g.cols + ', ' + g.links.length + ' links from ' + Math.min(...g.needs).toFixed(2) + ' to ' + Math.max(...g.needs).toFixed(2) + ' m against a lead pair of ' + g.pair.toFixed(2) + ' m; '
+ (g.bothNear ? 'both free ends land at the near end, so no return cable is laid; ' : 'a return cable of ' + g.ret.toFixed(1) + ' m brings the far end home; ')
+ (g.jumpers.length ? g.jumpers.length + (g.jumpers.length === 1 ? ' link is' : ' links are') + ' made up with a jumper spliced in on site, ' + g.jumper_m.toFixed(1) + ' m of cable and ' + g.jumpers.length + ' more mated pairs; ' : '')
+ (open ? 'THE CIRCUIT IS OPEN AND BOTH ENDS ARE LIVE: ' + g.short.length + ' links do not reach (short by up to ' + worst.toFixed(2) + ' m), so no current flows anywhere, but up to '
+ voc.toFixed(0) + ' V stands across a break and an open connector at that voltage is where a direct current arc starts'
: 'every link reaches, so the loop closes and ' + c.amps + ' A flows all the way round it')
+ '; ' + g.lead_m.toFixed(1) + ' m of module lead and ' + g.field_m.toFixed(1) + ' m of cable laid on site; '
+ loopWords + ' '
+ (open ? g.ohm.toFixed(3) + ' ohm IF IT WERE CLOSED, and ' + (c.amps * c.amps * g.ohm).toFixed(0) + ' W lost at ' + c.amps + ' A: nothing is lost in it now because nothing flows in it'
: g.ohm.toFixed(3) + ' ohm, ' + (amps * amps * g.ohm).toFixed(0) + ' W lost at ' + amps + ' A');
// THE CONNECTION LIST, in the order the current runs, terminal by terminal. It is the same walk the
// checks make, so what a reader sees in words is what the drawing was built from.
const connections = [{ from:'INV\u2212', to:'M' + g.order[0] + '\u2212', metres:c.near_end_m, home:true, node:'home-' }];
g.links.forEach((l, i) => connections.push({ node:'L' + i, from:'M' + l.from + '+', to:'M' + l.to + '\u2212',
needed:rnd(l.need, 2), pair:rnd(g.pair, 2), reaches:l.reaches, jumper:rnd(l.jumper || 0, 2) }));
connections.push({ from:'M' + g.order[g.order.length - 1] + '+', to:'INV+', metres:c.near_end_m, home:true, node:'home+' });
return { connections, numbers: { circuit: open ? 'OPEN, both ends live' : 'closed', current_a: rnd(amps, 2),
open_circuit_volts_at_25c: rnd(voc, 0), volts_across_a_break: open ? rnd(voc, 0) : 0, links: g.links.length,
shortest_link_m: rnd(Math.min(...g.needs), 3), longest_link_m: rnd(Math.max(...g.needs), 3), lead_pair_m: rnd(g.pair, 3),
links_that_do_not_reach: g.short.length, worst_shortfall_m: rnd(worst, 3), module_lead_m: rnd(g.lead_m, 1), cable_laid_on_site_m: rnd(g.field_m, 1),
total_conductor_m: rnd(g.lead_m + g.field_m, 1), connector_pairs: g.pairs, string_resistance_ohm: rnd(g.ohm, 4), loss_w: rnd(amps * amps * g.ohm, 1),
volt_drop_v: rnd(amps * g.ohm, 2), row_length_m: rnd(g.row, 2), string_volts_at_vmp: rnd(g.N * c.module_vmp, 0),
loss_w_if_it_were_closed: rnd(c.amps * c.amps * g.ohm, 1),
volts_to_earth_each_end: '−' + rnd(g.N * c.module_vmp / 2, 0) + ' to +' + rnd(g.N * c.module_vmp / 2, 0),
routing: g.routing, rows_of_modules: g.rows, columns_of_modules: g.cols,
modules_in_the_last_column: g.N - (g.cols - 1) * g.rows > 0 ? Math.min(g.rows, g.N - (g.cols - 1) * g.rows) : g.rows,
both_ends_at_the_near_end: g.bothNear, return_cable_m: rnd(g.ret, 2),
smallest_lead_pair_that_reaches_m: rnd(g.smallest, 3),
lead_pair_to_order_m: rnd(g.pair, 3),
connectors_fitted_on_site: g.siteEnds + 2 * g.jumpers.length,
jumpers_made_on_site: g.jumpers.length, jumper_cable_m: rnd(g.jumper_m, 2),
array_loop_m2_rough: rnd(g.arrayLoop, 2),
home_run_loop_m2_rough: g.homeLoop === null ? null : rnd(g.homeLoop, 2),
total_loop_m2_rough: g.loop === null ? null : rnd(g.loop, 2),
site_cable_saved_m: rnd(g.saved, 2),
lead_resistance_ohm: rnd(g.ohmLead, 4), site_cable_resistance_ohm: rnd(g.ohmSite, 4),
rating_check: g.hot.length ? 'FAILED: ' + g.hot.join('; ') : 'passed, both conductors at or under ' + c.rating_c + ' C',
// THE THREE SCALES, from the implanted resistance library. NONE OF THIS IS DRAWN.
series_resistance_ohm_string: rnd(RE.string.resistance.r_total_ohm, 4),
series_resistance_ohm_block_mean: rnd(RE.block.r_total_ohm_mean, 4),
volt_drop_v_string: rnd(RE.string.vdrop_v, 2), volt_drop_pct_string: rnd(RE.string.vdrop_pct, 3),
loss_w_string: rnd(RE.string.loss_w, 1), loss_kw_block: rnd(RE.block.loss_w / 1000, 3),
loss_mw_farm: rnd(RE.farm.loss_w / 1e6, 3), farm_blocks: RE.farm.blocks, farm_strings: RE.farm.strings,
farm_lead_km: RE.farm.lead_km, farm_site_km: RE.farm.site_km,
cables_in_parallel: RE.inputs.n_parallel.value,
ampacity_verdict: null, ampacity_reason: 'group factor must be typed',
inputs_assumed: RE.status.words },
said, electrical_order: order, resistance: RE, resistance_table: RE.table, key: RE.key,
how: 'geometry only: module ' + c.width_m + ' m wide by ' + c.module_height_m + ' m tall in portrait, ' + c.cell_cols + ' by ' + c.cell_rows
+ ' half cells, junction boxes ' + c.box_spacing_m + ' m apart at mid height, a link is the distance between the boxes it joins; leads ' + c.lead_mm2 + ' mm2, site cable ' + c.cable_mm2
+ ' mm2, copper, the leads at ' + c.t_lead_c + ' C and the site cable at ' + c.t_site_c + ' C (give conductor_c and both take that figure); near end ' + c.near_end_m + ' m from the inverter. '
+ 'The site cable temperature is an assumption and it matters: buried is about 30 C, clipped along the structure is near the lead temperature; ' + c.t_site_c + ' C was used here. '
+ 'A link has to span the STRAIGHT DISTANCE IN THE PLANE between the two boxes plus the slack allowance, ' + (+c.slack_m || 0) + ' m here. '
+ 'The boxes sit at mid length of the module\u2019s long side, spread along its short axis, so in portrait they are side by side along the table and in landscape one above the other. '
+ 'A cable to a free end is counted along the structure, not across the diagonal. '
+ 'The loop is in two parts, both rough: the ARRAY loop is the row length times a stated gap, and the HOME RUN loop is the run times how far apart the two cables are laid. '
+ 'Bundling the home run pair shrinks the loop more than the wiring choice does, for either wiring. '
+ 'Site cable not laid, against the same row wired one after another with no module turned and its far end brought home: ' + g.saved.toFixed(2) + ' m. '
+ 'Electrical order ' + order + '. Colour is the POTENTIAL RELATIVE TO THE MINUS TERMINAL, not to earth: the array floats, so either terminal may sit at up to half the '
+ 'array voltage with respect to earth, and a black line does not mean an earthed one. The line does not thicken or thin along the string, because a series circuit carries one current. '
+ 'The moving highlight is the INSTANT THE CIRCUIT CLOSES; after that the current is the same all the way round and nothing travels along the wire. An open string carries no current and is NOT safe: up to '
+ rnd(voc, 0) + ' V at 25 C stands across a break, more when it is cold. '
+ 'Every input can be changed. An estimate, not a study.', string: g, inputs_used: Object.assign({}, c) };
}
// WHAT A READER MAY TURN, in plain words with its unit. The window makes a box out of each of these.
const BOXES = [
{ key:'mounting', label:'mounting', kind:'choice', choices:[['fixed', 'fixed tilt'], ['east-west', 'east and west facing'], ['tracker', 'single axis tracker']] },
{ key:'orientation', label:'modules', kind:'choice', choices:[['portrait', 'portrait'], ['landscape', 'landscape']] },
{ key:'modules_high', label:'modules high (each face)', kind:'number', min:1, max:6, step:1 },
{ key:'turn_alternate_rows', label:'return rows turned round', kind:'choice', choices:[[0, 'no'], [1, 'yes']] },
{ key:'jumpers', label:'jumper where leads fall short', kind:'choice', choices:[[0, 'no, say it is open'], [1, 'yes, splice one in']] },
{ key:'view', label:'drawn as', kind:'choice', choices:[['wiring', 'the back, wiring'], ['scale', 'modules to scale']] },
{ key:'sheet', label:'on', kind:'choice', choices:[[0, 'the night sky'], [1, 'a drawing sheet']] },
{ key:'routing', label:'routing', kind:'choice', choices:[
['one-after-another', 'one after another, with a return cable'],
['serpentine', 'along and back, no return cable'],
['leapfrog', 'leapfrog inside each row'],
['zigzag', 'zigzag between two rows']] },
{ key:'turn_every_second', label:'every second module turned', kind:'choice', choices:[[0, 'no'], [1, 'yes']] },
{ key:'modules', label:'modules', kind:'number', min:2, max:40, step:1 },
{ key:'width_m', label:'module width', unit:'m', kind:'number', min:0.4, max:3, step:0.001 },
{ key:'module_height_m', label:'module height', unit:'m', kind:'number', min:0.4, max:4, step:0.001 },
{ key:'gap_m', label:'gap along the table', unit:'m', kind:'number', min:0, max:1, step:0.005 },
{ key:'gap_up_m', label:'gap up the table', unit:'m', kind:'number', min:0, max:1, step:0.005 },
{ key:'ridge_gap_m', label:'gap at the ridge', unit:'m', kind:'number', min:0, max:2, step:0.01 },
{ key:'tube_gap_m', label:'gap at the torque tube', unit:'m', kind:'number', min:0, max:2, step:0.01 },
{ key:'box_spacing_m', label:'junction boxes apart', unit:'m', kind:'number', min:0.05, max:2, step:0.01 },
{ key:'leads', label:'leads', kind:'choice', choices:[['reach', 'the pair that reaches'], ['supplied', 'as supplied, portrait']] },
{ key:'lead_slack_m', label:'slack in the lead pair', unit:'m', kind:'number', min:0, max:2, step:0.01 },
{ key:'lead_plus_m', label:'+ lead', unit:'m', kind:'number', min:0.05, max:8, step:0.01 },