In this section
- Fire Site transform · faraday / bench/fire_site.js lines 1–101
- Fire Topo transform · faraday / bench/fire_topo.js lines 1–91
- Million storage · faraday / bench/million.py lines 1–119
- Million Check ingest · faraday / bench/million_check.mjs lines 1–41
- National Cases transform · faraday / bench/national_cases.py lines 1–36
- One transform · faraday / bench/one.py lines 1–21
- Page render · faraday / bench/page.py lines 1–89
- Bench — Results Page render · faraday / bench/results/index.html lines 1–50
- Site Cases transform · faraday / bench/site_cases.py lines 1–142
Fire Site
A JavaScript module in the bench folder of Faraday that works with solar, substations and transformers.
transformfaraday / bench/fire_site.js · lines 1–101 of 101 · Entry point · pattern standardSite (shared by 51 files)
- What it does
- It calculates solar, substations and transformers. Defines 9 functions or classes, including standardSite, add, mul, div, conj.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, substations, transformers.
- Downstream impact
- Used directly by 3 files: Commands Check (faraday); Million Check (faraday); Bench — Results Page (faraday).
- What it achieves
- It is built from the standard site helper (`standardSite`), the add step (`add`) and the mul step (`mul`). SITE PULSE in the visitor's browser: a port of `solve` and `record` in `bench/site_cases.py`.
- Why it matters
- Loaded by the Results page. Also imported by Commands Check and Million Check.
- Application
- faraday · bench · JavaScript module
- Uses
- Fire (require)
- Used by
- required by Commands Check (require), required by Million Check (require), loaded by Bench — Results Page (script src), mentioned in Standalone (comment link)
- Produces
- standardSite, add, mul, div, conj, rnd, solve, sitePulse, signed
- Defines here
- standardSite, add, mul, div, conj, rnd, solve, sitePulse, signed
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/fire_site.js:1-101 · blob 4af51f1fc02ee0e7ccde6985896b8832c4bf370a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// 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);Fire Topo
A JavaScript module in the bench folder of Faraday that works with solar, cables, transformers and substations.
transformfaraday / bench/fire_topo.js · lines 1–91 of 91 · Not reached from any entry point (candidate for review) · pattern mulberry (shared by 65 files)
- What it does
- It calculates solar, cables, transformers and substations. Defines 9 functions or classes, including mulberry32, network, add, mul, div.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, cables, transformers, substations.
- Downstream impact
- Used directly by 2 files: Commands Check (faraday); Topo Check (faraday).
- What it achieves
- It is built from the mulberry32 step (`mulberry32`), the network step (`network`) and the add step (`add`). 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.
- Why it matters
- Imported by Commands Check and Topo Check.
- Application
- faraday · bench · JavaScript module
- Uses
- Fire (require)
- Used by
- required by Commands Check (require), required by Topo Check (require)
- Produces
- mulberry32, network, add, mul, div, conj, solve, rnd, run
- Defines here
- mulberry32, network, add, mul, div, conj, solve, rnd, run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/fire_topo.js:1-91 · blob 81b7df22fbd3a6180fc6fe02808bd0361e4298fe · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// 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);Million
A Python command-line tool in the bench folder of Faraday that works with generic site (`generic_site`) (units: kW, kVA).
storagefaraday / bench/million.py · lines 1–119 of 119 · Entry point · pattern shard (shared by 5 files)
- What it does
- It loads data. Defines 7 functions or classes, including mulberry32, nxt, generic_site, one_case, shard. Uses libraries argparse, json, math, os, subprocess. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the mulberry32 step (`mulberry32`), the nxt step (`nxt`) and the one case helper (`one_case`). One seed = one generic site (no real one) x 8 scenarios x 3 load shares = 24 cases. It accepts `--seeds`, `--workers` and `--selftest`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench · Python CLI
- Uses
- Site Cases (import), argparse, json, math, os, subprocess, sys, time, multiprocessing
- Used by
- none found
- Produces
- mulberry32, generic_site, one_case, shard, status, main
- Defines here
- mulberry32, nxt, generic_site, one_case, shard, status, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/million.py:1-119 · blob 59b7a436e9a8f2adc896b7f1dcc5367034786c7a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""bench/million.py - SITE PULSE BY THE MILLION, EVERY TEST TESTED TWICE.
One seed = one generic site (no real one) x 8 scenarios x 3 load shares = 24 cases. Each case is solved here in Python
(site_cases.solve) and AGAIN in JavaScript (fire_site.js, the code the Kuiper runs in a visitor's browser) by million_check.mjs,
which rebuilds the same site from the same seed and must get the same numbers, or the shard is marked DIFFERS.
The site comes from a small stated generator (mulberry32, whole number arithmetic only) written identically in both languages,
because Python's random cannot be reproduced in JavaScript.
Plain Python and node: no server, no browser. Shards on E: (one file per 1,000 seeds, written whole then renamed, so a stop
at any moment loses at most the shards in flight and a restart skips what is finished). Git gets the summary, never the shards.
python bench/million.py --seeds 420000 --workers 16 # about ten million cases
python bench/million.py --selftest
"""
import argparse, json, math, os, subprocess, sys, time
from multiprocessing import Pool
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import site_cases as SC
OUT = os.environ.get('MILLION_OUT', r'E:\faraday-bench\million')
PER_SHARD = 1000
LOADS = (1.0, 0.6, 0.3)
KVA = (500, 800, 1000, 1600, 2000); LIMITS = (0, 50, 200, 500, 1000); GENS = (0, 250, 500, 1000)
def mulberry32(a):
a &= 0xFFFFFFFF
def nxt():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = a
t = ((t ^ (t >> 15)) * (t | 1)) & 0xFFFFFFFF
t ^= (t + (((t ^ (t >> 7)) * (t | 61)) & 0xFFFFFFFF)) & 0xFFFFFFFF
return ((t ^ (t >> 14)) & 0xFFFFFFFF)
return nxt
def generic_site(seed):
"""Whole numbers only until the last division, so both languages hold exactly the same site."""
g = mulberry32(seed * 2654435761 + 12345); pick = lambda n: g() % n
n = 2 + pick(7); subs = []; total = 0
for k in range(1, n + 1):
kva = KVA[pick(5)]; load = kva * (25 + pick(56)) // 100; total += load
subs.append(dict(n=k, kva=kva, load_kw=load, km=(5 + pick(76)) / 100, tenant=(k == n and pick(10) < 3)))
pv = (total * (20 + pick(131)) // 1000) * 10
return dict(intake_cable_km=(10 + pick(191)) / 100, export_limit_kw=float(LIMITS[pick(5)]), generator_kw=float(GENS[pick(4)]),
pv_kw=float(pv), pv_on=1 + pick(n), subs=subs)
def one_case(site, scen, ls):
_, pv_share, gen_on, off = SC.SCENARIOS[scen]
r = SC.solve(site, pv_share, gen_on, off, ls)
ok = r['rounds'] <= 300 and r['balance'] < 1e-6
export = max(0.0, -r['p_poc_kw']); over = max(0.0, export - site['export_limit_kw'])
vmax = max(r['V'].values()); vmin = min(r['V'].values()); tx = max(r['tx_loading_pct'].values()) if r['tx_loading_pct'] else 0.0
flags = (1 if over > 0 else 0) | (2 if vmax > SC.CANDIDATE['volts_high_pu'] else 0) | (4 if vmin < SC.CANDIDATE['volts_low_pu'] else 0) | (8 if tx > 100 else 0)
return r, ok, flags, vmax, vmin, tx
def shard(i):
path = os.path.join(OUT, 'shards', 's%06d.csv' % i); done = path + '.json'
if os.path.exists(done): return json.load(open(done))
t0 = time.time(); rows = []; ok_n = 0; flag_n = [0, 0, 0, 0]
for seed in range(i * PER_SHARD, (i + 1) * PER_SHARD):
site = generic_site(seed)
for scen in range(1, 9):
for ls in LOADS:
r, ok, flags, vmax, vmin, tx = one_case(site, scen, ls)
ok_n += ok
for b in range(4): flag_n[b] += (flags >> b) & 1
rows.append('%d,%d,%g,%.12g,%.12g,%.12g,%.12g,%.12g,%.12g,%d,%.3g,%d,%d' % (seed, scen, ls, r['p_poc_kw'], r['q_poc_kvar'], r['loss_kw'], vmax, vmin, tx, r['rounds'], r['balance'], flags, 1 if ok else 0))
tmp = path + '.tmp'
with open(tmp, 'w', newline='\n') as f: f.write('seed,scenario,load_share,p_kw,q_kvar,loss_kw,vmax_pu,vmin_pu,worst_tx_pct,rounds,balance,flags,ok\n' + '\n'.join(rows) + '\n')
os.replace(tmp, path)
# THE SECOND OPINION: the same shard, rebuilt from the seeds and solved again by the code the browser runs
try:
c = subprocess.run(['node', os.path.join(HERE, 'million_check.mjs'), path], capture_output=True, text=True, timeout=600)
check = json.loads(c.stdout.strip().splitlines()[-1]) if c.returncode in (0, 1) and c.stdout.strip() else dict(error=(c.stderr or 'no output')[:300])
except Exception as e:
check = dict(error=str(e)[:300])
out = dict(shard=i, cases=len(rows), confirmed=ok_n, refuted=len(rows) - ok_n, export_over=flag_n[0], volts_high=flag_n[1], volts_low=flag_n[2], tx_over=flag_n[3],
seconds=round(time.time() - t0, 2), check=check)
with open(done + '.tmp', 'w') as f: json.dump(out, f)
os.replace(done + '.tmp', done)
return out
def status(done, total_shards, t0, note=''):
cases = sum(d['cases'] for d in done); conf = sum(d['confirmed'] for d in done)
matched = sum(d['check'].get('matched', 0) for d in done); differed = sum(d['check'].get('differed', 0) for d in done)
rdiff = sum(d['check'].get('rounds_differ', 0) for d in done); errs = [d['shard'] for d in done if 'error' in d['check']]
el = time.time() - t0; rate = cases / el if el > 0 else 0
lines = ['# MILLION STATUS ' + time.strftime('%Y-%m-%d %H:%M:%S'), '',
'%d of %d shards; %s cases solved in Python; %s a second this run' % (len(done), total_shards, format(cases, ','), format(int(rate), ',')),
'CONFIRMED %s, REFUTED %s (did not converge or power did not balance)' % (format(conf, ','), format(cases - conf, ',')),
'SECOND OPINION (JavaScript, the code the Kuiper runs): matched %s, DIFFERED %s, rounds differ by count only %s, shards the check could not run %d' % (format(matched, ','), format(differed, ','), format(rdiff, ','), len(errs)),
'What the sites showed: export over the limit %s; volts over 1.06 %s; volts under 0.94 %s; a transformer over its rating %s' % tuple(format(sum(d[k] for d in done), ',') for k in ('export_over', 'volts_high', 'volts_low', 'tx_over')),
note]
if differed or errs: lines.append('ACT: BLOCKED or DIFFERS. first shards: ' + ', '.join(str(d['shard']) for d in done if d['check'].get('differed') or 'error' in d['check'])[:200])
os.makedirs(OUT, exist_ok=True)
with open(os.path.join(OUT, 'STATUS.md'), 'w') as f: f.write('\n'.join(lines) + '\n')
return lines
def main():
ap = argparse.ArgumentParser(); ap.add_argument('--seeds', type=int, default=42000); ap.add_argument('--workers', type=int, default=16); ap.add_argument('--selftest', action='store_true')
a = ap.parse_args()
os.makedirs(os.path.join(OUT, 'shards'), exist_ok=True)
if a.selftest:
s1, s2 = generic_site(7), generic_site(7); assert s1 == s2 and generic_site(8) != s1
r, ok, *_ = one_case(SC.standard_site(), 3, 0.3); assert ok and abs(r['p_poc_kw'] - (-209.1)) < 0.06, r['p_poc_kw']
print('selftest ok; site 7:', json.dumps(s1)[:200]); return
n = (a.seeds + PER_SHARD - 1) // PER_SHARD; t0 = time.time(); done = []
with Pool(a.workers) as pool:
for d in pool.imap_unordered(shard, range(n)):
done.append(d)
if len(done) % 5 == 0 or len(done) == n: status(done, n, t0, 'RUNNING' if len(done) < n else 'FINISHED')
print('\n'.join(status(done, n, t0, 'FINISHED')))
if __name__ == '__main__':
main()Million Check
A JavaScript module in the bench folder of Faraday that works with generic site (`genericSite`) (units: kW, kVA).
ingestfaraday / bench/million_check.mjs · lines 1–41 of 41 · Not reached from any entry point (candidate for review) · pattern mulberry (shared by 65 files)
- What it does
- It loads data. Defines mulberry32, genericSite, close. Uses libraries node:module, node:fs. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the mulberry32 step (`mulberry32`), the generic site helper (`genericSite`) and the close step (`close`). THE SECOND OPINION. Takes one shard written by `million.py`, rebuilds every site from its seed with the same stated generator, solves every case again with `fire_site.js` (the code the Kuiper runs in a visitor's browser).
- Why it matters
- No other file in the estate was found to import it.
- Application
- faraday · bench · JavaScript module
- Uses
- Fire (require), Fire Site (require), node:module, node:fs
- Used by
- none found
- Produces
- genericSite
- Defines here
- mulberry32, genericSite, close
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/million_check.mjs:1-41 · blob 3e97c5544dccfc5a0e5d51825ca512c191354aaa · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// bench/million_check.mjs - THE SECOND OPINION. Takes one shard written by million.py, rebuilds every site from its seed with
// the same stated generator, solves every case again with fire_site.js (the code the Kuiper runs in a visitor's browser), and
// compares number by number (1e-9 relative). The last line printed is one JSON object; exit 1 if any case differs.
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const require = createRequire(import.meta.url);
const FIRE = require('./fire.js'); require('./fire_site.js');
const { solve, SCENARIOS, CANDIDATE } = FIRE.sitePulse;
const KVA = [500, 800, 1000, 1600, 2000], LIMITS = [0, 50, 200, 500, 1000], GENS = [0, 250, 500, 1000];
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; }; }
export function genericSite(seed) {
const g = mulberry32(Number((BigInt(seed) * 2654435761n + 12345n) & 0xFFFFFFFFn)), pick = n => g() % n;
const n = 2 + pick(7), subs = []; let total = 0;
for (let k = 1; k <= n; k++) { const kva = KVA[pick(5)], load = Math.floor(kva * (25 + pick(56)) / 100); total += load;
const km = (5 + pick(76)) / 100, tenant = (k === n) ? pick(10) < 3 : false; subs.push({ n: k, kva, load_kw: load, km, tenant }); }
const pv = Math.floor(total * (20 + pick(131)) / 1000) * 10;
return { intake_cable_km: (10 + pick(191)) / 100, export_limit_kw: LIMITS[pick(5)], generator_kw: GENS[pick(4)], pv_kw: pv, pv_on: 1 + pick(n), subs };
}
const close = (a, b) => a === b || Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
const lines = readFileSync(process.argv[2], 'utf8').split('\n').filter(Boolean).slice(1);
let matched = 0, differed = 0, roundsDiffer = 0, bothRefuse = 0, lastSeed = -1, site = null; const first = [];
for (const l of lines) {
const [seed, scen, ls, p, q, loss, vmax, vmin, tx, rounds] = l.split(',').map(Number);
if (seed !== lastSeed) { site = genericSite(seed); lastSeed = seed; }
const sc = SCENARIOS[scen], r = solve(site, sc[1], sc[2], sc[3], ls);
const vs = Object.values(r.V), txs = Object.values(r.tx_loading_pct);
const got = [r.p_poc_kw, r.q_poc_kvar, r.loss_kw, Math.max(...vs), Math.min(...vs), txs.length ? Math.max(...txs) : 0], want = [p, q, loss, vmax, vmin, tx];
// WHEN THE TWO STOPPED ON DIFFERENT ROUNDS (the last step sat on the 1e-9 volt stopping line), each is one round of a converging
// sweep from the other, and they agree to about 1e-9 relative, not better: judged at 1e-6 and COUNTED, never hidden.
// A CASE THAT DID NOT CONVERGE IN EITHER LANGUAGE (over 300 rounds: the site is beyond what the sweep can solve, and the record
// says REFUTED) has no answer to compare: the two wander apart in the last digits. Counted as both_refuse, not as a match of numbers.
if (r.rounds > 300 && rounds > 300) { bothRefuse++; matched++; continue; }
const tol = r.rounds === rounds ? 1e-9 : 1e-6;
const bad = got.findIndex((g, i) => !(+g.toPrecision(12) === want[i] || Math.abs(g - want[i]) <= tol * Math.max(1, Math.abs(g), Math.abs(want[i]))));
if (bad >= 0) { differed++; if (first.length < 3) first.push({ seed, scen, ls, which: bad, js: got[bad], py: want[bad] }); }
else { matched++; if (r.rounds !== rounds) roundsDiffer++; }
}
console.log(JSON.stringify({ rows: lines.length, matched, differed, rounds_differ: roundsDiffer, both_refuse: bothRefuse, first }));
process.exit(differed ? 1 : 0);National Cases
A Python module in the bench folder of Faraday. It is built from the day step (`day`), the t storage helper (`t_storage`) and the t known helper (`t_known`).
transformfaraday / bench/national_cases.py · lines 1–36 of 36 · Entry point · pattern t_known (shared by 3 files)
- What it does
- It calculates its inputs. Defines day, t_storage, t_known, registry. Uses libraries json, math.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Downstream impact
- Used directly by 1 file: Tests (faraday). Reached from 1 other entry point, including One (faraday).
- What it achieves
- NATIONAL DAY: one spring day of a whole country's electricity, and how much storage it would take. Its code works with 604 GWh, 30.5 GW and 44.4 GW.
- Why it matters
- Checked by Tests.
- Application
- faraday · bench · Python module
- Uses
- json, math
- Used by
- imported by Tests (import)
- Produces
- day, t_storage, t_known, registry
- Defines here
- day, t_storage, t_known, registry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/national_cases.py:1-36 · blob e9e7a7a91b7fc38a84e0bcf97e61b7fd6825bf1b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/national_cases.py - NATIONAL DAY: one spring day of a whole country's electricity, and how much storage it would take.
GENERIC round figures from a published article citing the system operator's public half hourly demand forecast: demand between 18 and
30.5 GW, 604 GWh in the day; a winter peak of about 44.4 GW. The day's shape is a stated smooth curve (CANDIDATE), scaled to the total.
Question: with G gigawatts of steady generation running all day (nuclear, wind, gas, or none), how much must storage deliver?
"""
import json
import math
def day():
raw = [24.25 + 6.25 * math.sin(math.pi * (h / 2.0 - 7) / 12) for h in range(48)] # half hours; low at night, high by day
k = 604.0 / (sum(raw) / 2.0); return [x * k for x in raw]
def t_storage(firm_gw, eff):
d = day(); short = sum(max(0.0, x - firm_gw) for x in d) / 2.0; spare = sum(max(0.0, firm_gw - x) for x in d) / 2.0
need = short / eff
return dict(question='With %g GW of steady generation all day, how much must storage deliver on a 604 GWh spring day, and how much must go in?' % firm_gw,
sentence='National day: %g GW steady generation' % firm_gw, command='fire national-day ' + json.dumps(dict(firm_gw=firm_gw, round_trip=eff), sort_keys=True),
did='48 half hours: demand above the steady generation comes from storage; what goes in is that divided by the round trip efficiency',
numbers=dict(storage_delivers_gwh=round(short, 1), must_be_put_in_gwh=round(need, 1), spare_generation_that_day_gwh=round(spare, 1), day_low_gw=round(min(d), 1), day_high_gw=round(max(d), 1)),
observed='storage delivers %.0f GWh and needs %.0f GWh put in; the steady generation has %.0f GWh to spare that day: %s' % (short, need, spare, 'enough to refill it' if spare >= need else 'NOT enough to refill it'),
assumed='a smooth stated day shape scaled to 604 GWh; round trip efficiency as given', result='CONFIRMED' if abs(sum(d) / 2.0 - 604.0) < 1e-9 else 'REFUTED')
def t_known():
avg = 604.0 / 24; need = 604.0 / 0.9
ok = 18 <= avg <= 30.5 and abs(need - 670) < 2
return dict(question='Do the published sums hold: 604 GWh in a day with demand between 18 and 30.5 GW, and about 670 GWh of storage to cover it all?', sentence='National day: the known answers',
command='fire national-day-known {}', did='divided', numbers=dict(average_gw=round(avg, 1), storage_input_gwh_at_90_pct_round_trip=round(need)),
observed='the day averages %.1f GW, inside 18 to 30.5; 604 / 0.90 = %.0f GWh: the published 670 holds at a 90%% round trip' % (avg, need), assumed='none', result='CONFIRMED' if ok else 'REFUTED')
def registry():
R = [('NATIONAL DAY', 'the known answers', (t_known, ()))]
for g in (0, 5, 10, 15, 18, 20, 22, 25, 28, 30.5):
for eff in (0.85, 0.90): R.append(('NATIONAL DAY', '%g GW steady, %g round trip' % (g, eff), (t_storage, (g, eff))))
return ROne
A Python command-line tool in the bench folder of Faraday.
transformfaraday / bench/one.py · lines 1–21 of 21 · Entry point
- What it does
- It calculates its inputs. Defines main. Uses libraries json, os, sys, time.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- `bench/one.py` N - run test N in a process of its own and print its record as one line of JSON.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench · Python CLI
- Uses
- Tests (import), json, os, sys, time
- Used by
- none found
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/one.py:1-21 · blob 4a3752f6cf26bca6fbcc4aa8ae70c6bd2d66daba · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/one.py N - run test N in a process of its own and print its record as one line of JSON. Nothing else."""
import json
import os
import sys
import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def main():
n = int(sys.argv[1]); t0 = time.time()
try:
import tests
rec = tests.run(n)
except Exception as e: # a test that throws is a result, not a crash of the run
rec = dict(n=n, result='ERROR', observed='%s: %s' % (type(e).__name__, e))
rec['seconds'] = round(time.time() - t0, 2)
sys.stdout.write(json.dumps(rec, sort_keys=True) + '\n')
if __name__ == '__main__':
main()Page
A Python module in the bench folder of Faraday that draws records and commands. It builds files (`build_files`).
renderfaraday / bench/page.py · lines 1–89 of 89 · Entry point
- What it does
- It draws records and commands. Defines build_files. Uses libraries json, time. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file records.json; JSON file commands.json; form fields (user input). Out: canvas drawing.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- The bench as cells, with a command bar. It reads `records.json`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench · Python module
- Uses
- json, time
- Used by
- none found
- Produces
- build_files
- Defines here
- build_files
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/page.py:1-89 · blob e74d417aaf932b2b0588bec7815514f8f0260c5c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/page.py - the bench as cells, with a command bar. A small static page that FETCHES its data, as GridAtlas fetches its config:
index.html the page: cells placed by the Kuiper's law, a pulse, a card, and the bar (choose a sentence, or type a command)
commands.json THE COMMAND LIST (config): sentences a person reads, each with the command it stands for. Edit this file, or let
the runner rebuild it, and the list in the page changes. Nothing about the list is written into the page.
records.json every saved simulation, short form
../fire.js the commands that RUN IN THE VISITOR'S BROWSER (and ../fire_site.js when it exists)
White to ice blue = CONFIRMED; the one warning colour = REFUTED; grey = anything else. Black between every dot.
"""
import json
import time
PAGE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bench</title>
<style>
html,body{margin:0;background:#000;color:#dfe9f5;font:15px/1.5 Consolas,Menlo,monospace}
#wrap{position:relative}canvas{display:block;width:100%;touch-action:manipulation}
#card{position:absolute;left:12px;right:12px;top:12px;max-width:680px;margin:auto;background:#02080c;border:1px solid #1d5560;padding:12px 14px;display:none;max-height:62vh;overflow:auto}
#card h2{margin:0 0 4px;font-size:16px;color:#fff}.r{display:inline-block;padding:0 6px;border:1px solid;margin-right:8px;font-size:12px}
#card p{margin:6px 0}small{color:#8aa}#x{position:absolute;right:10px;top:6px;cursor:pointer;color:#8aa}
#bar{display:flex;flex-wrap:wrap;gap:8px;padding:10px 12px;border-top:1px solid #14323a;background:#02080c}
#bar select,#bar input,#bar button{background:#000;color:#dfe9f5;border:1px solid #1d5560;padding:9px 10px;font:inherit}
#bar select{flex:1 1 260px;min-width:0}#bar input{flex:3 1 420px;min-width:0;color:#22e0ff}#bar button{color:#22e0ff;letter-spacing:.08em}
#foot{padding:8px 12px;color:#667;font-size:12px}
</style></head><body>
<div id="wrap"><div id="load" style="padding:18px 14px;color:#8aa">Opening: fetching the saved simulations (about 2.5 MB). On a slow connection this takes a few seconds.</div><canvas id="c"></canvas><div id="card"><span id="x">x</span><h2 id="h"></h2><div id="b"></div></div></div>
<div id="bar"><select id="ex"><option value="">- choose an example sentence -</option></select>
<input id="cmd" spellcheck="false" placeholder='type a command: fire cable-withstand {"metal":"al","size_mm2":185,"seconds":1,"fault_ka":16} - help'>
<button id="go">FIRE</button><button id="all">WHOLE VIEW</button></div>
<div id="foot"><span id="tally"></span> Estimates from stated figures; change any number in a command and fire it again: it runs on your device and nothing you type leaves it. Provided as is, without warranty of any kind; a chart, not a design.</div>
<script src="../fire.js"></script><script src="../fire_site.js" onerror="void 0"></script>
<script>
let R=[],W,H,S,t0=performance.now(),sel=-1,fam=null;const G=Math.PI*(3-Math.sqrt(5)),c=document.getElementById('c'),x=c.getContext('2d'),$=id=>document.getElementById(id);
function fit(){const d=devicePixelRatio||1;W=c.clientWidth;H=Math.max(260,Math.min(innerHeight-150,W));c.width=W*d;c.height=H*d;c.style.height=H+'px';x.setTransform(d,0,0,d,0,0);S=Math.min(W,H)*0.47/Math.sqrt(R.length+1)}
function pos(j){const r=Math.sqrt(j+0.5)*S,a=j*G;return[W/2+r*Math.cos(a),H/2-r*Math.sin(a)]}
function col(r){return r.result==='CONFIRMED'?'#eaf6ff':r.result==='REFUTED'?'#ff8a3c':'#56626b'}
function draw(now){x.clearRect(0,0,W,H);const front=(now-t0)/1000*Math.sqrt(R.length+1)*S*0.9,dot=Math.max(1.2,S*0.30);
if(front<Math.sqrt(R.length+1)*S*1.1){x.strokeStyle='rgba(34,224,255,.6)';x.lineWidth=2;x.beginPath();x.arc(W/2,H/2,front,0,7);x.stroke()}
for(let j=0;j<R.length;j++){const p=pos(j),lit=Math.hypot(p[0]-W/2,p[1]-H/2)<=front&&(!fam||R[j].family===fam);x.globalAlpha=lit?1:0.10;x.fillStyle=lit?col(R[j]):'#9fb3c0';
x.beginPath();x.arc(p[0],p[1],j===sel?dot*1.6:dot,0,7);x.fill()}x.globalAlpha=1;requestAnimationFrame(draw)}
function esc(s){return String(s).replace(/[&<>]/g,m=>({'&':'&','<':'<','>':'>'}[m]))}
function nums(n){return n?Object.entries(n).map(e=>e[0].replace(/_/g,' ')+': '+(typeof e[1]==='object'&&e[1]?JSON.stringify(e[1]):e[1])).join(' - '):''}
function card(title,tag,colour,body){$('h').textContent=title;$('b').innerHTML='<span class="r" style="color:'+colour+'">'+tag+'</span>'+body;$('card').style.display='block'}
function show(j){sel=j;const r=R[j];card(r.n+' - '+(r.family||'')+': '+(r.name||''),r.result,col(r),(r.question?'<p>'+esc(r.question)+'</p>':'')+'<p><b>Seen:</b> '+esc(r.observed||'')+'</p><p><small>'+esc(nums(r.numbers))+'</small></p>'+(r.command?'<p><small><b>pop command</b> (tap to put it in the bar): <a href="#" id="use" style="color:#22e0ff">'+esc(r.command.slice(0,300))+'</a></small></p>':'' … [line shortened here: 403 characters; full line on GitHub]
const u=$('use');if(u)u.onclick=e=>{e.preventDefault();$('cmd').value=r.command;$('cmd').focus()}}
function fire(){const text=$('cmd').value.trim();if(!text)return;
if(/^help$/i.test(text)){card('Commands','HELP','#22e0ff','<p>Type <b>fire</b>, a name, and the inputs in { }. Choose a sentence on the left to see one, change any number, press FIRE.</p><p><small>These run on your device: '+esc((window.FIRE?FIRE.names:[]).join(', '))+'. Others show their saved result.</small></p>');return}
try{const o=FIRE.fire(text);const same=R.findIndex(q=>q.command===text);
if(o.ran){fam=o.family;sel=same;t0=performance.now();card('fire '+o.name,'RAN ON YOUR DEVICE','#eaf6ff','<p><b>'+esc(o.said)+'</b></p><p><small>'+esc(nums(o.numbers))+'</small></p><p><small>how: '+esc(o.how)+'</small></p><p><small>inputs: '+esc(JSON.stringify(o.inputs))+' - change any of them in the bar and fire again</small></p>')}
else if(same>=0){fam=R[same].family;t0=performance.now();show(same);$('b').insertAdjacentHTML('afterbegin','<span class="r" style="color:#8aa">SAVED RESULT</span><small> this model runs in Python tonight; its browser version is next. </small>')}
else card('fire '+o.name,'NOT YET','#8aa','<p>This command does not run on your device yet, and no saved result has exactly these inputs. Choose a sentence on the left, or type help.</p>')}
catch(e){card('That did not run','CHECK THE COMMAND','#ff8a3c','<p>'+esc(e.message)+'</p>')}}
c.addEventListener('click',e=>{const b=c.getBoundingClientRect(),mx=e.clientX-b.left,my=e.clientY-b.top;let best=-1,bd=1e9;for(let j=0;j<R.length;j++){const p=pos(j),d=Math.hypot(p[0]-mx,p[1]-my);if(d<bd){bd=d;best=j}}if(bd<Math.max(8,S*0.9))show(best)});
$('x').onclick=()=>{$('card').style.display='none';sel=-1};$('go').onclick=fire;$('cmd').addEventListener('keydown',e=>{if(e.key==='Enter')fire()});
$('all').onclick=()=>{fam=null;sel=-1;t0=performance.now();$('card').style.display='none'};
$('ex').onchange=e=>{if(e.target.value){$('cmd').value=e.target.value;fire();e.target.selectedIndex=0}};
addEventListener('resize',fit);
Promise.all([fetch('records.json').then(r=>r.json()),fetch('commands.json').then(r=>r.json())]).then(([rec,cfg])=>{R=rec.records;$('tally').textContent=rec.tally;$('load').remove();
let g=null,og=null;for(const k of cfg.commands){if(k.family!==g){g=k.family;og=document.createElement('optgroup');og.label=g;$('ex').appendChild(og)}const o=document.createElement('option');o.value=k.command;o.textContent=k.sentence;og.appendChild(o)}
fit();t0=performance.now();requestAnimationFrame(draw);const q=new URLSearchParams(location.search).get('fire');if(q){$('cmd').value='fire '+q;fire()}})
.catch(e=>{document.body.insertAdjacentHTML('afterbegin','<p style="padding:16px">The records could not be loaded: '+esc(e.message)+'</p>')});
</script></body></html>
"""
def build_files(rows):
"""Returns {file name: text} for bench/results/: the page, the command list (config) and the records."""
rows = sorted(rows, key=lambda r: r['n'])
keep = ('n', 'family', 'name', 'result', 'question', 'observed', 'numbers', 'sentence', 'command')
lean = ('n', 'family', 'name', 'result', 'observed', 'numbers', 'command')
recs = [{k: r[k] for k in (keep if r['n'] <= 200 else lean) if k in r} for r in rows]
tally = {}
for r in rows:
tally[r['result']] = tally.get(r['result'], 0) + 1
t = '%d saved simulations: ' % len(rows) + ', '.join('%d %s' % (v, k.lower()) for k, v in sorted(tally.items()))
commands, seen = [], {}
for r in rows: # the known answers first, then up to eight a family, in record order
if 'command' not in r or 'sentence' not in r:
continue
fam = r.get('family', '')
known = 'known answer' in r.get('name', '')
if known or seen.get(fam, 0) < 8:
seen[fam] = seen.get(fam, 0) + (0 if known else 1)
commands.append(dict(family=fam, sentence=r['sentence'], command=r['command'], record=r['n']))
commands.sort(key=lambda k: (k['family'], 'known' not in k['sentence'], k['record']))
cfg = dict(schema='bench.commands.v1', what_it_is='The list in "choose an example sentence". One entry = the sentence a person reads and the command it stands for. The page fetches this file; nothing about the list is written into the page.',
generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), commands=commands)
return {'index.html': PAGE, 'commands.json': json.dumps(cfg, indent=1), 'records.json': json.dumps(dict(tally=t, records=recs), separators=(',', ':'))}Bench — Results Page
A web page in Faraday that draws records and commands. It is built from the draw step (`draw`), the esc step (`esc`) and the nums step (`nums`).
renderfaraday / bench/results/index.html · lines 1–50 of 50 · Entry point
- What it does
- It draws records and commands. Defines 8 functions or classes, including fit, pos, col, draw, esc. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file records.json; JSON file commands.json; form fields (user input). Out: web page; canvas drawing.
- Downstream impact
- It is itself an entry point (page); no other file was found loading it.
- What it achieves
- Defines `fit`, `pos`, `col` and 5 more. It reads `records.json`. It responds to click, keydown and resize events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench/results · page
- Uses
- Fire (script src), Fire Site (script src)
- Used by
- none found
- Produces
- fit, pos, col, draw, esc, nums, card, fire
- Defines here
- fit, pos, col, draw, esc, nums, card, fire
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/results/index.html:1-50 · blob cd9030a11112f9b27bef9abccadffb84e36d4472 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bench</title>
<style>
html,body{margin:0;background:#000;color:#dfe9f5;font:15px/1.5 Consolas,Menlo,monospace}
#wrap{position:relative}canvas{display:block;width:100%;touch-action:manipulation}
#card{position:absolute;left:12px;right:12px;top:12px;max-width:680px;margin:auto;background:#02080c;border:1px solid #1d5560;padding:12px 14px;display:none;max-height:62vh;overflow:auto}
#card h2{margin:0 0 4px;font-size:16px;color:#fff}.r{display:inline-block;padding:0 6px;border:1px solid;margin-right:8px;font-size:12px}
#card p{margin:6px 0}small{color:#8aa}#x{position:absolute;right:10px;top:6px;cursor:pointer;color:#8aa}
#bar{display:flex;flex-wrap:wrap;gap:8px;padding:10px 12px;border-top:1px solid #14323a;background:#02080c}
#bar select,#bar input,#bar button{background:#000;color:#dfe9f5;border:1px solid #1d5560;padding:9px 10px;font:inherit}
#bar select{flex:1 1 260px;min-width:0}#bar input{flex:3 1 420px;min-width:0;color:#22e0ff}#bar button{color:#22e0ff;letter-spacing:.08em}
#foot{padding:8px 12px;color:#667;font-size:12px}
</style></head><body>
<div id="wrap"><div id="load" style="padding:18px 14px;color:#8aa">Opening: fetching the saved simulations (about 2.5 MB). On a slow connection this takes a few seconds.</div><canvas id="c"></canvas><div id="card"><span id="x">x</span><h2 id="h"></h2><div id="b"></div></div></div>
<div id="bar"><select id="ex"><option value="">- choose an example sentence -</option></select>
<input id="cmd" spellcheck="false" placeholder='type a command: fire cable-withstand {"metal":"al","size_mm2":185,"seconds":1,"fault_ka":16} - help'>
<button id="go">FIRE</button><button id="all">WHOLE VIEW</button></div>
<div id="foot"><span id="tally"></span> Estimates from stated figures; change any number in a command and fire it again: it runs on your device and nothing you type leaves it. Provided as is, without warranty of any kind; a chart, not a design.</div>
<script src="../fire.js"></script><script src="../fire_site.js" onerror="void 0"></script>
<script>
let R=[],W,H,S,t0=performance.now(),sel=-1,fam=null;const G=Math.PI*(3-Math.sqrt(5)),c=document.getElementById('c'),x=c.getContext('2d'),$=id=>document.getElementById(id);
function fit(){const d=devicePixelRatio||1;W=c.clientWidth;H=Math.max(260,Math.min(innerHeight-150,W));c.width=W*d;c.height=H*d;c.style.height=H+'px';x.setTransform(d,0,0,d,0,0);S=Math.min(W,H)*0.47/Math.sqrt(R.length+1)}
function pos(j){const r=Math.sqrt(j+0.5)*S,a=j*G;return[W/2+r*Math.cos(a),H/2-r*Math.sin(a)]}
function col(r){return r.result==='CONFIRMED'?'#eaf6ff':r.result==='REFUTED'?'#ff8a3c':'#56626b'}
function draw(now){x.clearRect(0,0,W,H);const front=(now-t0)/1000*Math.sqrt(R.length+1)*S*0.9,dot=Math.max(1.2,S*0.30);
if(front<Math.sqrt(R.length+1)*S*1.1){x.strokeStyle='rgba(34,224,255,.6)';x.lineWidth=2;x.beginPath();x.arc(W/2,H/2,front,0,7);x.stroke()}
for(let j=0;j<R.length;j++){const p=pos(j),lit=Math.hypot(p[0]-W/2,p[1]-H/2)<=front&&(!fam||R[j].family===fam);x.globalAlpha=lit?1:0.10;x.fillStyle=lit?col(R[j]):'#9fb3c0';
x.beginPath();x.arc(p[0],p[1],j===sel?dot*1.6:dot,0,7);x.fill()}x.globalAlpha=1;requestAnimationFrame(draw)}
function esc(s){return String(s).replace(/[&<>]/g,m=>({'&':'&','<':'<','>':'>'}[m]))}
function nums(n){return n?Object.entries(n).map(e=>e[0].replace(/_/g,' ')+': '+(typeof e[1]==='object'&&e[1]?JSON.stringify(e[1]):e[1])).join(' - '):''}
function card(title,tag,colour,body){$('h').textContent=title;$('b').innerHTML='<span class="r" style="color:'+colour+'">'+tag+'</span>'+body;$('card').style.display='block'}
function show(j){sel=j;const r=R[j];card(r.n+' - '+(r.family||'')+': '+(r.name||''),r.result,col(r),(r.question?'<p>'+esc(r.question)+'</p>':'')+'<p><b>Seen:</b> '+esc(r.observed||'')+'</p><p><small>'+esc(nums(r.numbers))+'</small></p>'+(r.command?'<p><small><b>pop command</b> (tap to put it in the bar): <a href="#" id="use" style="color:#22e0ff">'+esc(r.command.slice(0,300))+'</a></small></p>':'' … [line shortened here: 403 characters; full line on GitHub]
const u=$('use');if(u)u.onclick=e=>{e.preventDefault();$('cmd').value=r.command;$('cmd').focus()}}
function fire(){const text=$('cmd').value.trim();if(!text)return;
if(/^help$/i.test(text)){card('Commands','HELP','#22e0ff','<p>Type <b>fire</b>, a name, and the inputs in { }. Choose a sentence on the left to see one, change any number, press FIRE.</p><p><small>These run on your device: '+esc((window.FIRE?FIRE.names:[]).join(', '))+'. Others show their saved result.</small></p>');return}
try{const o=FIRE.fire(text);const same=R.findIndex(q=>q.command===text);
if(o.ran){fam=o.family;sel=same;t0=performance.now();card('fire '+o.name,'RAN ON YOUR DEVICE','#eaf6ff','<p><b>'+esc(o.said)+'</b></p><p><small>'+esc(nums(o.numbers))+'</small></p><p><small>how: '+esc(o.how)+'</small></p><p><small>inputs: '+esc(JSON.stringify(o.inputs))+' - change any of them in the bar and fire again</small></p>')}
else if(same>=0){fam=R[same].family;t0=performance.now();show(same);$('b').insertAdjacentHTML('afterbegin','<span class="r" style="color:#8aa">SAVED RESULT</span><small> this model runs in Python tonight; its browser version is next. </small>')}
else card('fire '+o.name,'NOT YET','#8aa','<p>This command does not run on your device yet, and no saved result has exactly these inputs. Choose a sentence on the left, or type help.</p>')}
catch(e){card('That did not run','CHECK THE COMMAND','#ff8a3c','<p>'+esc(e.message)+'</p>')}}
c.addEventListener('click',e=>{const b=c.getBoundingClientRect(),mx=e.clientX-b.left,my=e.clientY-b.top;let best=-1,bd=1e9;for(let j=0;j<R.length;j++){const p=pos(j),d=Math.hypot(p[0]-mx,p[1]-my);if(d<bd){bd=d;best=j}}if(bd<Math.max(8,S*0.9))show(best)});
$('x').onclick=()=>{$('card').style.display='none';sel=-1};$('go').onclick=fire;$('cmd').addEventListener('keydown',e=>{if(e.key==='Enter')fire()});
$('all').onclick=()=>{fam=null;sel=-1;t0=performance.now();$('card').style.display='none'};
$('ex').onchange=e=>{if(e.target.value){$('cmd').value=e.target.value;fire();e.target.selectedIndex=0}};
addEventListener('resize',fit);
Promise.all([fetch('records.json').then(r=>r.json()),fetch('commands.json').then(r=>r.json())]).then(([rec,cfg])=>{R=rec.records;$('tally').textContent=rec.tally;$('load').remove();
let g=null,og=null;for(const k of cfg.commands){if(k.family!==g){g=k.family;og=document.createElement('optgroup');og.label=g;$('ex').appendChild(og)}const o=document.createElement('option');o.value=k.command;o.textContent=k.sentence;og.appendChild(o)}
fit();t0=performance.now();requestAnimationFrame(draw);const q=new URLSearchParams(location.search).get('fire');if(q){$('cmd').value='fire '+q;fire()}})
.catch(e=>{document.body.insertAdjacentHTML('afterbegin','<p style="padding:16px">The records could not be loaded: '+esc(e.message)+'</p>')});
</script></body></html>Site Cases
A Python module in the bench folder of Faraday that works with solar, transformers, 11kV and substations.
transformfaraday / bench/site_cases.py · lines 1–142 of 142 · Entry point · pattern registry (shared by 8 files)
- What it does
- It calculates solar, transformers, 11kV and substations. Defines 9 functions or classes, including standard_site, solve, record, t_scenario, t_threshold. Uses libraries json, math, random.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 11kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, transformers, 11kV, substations.
- Inputs & outputs
- Voltage levels named: 11kV.
- Downstream impact
- Used directly by 2 files: Million (faraday); Tests (faraday). Reached from 1 other entry point, including One (faraday).
- What it achieves
- It is built from the standard site helper (`standard_site`), the solve step (`solve`) and the record step (`record`). SITE PULSE: a generic industrial site behind its meter, as cells and two pulses. Its code works with 11 kV.
- Why it matters
- Imported by Million. Checked by Tests.
- Application
- faraday · bench · Python module
- Uses
- json, math, random
- Used by
- imported by Million (import), imported by Tests (import)
- Produces
- standard_site, solve, record, t_scenario, t_threshold, random_site, t_survey, registry
- Defines here
- standard_site, solve, record, t_scenario, t_threshold, bad, random_site, t_survey, registry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/site_cases.py:1-142 · blob 0723b92b21602c61f60c98c3152876a3328ac1d5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/site_cases.py - SITE PULSE: a generic industrial site behind its meter, as cells and two pulses.
A factory with its own 11 kV intake, a few site substations (each a transformer with a lumped load on its low voltage side), solar
on the low voltage side of ONE of them, an on site generator, and an export limit agreed with the network operator. The questions a
site owner pays an engineer to answer: what flows at the connection point, what voltage each bus sees, how loaded each transformer is,
whether the export limit binds, and how much the fault level at a low voltage board rises. Here they are ESTIMATES from stated,
generic figures, so that the right study can be commissioned; every figure is an input the owner can overwrite with their own.
NOTHING HERE IS ANY REAL SITE. Sizes are round numbers chosen to be typical. Every electrical figure is a CANDIDATE quoted from memory.
Method: the same forward-backward sweep as the feeder pulse (tests.py), per phase, in volts and amps at 11 kV, transformers as series
impedances referred to 11 kV, constant power loads and sources (a source is a negative load).
"""
import json
import math
import random
CANDIDATE = dict(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)
def standard_site():
"""Five site substations off one intake. Solar on number 4. A generator on the intake board. Round, generic figures."""
return dict(intake_cable_km=0.6, export_limit_kw=500.0, generator_kw=500.0, pv_kw=1000.0, pv_on=4,
subs=[dict(n=1, kva=1600, load_kw=900, km=0.15), dict(n=2, kva=1000, load_kw=550, km=0.25), dict(n=3, kva=1000, load_kw=500, km=0.35),
dict(n=4, kva=1000, load_kw=350, km=0.45), dict(n=5, kva=800, load_kw=300, km=0.30, tenant=True)])
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'))}
def solve(site, pv_share, gen_on, off=(), load_share=1.0, c=CANDIDATE, tol=1e-9):
vb = c['kv'] * 1000 / math.sqrt(3)
zs_mag = (c['kv'] ** 2) / c['grid_fault_mva']; xr = c['grid_x_over_r']; rs = zs_mag / math.sqrt(1 + xr * xr)
Z = {'poc': complex(rs, rs * xr), 'board': complex(c['hv_cable_r'], c['hv_cable_x']) * site['intake_cable_km']}
parent = {'grid': None, 'poc': 'grid', 'board': 'poc'}; S = {}; kva = {}
tanl = math.tan(math.acos(c['load_pf'])); tang = math.tan(math.acos(c['gen_pf']))
if gen_on: S['board'] = -complex(site['generator_kw'], site['generator_kw'] * tang) * 1000 / 3
for s in site['subs']:
hv, lv = 'hv%d' % s['n'], 'lv%d' % s['n']; parent[hv] = 'board'; parent[lv] = hv
Z[hv] = complex(c['hv_cable_r'], c['hv_cable_x']) * s['km']
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] = complex(rt, rt * txr); kva[lv] = s['kva']
dead = ('tenant' in off and s.get('tenant'))
if dead: parent.pop(hv); parent.pop(lv); Z.pop(hv); Z.pop(lv); kva.pop(lv); continue
kw = 0.0 if ('pvload' in off and s['n'] == site['pv_on']) else s['load_kw'] * load_share
p = complex(kw, kw * tanl)
if s['n'] == site['pv_on']: p -= complex(site['pv_kw'] * pv_share, 0)
S[lv] = p * 1000 / 3
kids = {}
for n, p in parent.items():
if p is not None: kids.setdefault(p, []).append(n)
order = ['grid']
for n in order: order += kids.get(n, [])
V = {n: complex(vb, 0) for n in order}; rounds = 0
while True:
rounds += 1
J = {n: ((S[n] / V[n]).conjugate() if n in S else 0j) for n in order}
for n in reversed(order): # PULSE ONE: currents sum back toward the grid
if parent[n] is not None: J[parent[n]] += J[n]
nv = {'grid': complex(vb, 0)}
for n in order[1:]: nv[n] = nv[parent[n]] - J[n] * Z[n] # PULSE TWO: volts fall (or rise) out from the grid
step = max(abs(nv[n] - V[n]) for n in order); V = nv
if step < tol or rounds > 300: break
s_poc = V['poc'] * J['poc'].conjugate() * 3 # + import, - export, in volt amperes
loss = sum(abs(J[n]) ** 2 * Z[n].real for n in order[1:]) * 3
net = sum(S.values()).real * 3
source = (V['grid'] * J['poc'].conjugate()).real * 3
tx = {n: abs(V[n] * J[n].conjugate() * 3) / 1000 / kva[n] * 100 for n in kva}
# fault level at the low voltage board beside the solar: grid through the impedances, plus the inverters, plus the generator
lv = 'lv%d' % site['pv_on']; fault_ka = None
if lv in Z:
zpath = Z['poc'] + Z['board'] + Z['hv%d' % site['pv_on']] + Z[lv]
i_grid = vb / abs(zpath) # amps at 11 kV
i_pv = c['inverter_fault_x_rated'] * site['pv_kw'] * pv_share * 1000 / (math.sqrt(3) * c['kv'] * 1000)
i_gen = (site['generator_kw'] / c['gen_pf'] * 1000 / (math.sqrt(3) * c['kv'] * 1000) / c['generator_subtransient_pu']) if gen_on else 0.0
fault_ka = dict(grid_only=round(i_grid * c['kv'] / 0.4 / 1000, 2), with_sources=round((i_grid + i_pv + i_gen) * c['kv'] / 0.4 / 1000, 2))
return dict(V={n: abs(V[n]) / vb for n in order}, p_poc_kw=s_poc.real / 1000, q_poc_kvar=s_poc.imag / 1000, loss_kw=loss / 1000,
tx_loading_pct=tx, rounds=rounds, balance=abs(source - net - loss) / max(abs(net), 1.0), fault_ka=fault_ka)
def record(site, scen, load_share, note=''):
name, pv_share, gen_on, off = SCENARIOS[scen]; c = CANDIDATE
r = solve(site, pv_share, gen_on, off, load_share)
export = max(0.0, -r['p_poc_kw']); over = max(0.0, export - site['export_limit_kw'])
vmax = max(r['V'].values()); vmin = min(r['V'].values()); worst_tx = max(r['tx_loading_pct'].values())
ok = r['rounds'] <= 300 and r['balance'] < 1e-6
flags = []
if over > 0: flags.append('export %.0f kW is %.0f kW over the %.0f kW limit: the solar must be held back' % (export, over, site['export_limit_kw']))
if vmax > c['volts_high_pu']: flags.append('highest voltage %.3f of nominal is over %.2f' % (vmax, c['volts_high_pu']))
if vmin < c['volts_low_pu']: flags.append('lowest voltage %.3f of nominal is under %.2f' % (vmin, c['volts_low_pu']))
if worst_tx > 100: flags.append('a transformer is at %.0f%% of its rating' % worst_tx)
inputs = dict(scenario=scen, load_share=load_share, site=site)
return dict(question='Site pulse, scenario %d (%s), site load at %d%%%s: what flows at the connection point, what does each bus see, how loaded is each transformer?' % (scen, name, round(load_share * 100), note),
sentence='Site pulse: %s, load %d%%' % (name, round(load_share * 100)),
command='fire site-pulse ' + json.dumps(inputs, separators=(',', ':'), sort_keys=True),
did='two pulses per round until the volts stop moving: currents summed back to the grid, volts dropped or raised out from it; then power in = net load + losses',
numbers=dict(connection_point_kw=round(r['p_poc_kw'], 1), connection_point_kvar=round(r['q_poc_kvar'], 1), export_kw=round(export, 1), over_limit_kw=round(over, 1),
losses_kw=round(r['loss_kw'], 2), highest_volts_pu=round(vmax, 4), lowest_volts_pu=round(vmin, 4), worst_transformer_pct=round(worst_tx, 1),
rounds=r['rounds'], power_balance_error=float('%.2e' % r['balance']), fault_level_beside_solar_ka=r['fault_ka']),
observed=('connection point %+.0f kW (plus is import), %+.0f kvar; volts %.3f to %.3f; busiest transformer %.0f%%; ' % (r['p_poc_kw'], r['q_poc_kvar'], vmin, vmax, worst_tx)) + ('; '.join(flags) if flags else 'inside every limit'),
assumed='a GENERIC site, no real one; every electrical figure a CANDIDATE: ' + json.dumps(c, sort_keys=True), result='CONFIRMED' if ok else 'REFUTED')
def t_scenario(scen, load_share): return record(standard_site(), scen, load_share)
def t_threshold(kind):
"""Bisect to the number an owner wants: how much solar before a limit binds, at light load (the hard case)."""
lo, hi = 0.0, 6000.0
def bad(pv):
s = standard_site(); s['pv_kw'] = pv; r = solve(s, 1.0, False, (), 0.3)
if kind == 'export limit': return max(0.0, -r['p_poc_kw']) > s['export_limit_kw']
if kind == 'voltage rise': return max(r['V'].values()) > CANDIDATE['volts_high_pu']
if kind == 'transformer rating': return max(r['tx_loading_pct'].values()) > 100
if not bad(hi): return dict(question='How much solar before the %s binds (load at 30%%)?' % kind, sentence='Site threshold: %s' % kind, command='fire site-threshold {"limit":"%s"}' % kind,
did='tried up to 6,000 kW', numbers=dict(threshold_kw=None), observed='never binds below 6,000 kW on this site', assumed='generic site; CANDIDATE figures', result='NO EFFECT')
for _ in range(40):
mid = (lo + hi) / 2
if bad(mid): hi = mid
else: lo = mid
return dict(question='How much solar can this generic site carry at 30%% load before the %s binds?' % kind, sentence='Site threshold: %s' % kind,
command='fire site-threshold {"limit":"%s","load_share":0.3}' % kind, did='halved the interval forty times between a solar size that is fine and one that is not',
numbers=dict(threshold_kw=round(hi, 1)), observed='the %s first binds at about %.0f kW of solar' % (kind, hi), assumed='generic site; CANDIDATE figures: ' + json.dumps(CANDIDATE, sort_keys=True), result='CONFIRMED')
def random_site(seed):
g = random.Random(seed); n = g.randint(2, 8); subs = []
for k in range(1, n + 1):
kva = g.choice([500, 800, 1000, 1600, 2000]); subs.append(dict(n=k, kva=kva, load_kw=round(kva * g.uniform(0.25, 0.8)), km=round(g.uniform(0.05, 0.8), 2), tenant=(k == n and g.random() < 0.3)))
total = sum(s['load_kw'] for s in subs)
return dict(intake_cable_km=round(g.uniform(0.1, 2.0), 2), export_limit_kw=float(g.choice([0, 50, 200, 500, 1000])), generator_kw=float(g.choice([0, 250, 500, 1000])),
pv_kw=float(round(total * g.uniform(0.2, 1.5), -1)), pv_on=g.randint(1, n), subs=subs)
def t_survey(seed):
"""One of many generic sites: full solar at light load, generator off: the case that finds trouble."""
return record(random_site(seed), 3, 0.3, note=', generic site number %d' % seed)
def registry():
R = []
for scen in range(1, 9):
for ls in (1.0, 0.6, 0.3): R.append(('SITE PULSE', 'scenario %d at %d%% load' % (scen, round(ls * 100)), (t_scenario, (scen, ls))))
for k in ('export limit', 'voltage rise', 'transformer rating'): R.append(('SITE THRESHOLDS', k, (t_threshold, (k,))))
for seed in range(1, 2001): R.append(('SITE SURVEY', 'generic site %d' % seed, (t_survey, (seed,))))
return R