In this section
- Farm other · gpu-drivers-for-global-grid / engine/farm.py lines 1–153
- Feeding other · gpu-drivers-for-global-grid / engine/feeding.py lines 1–94
- Fused other · gpu-drivers-for-global-grid / engine/fused.py lines 1–194
- Selftest other · gpu-drivers-for-global-grid / engine/selftest.py lines 1–124
Farm
A Python command-line tool in the engine folder of GPU Drivers for Global Grid that solves strings (`solve_strings`) (units: kW, kVA, MVA). It is built from the farm step (`farm`).
othergpu-drivers-for-global-grid / engine/farm.py · lines 1–153 of 153 · Entry point
- What it does
- Defines farm, solve_strings, main. Uses libraries argparse, json, sys. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'farm'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: 1500V.
- Inputs & outputs
- In: command-line arguments. Voltage levels named: 1500V.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Farm-scale model: many string inverters, array size in the client's hands. Its code works with 352 kVA, 465 kW and 500 kVA. It accepts `--class`, `--inverters` and `--series`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- argparse, json, sys
- Used by
- none found
- Produces
- farm, solve_strings, main
- Defines here
- farm, solve_strings, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/farm.py:1-153 · blob f4269cc74827bec43c70f9b28318296e077e7299 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
"""Farm-scale model: many string inverters, array size in the client's hands.
Two inverter classes, both from E:\\swarm\\inverter-classes.json, nameless by
rule. Their provenance travels with them: the 352 kVA class is FROM-DATASHEET
and in volume production; the larger class's nearest real product is a 465 kW
machine announced January 2026 and is FROM-PRESS only - no datasheet has been
published, and its DC input figures in that file are marked ASSUMED. It is
modelled here as what it is, not as a 500 kVA datasheet.
python farm.py the reference farm, 1000 inverters
python farm.py --inverters 900 --series 28 --strings 22
python farm.py --class large --solve-dcac 1.35
Every figure printed is computed from the arguments. No yield, no energy, no
export figure is stated: none is computed here.
"""
import argparse
import json
import sys
# ---- the two classes, as owned. AC kVA, max strings, provenance, note
CLASSES = {
"352": {
"label": "352 kVA class, 1500 V string inverter, variant A",
"kva": 352.0,
"max_strings": 24, # 12 MPPT x 2 inputs
"mppt": 12, "inputs_per_mppt": 2,
"src": "FROM-DATASHEET",
"note": "real, in volume production, fully documented",
},
"500": {
"label": "500 kW class string inverter",
"kva": 500.0,
# scaled, not invented: the string is fixed by the 1500 V ceiling, so a
# larger machine changes only how many strings hang off it.
"max_strings": 34, # = floor(1.35 x 500 / 19.8), the ratio
"mppt": 0, "inputs_per_mppt": 0,
"src": "SEEN-BY-OWNER",
"note": "a 500 kW machine was seen on a stand at a European exhibition "
"in 2026. Existence is first hand; the specification is not. "
"MPPT count and inputs per MPPT were not captured, so the "
"string count here is the ratio, not the machine's input list.",
},
"large": {
"label": "465 kW class string inverter (the 500 kVA slot)",
"kva": 465.0,
"max_strings": 36, # 6 MPPT x 6 inputs
"mppt": 6, "inputs_per_mppt": 6,
"src": "FROM-PRESS",
"note": "announced January 2026, press only - NO DATASHEET PUBLISHED. "
"Its DC input currents are ASSUMED. Do not commit against it.",
},
}
MODULE_WP = 660.0 # class T660, MODULE-CLASSES.md
DCAC_LO, DCAC_HI = 1.15, 1.40
def farm(cls, inverters, series, strings, wp=MODULE_WP):
c = CLASSES[cls]
if strings > c["max_strings"]:
raise SystemExit(
"REFUSED: %d strings exceeds this class's %d (%d MPPT x %d "
"inputs). The inverter cannot accept them."
% (strings, c["max_strings"], c["mppt"], c["inputs_per_mppt"]))
kw_string = series * wp / 1000.0
kw_inv = kw_string * strings
return {
"class": c["label"], "provenance": c["src"], "note": c["note"],
"inverters": inverters,
"modules_in_series": series, "strings_per_inverter": strings,
"module_wp": wp,
"kw_dc_per_string": round(kw_string, 3),
"kw_dc_per_inverter": round(kw_inv, 2),
"dc_ac_per_inverter": round(kw_inv / c["kva"], 4),
"mated_pairs_per_inverter": strings * 2,
"mw_dc_farm": round(kw_inv * inverters / 1000.0, 2),
"mva_ac_farm": round(c["kva"] * inverters / 1000.0, 2),
"strings_farm": strings * inverters,
"modules_farm": strings * series * inverters,
"mated_pairs_farm": strings * 2 * inverters,
"in_band": DCAC_LO <= kw_inv / c["kva"] <= DCAC_HI,
}
def solve_strings(cls, series, target, wp=MODULE_WP):
"""Most strings that stay at or under a target DC:AC, within the class."""
c = CLASSES[cls]
kw_string = series * wp / 1000.0
n = int(target * c["kva"] / kw_string)
return min(n, c["max_strings"]), n > c["max_strings"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--class", dest="cls", default="352",
choices=sorted(CLASSES))
ap.add_argument("--inverters", type=int, default=1000)
ap.add_argument("--series", type=int, default=30)
ap.add_argument("--strings", type=int, default=24)
ap.add_argument("--wp", type=float, default=MODULE_WP)
ap.add_argument("--solve-dcac", type=float, default=None)
ap.add_argument("--json", action="store_true")
a = ap.parse_args()
strings = a.strings
capped = False
if a.solve_dcac:
strings, capped = solve_strings(a.cls, a.series, a.solve_dcac, a.wp)
f = farm(a.cls, a.inverters, a.series, strings, a.wp)
if a.json:
print(json.dumps(f, indent=1)); return 0
print("FARM MODEL %s" % f["class"])
print(" provenance %s - %s" % (f["provenance"], f["note"]))
if f["provenance"] != "FROM-DATASHEET":
print(" *** this class is not documented. Treat every number below "
"as indicative. ***")
print()
print(" ARRAY, in your hands")
print(" modules in series per string ... %d" % f["modules_in_series"])
print(" strings per inverter .......... %d of a maximum %d"
% (f["strings_per_inverter"], CLASSES[a.cls]["max_strings"]))
print(" module ........................ %.0f Wp" % f["module_wp"])
if a.solve_dcac:
print(" (strings solved for a DC:AC target of %.2f%s)"
% (a.solve_dcac,
"; CAPPED by the inverter's input count" if capped else ""))
print()
print(" ONE INVERTER")
print(" kW DC per string .............. %8.2f kW" % f["kw_dc_per_string"])
print(" kW DC per inverter ............ %8.2f kW" % f["kw_dc_per_inverter"])
print(" DC:AC ......................... %8.3f %s"
% (f["dc_ac_per_inverter"],
"in the %.2f-%.2f band" % (DCAC_LO, DCAC_HI) if f["in_band"]
else "OUTSIDE the %.2f-%.2f band" % (DCAC_LO, DCAC_HI)))
print(" mated pairs, inverter side .... %8d" % f["mated_pairs_per_inverter"])
print()
print(" THE FARM, %d inverters" % f["inverters"])
print(" DC .............. %10.2f MWp" % f["mw_dc_farm"])
print(" AC .............. %10.2f MVA" % f["mva_ac_farm"])
print(" strings ......... %10s" % "{:,}".format(f["strings_farm"]))
print(" modules ......... %10s" % "{:,}".format(f["modules_farm"]))
print(" mated pairs ..... %10s (inverter side only)"
% "{:,}".format(f["mated_pairs_farm"]))
print()
print(" Not computed, and not implied: yield, energy, export, land area,")
print(" cable schedule or cost. None of those is in this model.")
return 0
if __name__ == "__main__":
sys.exit(main())Feeding
A Python command-line tool in the engine folder of GPU Drivers for Global Grid. It is built from the timed step (`timed`).
othergpu-drivers-for-global-grid / engine/feeding.py · lines 1–94 of 94 · Entry point · pattern timed (shared by 3 files)
- What it does
- Defines timed, main. Uses libraries sys, time, cupy. Side effects: starts processes.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Is the card the bottleneck, or is feeding it?
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- Fused (import), sys, time, cupy
- Used by
- none found
- Produces
- timed, main
- Defines here
- timed, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/feeding.py:1-94 · blob cc466e0af1421436d72e27542bcf72450ff3a88c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""Is the card the bottleneck, or is feeding it?
The claim to test: the kernel is already blistering, and the real constraint is
supplying it with deterministic work. If that is true, the arithmetic should be
a small fraction of a pass, and the time should sit in manufacturing indices
and reducing results.
Times each stage separately with the device synchronised between them, so the
numbers are stages and not an accident of asynchrony.
python feeding.py
"""
import sys
import time
try:
import cupy as cp
except Exception as exc: # pragma: no cover
print("cupy unavailable: %r" % (exc,))
sys.exit(1)
from fused import FUSED, SIZE, tables
def timed(fn, reps=5):
"""Median of reps, each synchronised. Never a single sample."""
out = []
for _ in range(reps):
cp.cuda.Stream.null.synchronize()
t0 = time.perf_counter()
fn()
cp.cuda.Stream.null.synchronize()
out.append(time.perf_counter() - t0)
out.sort()
return out[len(out) // 2]
def main():
free, total = cp.cuda.Device(0).mem_info
batch = 1 << 23
t = tables(cp)
print("one pass of %s cases, %.2f GB free of %.2f GB\n"
% ("{:,}".format(batch), free / 1e9, total / 1e9))
idx = cp.arange(0, batch, dtype=cp.int64)
codes = FUSED(idx, *t)
cp.cuda.Stream.null.synchronize()
stages = [
("manufacture the index (cp.arange)",
lambda: cp.arange(0, batch, dtype=cp.int64)),
("the arithmetic (fused kernel)",
lambda: FUSED(idx, *t)),
("reduce on the card (bincount)",
lambda: cp.bincount(codes, minlength=4)),
("whole pass, as run() does it",
lambda: cp.bincount(FUSED(cp.arange(0, batch, dtype=cp.int64), *t),
minlength=4)),
]
res = {}
for name, fn in stages:
res[name] = timed(fn)
whole = res["whole pass, as run() does it"]
print(" %-38s %9s %6s" % ("stage", "seconds", "share"))
print(" " + "-" * 56)
for name, _fn in stages:
s = res[name]
share = "" if name.startswith("whole") else "%5.1f%%" % (100 * s / whole)
print(" %-38s %9.6f %6s" % (name, s, share))
arith = res["the arithmetic (fused kernel)"]
feed = res["manufacture the index (cp.arange)"]
red = res["reduce on the card (bincount)"]
print()
print(" arithmetic is %.1f%% of a pass; feeding and reducing are %.1f%%"
% (100 * arith / whole, 100 * (feed + red) / whole))
print(" at this rate one pass of %s cases costs %.4f s, so a billion"
% ("{:,}".format(batch), whole))
print(" cases cost about %.2f s and ten billion about %.1f s."
% (whole * 1e9 / batch, whole * 1e10 / batch))
print()
print(" THE SPACE WE ACTUALLY HAVE: %s cases, which this card finishes"
% "{:,}".format(SIZE))
print(" in %.4f s. A working day of the card at this rate is %.2e cases."
% (whole * SIZE / batch, 8 * 3600 * batch / whole))
print()
print(" Not stated: watts per case on the processor side, which was never")
print(" recorded. These are stage times on one machine, median of 5.")
return 0
if __name__ == "__main__":
sys.exit(main())Fused
A Python command-line tool in the engine folder of GPU Drivers for Global Grid.
othergpu-drivers-for-global-grid / engine/fused.py · lines 1–194 of 194 · Entry point · pattern tables (shared by 4 files)
- What it does
- Defines chain, tables, run, main. Uses libraries sys, time, numpy, cupy. Side effects: starts processes.
- Downstream impact
- Used directly by 1 file: Feeding (gpu-drivers-for-global-grid).
- What it achieves
- It is built from the chain step (`chain`), the tables step (`tables`) and the run step (`run`). One fused kernel instead of a chain of elementwise ones.
- Why it matters
- Imported by Feeding.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- sys, time, numpy, cupy
- Used by
- imported by Feeding (import)
- Produces
- chain, tables, run, main
- Defines here
- chain, tables, run, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/fused.py:1-194 · blob ae190f9683e35f45fa2e271c8a3066d7b744e00a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""One fused kernel instead of a chain of elementwise ones.
The GPU review named this as the next win and said why: the card sat at 62%
not because of precision - float32 over the whole billion changed 0 verdicts
and was only 9% faster - but because roughly 22 float64 temporaries a case is
about 176 bytes a case, some 31 GB/s of DRAM round trips spread over many
small CuPy kernels. Each `xp.where`, each multiply, each compare allocates a
full-length array, writes it to memory and reads it back.
Fusing removes every one of them. The index is decoded INSIDE the kernel, the
arithmetic happens in registers, and the only thing that touches memory is one
read of the small lookup tables and one write of the verdict.
Same arithmetic as east_west_block.py: R1 cold voltage on both readings, then
the DC:AC band. Nothing new is computed here; this is the same answer, reached
without the round trips.
python fused.py compare fused against the chain, verify, time
"""
import sys
import time
import numpy as np
try:
import cupy as cp
except Exception as exc: # pragma: no cover
print("cupy unavailable: %r" % (exc,))
sys.exit(1)
# ---- what we own (MODULE-CLASSES.md): Voc, beta %/K, Wp
CLASSES = [(45.90, -0.25, 660.0), (50.59, -0.22, 760.0), (53.27, -0.25, 650.0)]
TMIN = [-14.0, -12.0, -11.0, -10.0, -8.0, -6.0]
SERIES = [float(s) for s in range(20, 35)]
STRINGS = [float(n) for n in range(16, 33)]
N_VOC = 101
N_BETA = 101 # beta +/- 10%, the second tolerance axis
INVERTER_KVA = 352.0
MAX_V = 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40
NC, NT, NS, NN, NV = len(CLASSES), len(TMIN), len(SERIES), len(STRINGS), N_VOC
NB = N_BETA
SIZE = NC * NT * NS * NN * NV * NB
VMID, BMID = N_VOC // 2, N_BETA // 2
OK, DISPUTED, FAIL_COLD, OUT_OF_BAND = 0, 1, 2, 3
# --------------------------------------------------------- the chain (before)
def chain(xp, idx, voc_t, beta_t, wp_t, tmin_t, ser_t, str_t):
"""The ordinary way: every operation allocates and writes a full array."""
r = idx
ci = r % NC; r = r // NC
ti = r % NT; r = r // NT
si = r % NS; r = r // NS
ni = r % NN; r = r // NN
vt = r % NV; r = r // NV
bt = r % NB
voc = voc_t[ci] * (1.0 + (vt - VMID) / VMID * 0.01)
beta = beta_t[ci] * (1.0 + (bt - BMID) / BMID * 0.10)
wp = wp_t[ci]
tmin = tmin_t[ti]
series = ser_t[si]
strings = str_t[ni]
nmax_b = xp.floor(MAX_V / (voc * (1.0 + beta / 100.0 * (tmin - 25.0))))
nmax_a = xp.floor(MAX_V / (voc * (1.0 + beta / 100.0 * (tmin - 15.0))))
ok_b = series <= nmax_b
ok_a = series <= nmax_a
dcac = (series * wp / 1000.0) * strings / INVERTER_KVA
in_band = (dcac >= DCAC_LO) & (dcac <= DCAC_HI)
return xp.where(~ok_a, FAIL_COLD,
xp.where(~ok_b, DISPUTED,
xp.where(in_band, OK,
OUT_OF_BAND))).astype(xp.int64)
# --------------------------------------------------------- the fused (after)
_SRC = """
long long r = idx;
int ci = (int)(r %% %(NC)d); r /= %(NC)d;
int ti = (int)(r %% %(NT)d); r /= %(NT)d;
int si = (int)(r %% %(NS)d); r /= %(NS)d;
int ni = (int)(r %% %(NN)d); r /= %(NN)d;
int vt = (int)(r %% %(NV)d); r /= %(NV)d;
int bt = (int)(r %% %(NB)d);
double v = voc[ci] * (1.0 + ((double)vt - %(VMID)d.0) / %(VMID)d.0 * 0.01);
double b = beta[ci] * (1.0 + ((double)bt - %(BMID)d.0) / %(BMID)d.0 * 0.10);
double w = wp[ci];
double tm = tmin[ti];
double se = ser[si];
double st = strs[ni];
double nmax_b = floor(%(MAXV).1f / (v * (1.0 + b / 100.0 * (tm - 25.0))));
double nmax_a = floor(%(MAXV).1f / (v * (1.0 + b / 100.0 * (tm - 15.0))));
bool ok_b = se <= nmax_b;
bool ok_a = se <= nmax_a;
double dcac = (se * w / 1000.0) * st / %(KVA).1f;
bool band = (dcac >= %(LO).2f) && (dcac <= %(HI).2f);
code = (!ok_a) ? %(FC)d : ((!ok_b) ? %(DI)d : (band ? %(OK)d : %(OB)d));
""" % {"NC": NC, "NT": NT, "NS": NS, "NN": NN, "NV": NV, "NB": NB,
"VMID": VMID, "BMID": BMID,
"MAXV": MAX_V, "KVA": INVERTER_KVA, "LO": DCAC_LO, "HI": DCAC_HI,
"FC": FAIL_COLD, "DI": DISPUTED, "OK": OK, "OB": OUT_OF_BAND}
FUSED = cp.ElementwiseKernel(
"int64 idx, raw float64 voc, raw float64 beta, raw float64 wp, "
"raw float64 tmin, raw float64 ser, raw float64 strs",
"int64 code", _SRC, "ventus_fused_case")
def tables(xp):
return (xp.asarray([c[0] for c in CLASSES]),
xp.asarray([c[1] for c in CLASSES]),
xp.asarray([c[2] for c in CLASSES]),
xp.asarray(TMIN), xp.asarray(SERIES), xp.asarray(STRINGS))
def run(kind, batch):
t = tables(cp)
totals = cp.zeros(4, dtype=cp.int64)
cp.cuda.Stream.null.synchronize()
t0 = time.perf_counter()
done = 0
while done < SIZE:
n = min(batch, SIZE - done)
idx = cp.arange(done, done + n, dtype=cp.int64)
codes = FUSED(idx, *t) if kind == "fused" else chain(cp, idx, *t)
totals += cp.bincount(codes, minlength=4)[:4]
done += n
cp.cuda.Stream.null.synchronize()
return time.perf_counter() - t0, [int(x) for x in cp.asnumpy(totals)]
def main():
free, total = cp.cuda.Device(0).mem_info
batch = max(1 << 12, min(1 << 23, int(free * 0.25 / 176)))
print("space %s cases over 6 axes %s" % ("{:,}".format(SIZE),
[NC, NT, NS, NN, NV, NB]))
print("device %.2f GB free of %.2f GB, batch %s\n"
% (free / 1e9, total / 1e9, "{:,}".format(batch)))
# ---- correctness first, on the processor, against a hand-checked case
tn = tables(np)
i = np.array([0 + NC * (3 + NT * (10 + NS * (8 + NN * (VMID + NV * BMID))))],
dtype=np.int64)
assert int(chain(np, i, *tn)[0]) == OK, "T660, -10 C, 30 series, 24 strings"
print("hand-checked case agrees: the reference block is buildable")
# ---- warm both kernels so compilation is not timed as arithmetic
run("fused", 1 << 16)
run("chain", 1 << 16)
sec_c, tot_c = run("chain", batch)
sec_f, tot_f = run("fused", batch)
if tot_c != tot_f:
print("FAIL: chain %s vs fused %s" % (tot_c, tot_f))
return 1
# and both against the processor over a sample
stride = 1000003
while np.gcd(stride, SIZE) != 1:
stride += 2
s = (np.arange(200000, dtype=np.int64) * stride) % SIZE
a = chain(np, s, *tn)
b = cp.asnumpy(FUSED(cp.asarray(s), *tables(cp)))
differ = int((a != b).sum())
print("verified: chain == fused on all %s cases, and processor vs fused "
"on 200,000 sampled cases: %d differ\n" % ("{:,}".format(SIZE), differ))
if differ:
return 1
if SIZE < batch:
print(" NOT A THROUGHPUT: the space is smaller than one batch.")
return 1
print(" chain of elementwise kernels .. %7.3f s %15s cases/s"
% (sec_c, "{:,.0f}".format(SIZE / sec_c)))
print(" one fused kernel .............. %7.3f s %15s cases/s"
% (sec_f, "{:,.0f}".format(SIZE / sec_f)))
print(" fused is %.2fx the chain" % (sec_c / sec_f))
print("\n longest single kernel launch is well under the 2 s Windows")
print(" display timeout, which matters because this card drives the")
print(" screen: batch %s at %.3f s a pass."
% ("{:,}".format(batch), sec_f / max(1, SIZE // batch)))
print(" verdicts %s" % tot_f)
return 0
if __name__ == "__main__":
sys.exit(main())Selftest
A Python command-line tool in the engine folder of GPU Drivers for Global Grid that works with closed forms (`closed_forms`), covering solar. It is built from the kernel step (`kernel`).
othergpu-drivers-for-global-grid / engine/selftest.py · lines 1–124 of 124 · Entry point · pattern closed_forms (shared by 2 files)
- What it does
- Defines kernel, closed_forms, main. Uses libraries sys. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: solar.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Self-test for the Ventus engine: our arithmetic, both backends, verified.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- Ventus Engine (import), sys
- Used by
- none found
- Produces
- kernel, closed_forms, main
- Defines here
- kernel, closed_forms, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/selftest.py:1-124 · blob f96a90668a4ed6686001464a29fca1577f8d1bad · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""Self-test for the Ventus engine: our arithmetic, both backends, verified.
The kernel is R1 from the solar formula - the cold-voltage limit - because it
is arithmetic we own and whose answers are already published in
cuda-maths/solar-billion/FORMULA.txt. Nothing here consults a model.
python selftest.py
"""
import sys
from ventus_engine import Backend, Engine, EngineError, Space
# module classes we own (MODULE-CLASSES.md): Voc, beta %/K, Vmp
CLASSES = [(45.90, -0.25, 38.10), # T660
(50.59, -0.22, 42.58), # W760
(53.27, -0.25, 44.67)] # J-650
TMIN = [-14, -12, -11, -10, -8, -6] # site minimum, degC
SERIES = list(range(20, 35)) # modules in series
MAX_SYSTEM_V = 1500.0
# the tolerance stack, the same two axes the precision-sense work swept
N_VOC_TOL, N_BETA_TOL = 1001, 101 # Voc +/-1%, beta +/-10%
VOC_TOL_NOMINAL, BETA_TOL_NOMINAL = N_VOC_TOL // 2, N_BETA_TOL // 2
def kernel(xp, axes):
"""R1: N_max = floor(1500 / (Voc * (1 + beta/100 * (Tdesign - 25)))).
Returns a verdict code: 0 buildable on BOTH readings, 1 buildable only
with the +10 K allowance (the disputed band), 2 buildable on neither.
"""
ci, ti, si, vt, bt = axes
voc = xp.asarray([c[0] for c in CLASSES])[ci]
beta = xp.asarray([c[1] for c in CLASSES])[ci]
tmin = xp.asarray([float(t) for t in TMIN])[ti]
series = xp.asarray([float(s) for s in SERIES])[si]
# tolerance: Voc +/-1% in 1001 steps, beta +/-10% in 101 steps
voc = voc * (1.0 + (vt - (N_VOC_TOL // 2)) / (N_VOC_TOL // 2) * 0.01)
beta = beta * (1.0 + (bt - (N_BETA_TOL // 2)) / (N_BETA_TOL // 2) * 0.10)
voc_b = voc * (1.0 + beta / 100.0 * (tmin - 25.0)) # strict
voc_a = voc * (1.0 + beta / 100.0 * (tmin + 10.0 - 25.0)) # +10 K
nmax_b = xp.floor(MAX_SYSTEM_V / voc_b)
nmax_a = xp.floor(MAX_SYSTEM_V / voc_a)
ok_b = series <= nmax_b
ok_a = series <= nmax_a
return xp.where(ok_b, 0, xp.where(ok_a, 1, 2)).astype(xp.int64)
def closed_forms(np, space, kern):
"""Assert the arithmetic BEFORE any sweep, on cases computed by hand."""
# T660 at -10 C, strict reading: Voc_cold 49.92 V, N_max 30
voc = 45.90 * (1 + (-0.25) / 100 * (-10 - 25))
assert abs(voc - 49.9163) < 1e-3, voc
assert int(1500 // voc) == 30, 1500 // voc
# and at -11 C it drops to 29, which is the whole point
voc11 = 45.90 * (1 + (-0.25) / 100 * (-11 - 25))
assert int(1500 // voc11) == 29, 1500 // voc11
# the kernel must agree with those two by hand, at nominal tolerance
nom_v = np.array([VOC_TOL_NOMINAL, VOC_TOL_NOMINAL])
nom_b = np.array([BETA_TOL_NOMINAL, BETA_TOL_NOMINAL])
ci = np.array([0, 0]); ti = np.array([3, 2]); si = np.array([10, 10])
assert TMIN[3] == -10 and TMIN[2] == -11 and SERIES[10] == 30
codes = kern(np, [ci, ti, si, nom_v, nom_b])
assert int(codes[0]) == 0, "30 at -10 C must be buildable on both"
assert int(codes[1]) == 1, "30 at -11 C must be the disputed band"
# a worse Voc tolerance must never make a design MORE buildable
one = np.array([0])
for vt in (0, VOC_TOL_NOMINAL, N_VOC_TOL - 1):
c = int(kern(np, [one, np.array([3]), np.array([10]),
np.array([vt]), np.array([BETA_TOL_NOMINAL])])[0])
assert c in (0, 1, 2)
if vt == N_VOC_TOL - 1: # the +1% corner
assert c >= 1, "at +1% Voc, 30 at -10 C must stop being safe"
return True
def main():
space = Space([len(CLASSES), len(TMIN), len(SERIES),
N_VOC_TOL, N_BETA_TOL],
["module_class", "site_tmin", "modules_in_series",
"voc_tolerance", "beta_tolerance"])
print("space:", space, "\n")
results = {}
for prefer in ("cpu", "auto"):
try:
eng = Engine(space, kernel, bytes_per_case=96, prefer=prefer)
except EngineError as exc:
print("skip %s: %s" % (prefer, exc)); continue
eng.assert_closed_forms(closed_forms)
v = eng.verify(n=min(100_000, space.size * 7))
r = eng.run(nbins=3)
print(eng.report(r, v, label=eng.backend.name)); print()
results[eng.backend.name] = (r, v)
if "cupy" in results and "numpy" in results:
g, c = results["cupy"][0], results["numpy"][0]
assert g.totals == c.totals, (g.totals, c.totals)
print("BOTH BACKENDS AGREE on all %d verdicts: %s" %
(sum(g.totals), g.totals))
print("speed-up cupy over numpy: %.2fx" % (g.rate / c.rate))
print("\n--- the house rules are enforced, not merely stated ---")
eng = Engine(space, kernel, prefer="cpu")
try:
eng.run()
except EngineError as exc:
print(" run before closed forms -> refused:", exc)
eng.assert_closed_forms(closed_forms)
try:
eng.run(limit=0)
except EngineError as exc:
print(" run over zero cases -> refused:", exc)
try:
from ventus_engine import Verification
eng.report(eng.run(nbins=3), Verification(0, 0, 0.0, 0.0, "a", "b"))
except EngineError as exc:
print(" report with no evidence -> refused:", exc)
return 0
if __name__ == "__main__":
sys.exit(main())