GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / worlds- / src

Worked Examples and 1 more file

A Python command-line tool in Worlds that finds the worked examples worth showing, by enumerating where the answer TURNS.

643 lines of Python from worlds-, in 2 files. Topic: Websites and apps. Section 2040 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Worked Examples ingest · worlds- / src/worked_examples.py lines 1–382
  2. Worlds render · worlds- / src/worlds.py lines 1–261

Worked Examples

A Python command-line tool in Worlds that finds the worked examples worth showing, by enumerating where the answer TURNS.

ingestworlds- / src/worked_examples.py · lines 1–382 of 382 · Entry point · pattern launch (shared by 5 files)

What it does
It loads data. Defines 9 functions or classes, including bins, g, reference, rear_of, temp_of. Uses libraries argparse, io, json, math, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 1500V (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: 1500V.
Inputs & outputs
In: JSON file worked-examples.json; 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
It is built from the temp of helper (`temp_of`), the fresh step (`fresh`) and the launch step (`launch`). Defines `bins`, `reference`, `rear_of` and 4 more. It accepts `--run`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
worlds- · src · Python CLI
Uses
Paths (import), argparse, io, json, math, os, sys, time, numpy
Used by
none found
Produces
bins, reference, rear_of, temp_of, main
Defines here
bins, g, reference, rear_of, temp_of, main, fresh, launch, sharpness
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
worlds-@83817c34790800d4af5057629121d83d0d67a332 src/worked_examples.py:1-382 · blob e45fb8f78ba30989b328fd27d53550bbc247d9a0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Find the worked examples worth showing, by enumerating where the answer TURNS.

A worked example is not a case that fails. Most of the space fails, and a
reader learns nothing from being shown the middle of a region. What teaches is
the TIPPING POINT: the exact rear gain, or the exact temperature, at which one
design stops clearing and starts breaching - because that is the number a
reader can carry into an argument.

So this does not sample. It enumerates the whole space at a resolution fine
enough that the crossing is a real number rather than a bracket - rear gain to
0.01 %, assessment temperature to 0.01 C - and reduces, inside the kernel, to
the FIRST value on each axis at which each test trips, for every combination of
module class, series count and routing.

  1.80 trillion cases, reduced to 300 rows of four crossings each.

It computes exactly what the published site program computes, using the same
bins, so every example it returns can be typed into the Kuiper as

    fire site {"module_class": ..., "modules_in_series": ..., ...}

and will reproduce. An example that cannot be typed back in is not an example,
it is a claim.

    python worked_examples.py           the space
    python worked_examples.py --run     enumerate it on the card
"""
import argparse
import io
import json
import math
import os
import sys
import time

import numpy as np

import paths

# Not written down here: this repository is public and an absolute path
# names a drive, a machine and an account. The root comes from GRID_DATA
# in the environment; see src/paths.py for the whole argument.
MODULES = paths.MODULES
BNPI_REAR = 0.135
V_CEIL = 1500.0
STRING_INPUT_A = 20.0
MPPT_INPUT_A = 40.0
STRINGS_PER_MPPT = 2
SIZING = 1.25

SERIES = list(range(20, 35))
ROUTING = ["leapfrog", "one-after-another"]
N_REAR, REAR_LO, REAR_HI = 3001, 0.0, 30.0        # per cent, 0.01 steps
N_TEMP, TEMP_LO, TEMP_HI = 2001, -20.0, 0.0       # degrees C, 0.01 steps

B_STRING, B_MPPT, B_VOLT = 1, 2, 4
TESTS = [(B_VOLT, "over the 1500 V equipment rating"),
         (B_STRING, "over the 20 A string input"),
         (B_MPPT, "over the 40 A machine input")]


def bins():
    paths.require(MODULES, "the module electrical data (MODULES.json)")
    d = json.load(io.open(MODULES, encoding="utf-8"))
    e = d["classes"] if isinstance(d, dict) and "classes" in d else d
    e = list(e.values()) if isinstance(e, dict) else e
    out = []
    for m in e:
        def g(k):
            v = m.get(k)
            return v.get("v") if isinstance(v, dict) else v
        voc, isc, imp = g("voc"), g("isc"), g("imp")
        beta, alpha, kc = g("beta_pct_per_K"), g("alpha"), g("k_corr")
        if None in (voc, isc, imp, beta, alpha, kc):
            continue
        out.append((float(voc), float(isc), float(imp), float(beta),
                    float(alpha), (float(kc) - 1.0) / BNPI_REAR, str(g("class_id"))))
    if not out:
        raise SystemExit("FAIL: no usable bins. Nothing enumerated.")
    return out


B = bins()
NB, NS, NR = len(B), len(SERIES), len(ROUTING)
RAD = [NB, NS, NR, N_REAR, N_TEMP]
SIZE = 1
for r in RAD:
    SIZE *= r
NGROUP = NB * NS * NR

# Inside the kernel, each case tells its GROUP the smallest axis index at which
# it saw a test trip. atomicMin over 300 groups is the whole reduction: no
# intermediate array of a trillion verdicts ever exists, which is the only
# reason this fits.
# A RAW KERNEL, NOT AN ELEMENTWISE ONE, AND FOR ONE REASON: the reduction is
# atomicMin over 300 groups, and an ElementwiseKernel hands a raw array in
# wrapped, so &arr[i] is not an int* and the atomics do not compile. Written
# out longhand, the pointers are real.
SRC = r"""
extern "C" __global__ void worked(
    const long long base, const long long count,
    const double* __restrict__ voc, const double* __restrict__ isc,
    const double* __restrict__ imp, const double* __restrict__ beta,
    const double* __restrict__ alpha, const double* __restrict__ phi,
    const double* __restrict__ ser,
    int* firstRearV, int* firstRearS, int* firstRearM,
    int* warmTempV, int* warmTempS, int* warmTempM, int* cleanRear)
{
  long long t = (long long)blockIdx.x * blockDim.x + threadIdx.x;
  if (t >= count) return;
  long long r = base + t;

  int bi = (int)(r %% R0); r /= R0;
  int si = (int)(r %% R1); r /= R1;
  int gi = (int)(r %% R2); r /= R2;
  int ri = (int)(r %% R3); r /= R3;
  int ti = (int)(r %% R4);
  (void)gi;

  double rear = (RLO + (RHI - RLO) * (double)ri / (R3 - 1.0)) / 100.0;
  double tmin =  TLO + (THI - TLO) * (double)ti / (R4 - 1.0);

  double kb = 1.0 + phi[bi] * rear;
  double kt = 1.0 + alpha[bi] / 100.0 * (tmin - 25.0);
  double isc_e = isc[bi] * kb * kt;
  double imp_e = imp[bi] * kb * kt;
  double v = ser[si] * voc[bi] * (1.0 + beta[bi] / 100.0 * (tmin - 25.0));

  int over_volt   = (v > VC) ? 1 : 0;
  int over_string = (imp_e > SIA) ? 1 : 0;
  int over_mppt   = (isc_e * SPM > MIA) ? 1 : 0;

  int g = (bi * R1 + si) * R2 + gi;

  /* the FIRST rear gain at which each test trips, and the WARMEST temperature.
     Warmest is the one that matters: a design that fails warm fails every
     colder night too. */
  if (over_volt)   { atomicMin(&firstRearV[g], ri); atomicMax(&warmTempV[g], ti); }
  if (over_string) { atomicMin(&firstRearS[g], ri); atomicMax(&warmTempS[g], ti); }
  if (over_mppt)   { atomicMin(&firstRearM[g], ri); atomicMax(&warmTempM[g], ti); }
  if (!over_volt && !over_string && !over_mppt) { atomicMax(&cleanRear[g], ri); }
}
"""
SRC = (SRC.replace("R0", str(RAD[0])).replace("R1", str(RAD[1]))
          .replace("R2", str(RAD[2])).replace("R3", str(RAD[3]))
          .replace("R4", str(RAD[4]))
          .replace("RLO", repr(float(REAR_LO))).replace("RHI", repr(float(REAR_HI)))
          .replace("TLO", repr(float(TEMP_LO))).replace("THI", repr(float(TEMP_HI)))
          .replace("VC", repr(float(V_CEIL))).replace("SIA", repr(float(STRING_INPUT_A)))
          .replace("MIA", repr(float(MPPT_INPUT_A))).replace("SPM", repr(float(STRINGS_PER_MPPT)))
          .replace("%%", "%"))


def reference(idx):
    out = np.zeros(len(idx), np.int64)
    for j, i in enumerate(idx):
        r = int(i)
        v = []
        for q in RAD:
            v.append(r % q)
            r //= q
        bi, si, _gi, ri, ti = v
        rear = (REAR_LO + (REAR_HI - REAR_LO) * ri / (N_REAR - 1.0)) / 100.0
        tmin = TEMP_LO + (TEMP_HI - TEMP_LO) * ti / (N_TEMP - 1.0)
        voc, isc, imp, beta, alpha, phi, _cid = B[bi]
        kb = 1.0 + phi * rear
        kt = 1.0 + alpha / 100.0 * (tmin - 25.0)
        isc_e, imp_e = isc * kb * kt, imp * kb * kt
        vv = SERIES[si] * voc * (1.0 + beta / 100.0 * (tmin - 25.0))
        m = 0
        if imp_e > STRING_INPUT_A:
            m |= B_STRING
        if isc_e * STRINGS_PER_MPPT > MPPT_INPUT_A:
            m |= B_MPPT
        if vv > V_CEIL:
            m |= B_VOLT
        out[j] = m
    return out


def rear_of(i):
    return REAR_LO + (REAR_HI - REAR_LO) * i / (N_REAR - 1.0)


def temp_of(i):
    return TEMP_LO + (TEMP_HI - TEMP_LO) * i / (N_TEMP - 1.0)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", action="store_true")
    a = ap.parse_args()

    print("WORKED EXAMPLES: enumerate where the answer TURNS")
    print("  module class        %6d" % NB)
    print("  modules in series   %6d   %d to %d" % (NS, SERIES[0], SERIES[-1]))
    print("  routing             %6d" % NR)
    print("  rear gain           %6d   %g to %g %%, 0.01 steps"
          % (N_REAR, REAR_LO, REAR_HI))
    print("  assessment temp     %6d   %g to %g C, 0.01 steps"
          % (N_TEMP, TEMP_LO, TEMP_HI))
    print("                      ------")
    print("                      %s cases, reduced to %d groups"
          % ("{:,}".format(SIZE), NGROUP))
    if not a.run:
        print("\n  --run to enumerate on the card.")
        return 0

    import cupy as cp
    mod = cp.RawModule(code=SRC, backend="nvrtc")
    fn = mod.get_function("worked")

    cols = [np.array([b[k] for b in B], float) for k in range(6)]
    dv, di, dp, dbe, dal, dph = (cp.asarray(c) for c in cols)
    dser = cp.asarray(np.array(SERIES, float))
    BIG = np.int32(1 << 30)

    def fresh():
        return (cp.full(NGROUP, BIG, cp.int32), cp.full(NGROUP, BIG, cp.int32),
                cp.full(NGROUP, BIG, cp.int32), cp.full(NGROUP, -1, cp.int32),
                cp.full(NGROUP, -1, cp.int32), cp.full(NGROUP, -1, cp.int32),
                cp.full(NGROUP, -1, cp.int32))

    def launch(base, count, arrs):
        threads = 256
        blocks = int((count + threads - 1) // threads)
        fn((blocks,), (threads,),
           (np.int64(base), np.int64(count), dv, di, dp, dbe, dal, dph, dser) + arrs)

    # VERIFY THE THING THAT IS ACTUALLY REPORTED, NOT A PROXY. Earlier sweeps
    # checked a per-case verdict; what this one reports is a REDUCTION, and a
    # reduction can be wrong in ways a per-case check never sees - a race, a
    # wrong group index, an atomic that loses an update. So the processor runs
    # the same reduction over the same contiguous block and the two sets of
    # crossings must agree exactly, every group, every column.
    VN = 20_000_000
    arrs = fresh()
    launch(0, VN, arrs)
    cp.cuda.Stream.null.synchronize()
    gpu = [cp.asnumpy(x) for x in arrs]

    idx = np.arange(VN, dtype=np.int64)
    r = idx.copy()
    bi = (r % RAD[0]).astype(np.int64); r //= RAD[0]
    si = (r % RAD[1]).astype(np.int64); r //= RAD[1]
    gi = (r % RAD[2]).astype(np.int64); r //= RAD[2]
    ri = (r % RAD[3]).astype(np.int64); r //= RAD[3]
    ti = (r % RAD[4]).astype(np.int64)
    voc = cols[0][bi]; isc = cols[1][bi]; imp = cols[2][bi]
    beta = cols[3][bi]; alpha = cols[4][bi]; phi = cols[5][bi]
    rear = (REAR_LO + (REAR_HI - REAR_LO) * ri / (N_REAR - 1.0)) / 100.0
    tmin = TEMP_LO + (TEMP_HI - TEMP_LO) * ti / (N_TEMP - 1.0)
    kb = 1.0 + phi * rear
    kt = 1.0 + alpha / 100.0 * (tmin - 25.0)
    isc_e = isc * kb * kt; imp_e = imp * kb * kt
    vv = np.array(SERIES, float)[si] * voc * (1.0 + beta / 100.0 * (tmin - 25.0))
    ov = vv > V_CEIL; os_ = imp_e > STRING_INPUT_A
    om = isc_e * STRINGS_PER_MPPT > MPPT_INPUT_A
    grp = (bi * RAD[1] + si) * RAD[2] + gi
    cpu = [np.full(NGROUP, BIG, np.int32) for _ in range(3)] +           [np.full(NGROUP, -1, np.int32) for _ in range(4)]
    for k, mask in enumerate((ov, os_, om)):
        if mask.any():
            np.minimum.at(cpu[k], grp[mask], ri[mask].astype(np.int32))
            np.maximum.at(cpu[3 + k], grp[mask], ti[mask].astype(np.int32))
    clean = ~ov & ~os_ & ~om
    if clean.any():
        np.maximum.at(cpu[6], grp[clean], ri[clean].astype(np.int32))
    differ = int(sum(int((g != c).sum()) for g, c in zip(gpu, cpu)))
    print("\n  verified: processor vs card on the REDUCTION over %s cases,"
          % "{:,}".format(VN))
    print("            %d of %d group values differ" % (differ, NGROUP * 7))
    if differ:
        print("  FAIL: nothing reported for a reduction that differs.")
        return 1

    arrs = fresh()
    step = 1 << 26
    done, t0 = 0, time.perf_counter()
    while done < SIZE:
        n = min(step, SIZE - done)
        launch(done, n, arrs)
        done += n
    cp.cuda.Stream.null.synchronize()
    sec = time.perf_counter() - t0
    print("  ENUMERATED %s in %.1f s (%s cases/s)"
          % ("{:,}".format(SIZE), sec, "{:,.0f}".format(SIZE / sec)))
    fV, fS, fM, wV, wS, wM, cR = arrs

    fV, fS, fM = cp.asnumpy(fV), cp.asnumpy(fS), cp.asnumpy(fM)
    wV, wS, wM = cp.asnumpy(wV), cp.asnumpy(wS), cp.asnumpy(wM)
    cR = cp.asnumpy(cR)

    rows = []
    for bi in range(NB):
        for si in range(NS):
            for gi in range(NR):
                g = (bi * NS + si) * NR + gi
                if gi != 0:
                    continue          # routing does not enter these three tests
                voc, isc, imp, beta, alpha, phi, cid = B[bi]
                rows.append({
                    "module_class": cid,
                    "modules_in_series": SERIES[si],
                    "bifaciality_derived": round(phi, 3),
                    "volt_trips_at_rear_pct": None if fV[g] >= BIG else round(rear_of(fV[g]), 2),
                    "volt_trips_warmest_c": None if wV[g] < 0 else round(temp_of(wV[g]), 2),
                    "string_trips_at_rear_pct": None if fS[g] >= BIG else round(rear_of(fS[g]), 2),
                    "string_trips_warmest_c": None if wS[g] < 0 else round(temp_of(wS[g]), 2),
                    "mppt_trips_at_rear_pct": None if fM[g] >= BIG else round(rear_of(fM[g]), 2),
                    "mppt_trips_warmest_c": None if wM[g] < 0 else round(temp_of(wM[g]), 2),
                    "clears_up_to_rear_pct": None if cR[g] < 0 else round(rear_of(cR[g]), 2),
                })

    # A TURN IS WORTH SHOWING WHEN IT IS CLOSE. A design that trips at 0 % rear
    # gain teaches nothing - it was never viable. One that trips at 11.3 % is an
    # argument, because 13.5 % is the sheet's own standard condition.
    def sharpness(r):
        best = None
        for k in ("volt_trips_at_rear_pct", "string_trips_at_rear_pct",
                  "mppt_trips_at_rear_pct"):
            x = r[k]
            if x is None or x <= 0.0:
                continue
            d = abs(x - 13.5)          # distance from the sheet's BNPI row
            best = d if best is None else min(best, d)
        return best

    ranked = [r for r in rows if sharpness(r) is not None]
    ranked.sort(key=sharpness)
    print("\n  THE TEN SHARPEST TURNS (closest to the sheet's own 13.5%% rear row)")
    print("  %-7s %-7s %-22s %-22s %s"
          % ("class", "series", "volts trip at rear", "string trips at rear",
             "clears to"))
    for r in ranked[:10]:
        print("  %-7s %-7d %-22s %-22s %s"
              % (r["module_class"], r["modules_in_series"],
                 "-" if r["volt_trips_at_rear_pct"] is None
                 else "%.2f%% (warmest %.2f C)" % (r["volt_trips_at_rear_pct"],
                                                   r["volt_trips_warmest_c"]),
                 "-" if r["string_trips_at_rear_pct"] is None
                 else "%.2f%% (warmest %.2f C)" % (r["string_trips_at_rear_pct"],
                                                   r["string_trips_warmest_c"]),
                 "-" if r["clears_up_to_rear_pct"] is None
                 else "%.2f%%" % r["clears_up_to_rear_pct"]))

    out = {"cases": SIZE, "seconds": round(sec, 2), "verified_differ": differ,
           "groups": NGROUP,
           "resolution": {"rear_gain_pct": 0.01, "assessment_temp_c": 0.01},
           "axes": {"module_class": NB, "modules_in_series": [SERIES[0], SERIES[-1]],
                    "rear_gain_pct": [REAR_LO, REAR_HI],
                    "assessment_temp_c": [TEMP_LO, TEMP_HI]},
           "datasheet_bnpi_rear_pct": BNPI_REAR * 100,
           "rows": rows,
           "ten_sharpest": ranked[:10],
           "what_a_turn_means":
               "The first rear gain, and the warmest assessment temperature, at "
               "which a test stops being satisfied. Warmest is the one that "
               "matters: a design that fails warm fails every colder night too. "
               "A turn at 0 % teaches nothing because the design was never "
               "viable; a turn near 13.5 % is an argument, because 13.5 % is "
               "the rear condition the datasheet itself publishes.",
           "reproducible":
               "Every row can be typed into the renderer as "
               "fire site {\"module_class\": ..., \"modules_in_series\": ..., "
               "\"rear_gain_pct\": ..., \"site_min_c\": ...} and will agree. An "
               "example that cannot be typed back in is a claim, not an example.",
           "not_computed":
               "Routing does not enter these three tests - it sets loop "
               "inductance and therefore the transient, which is a separate "
               "sweep. No load flow, no fault level, no yield, no cost.",
           "anonymised": "No project, site, maker or model anywhere."}
    p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                     "night-results", "worked-examples.json")
    os.makedirs(os.path.dirname(p), exist_ok=True)
    io.open(p, "w", encoding="utf-8", newline="\n").write(
        json.dumps(out, indent=1) + "\n")
    print("\n  wrote night-results/worked-examples.json")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Worlds

A Python command-line tool. It is built from the tables step (`tables`), the reference step (`reference`) and the page step (`page`).

renderworlds- / src/worlds.py · lines 1–261 of 261 · Entry point · pattern tables (shared by 4 files)

What it does
It draws its content. Defines tables, reference, page, main. Uses libraries io, os, sys, time, numpy. Side effects: changes the web page (DOM); starts processes.
Inputs & outputs
In: form fields (user input). Out: canvas drawing.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
The same points, rearranged, on the card.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
worlds- · src · Python CLI
Uses
io, os, sys, time, numpy, placement, cupy
Used by
none found
Produces
tables, reference, page, main
Defines here
tables, reference, page, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
worlds-@83817c34790800d4af5057629121d83d0d67a332 src/worlds.py:1-261 · blob 089f6e69eae9bd442483c520ff382901abeec70b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: unknown · users: none · canonical: unknown
"""Worlds: the same points, rearranged, on the card.

From the Kuiper to the wafer. The Kuiper arranges work by ORDER - oldest at
the middle, newest at the rim, on a golden spiral that never has to move
anything already placed. A design sweep needs the opposite: neighbouring cases
adjacent, so the boundary between one verdict and another shows as an edge
rather than as dust.

So this holds both arrangements and the journey between them. Nothing is
created or destroyed when a world changes shape; the same points move. That is
what makes the sweep legible as a descendant of the archive rather than a
different object entirely.

Everything is generated from an index on the card. No geometry is stored: the
world is a function, which is why eighteen quintillion planets fit in a few
hundred megabytes and why a billion designs fit in none at all.

    python worlds.py                 generate, verify, write worlds.html

Verified before anything is drawn: the card's geometry must equal the
processor's, point for point.
"""
import io
import os
import sys
import time

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from placement import GOLDEN, hilbert, hilbert_order, lattice, morph  # noqa: E402

try:
    import cupy as cp
except Exception as exc:                                   # pragma: no cover
    print("cupy unavailable: %r" % (exc,))
    sys.exit(1)

# ---- the space being arranged: a solar string design, as we already prove it
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)]
NC, NT, NS, NN = len(CLASSES), len(TMIN), len(SERIES), len(STRINGS)
RADICES = [NC, NT, NS, NN]
SIZE = NC * NT * NS * NN
ORDER = hilbert_order(SIZE)

INVERTER_KVA, MAX_V = 352.0, 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40
OK, DISPUTED, FAIL_COLD, OUT_OF_BAND = 0, 1, 2, 3
LABEL = ["buildable, both readings", "disputed: the clause decides it",
         "fails cold voltage", "DC:AC outside the band"]
COLOUR = ["#4ade80", "#f2b05e", "#5ec8f2", "#38415a"]

_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);

double v = voc[ci], b = beta[ci], w = wp[ci];
double tm = tmin[ti], se = ser[si], st = strs[ni];

double nb = floor(%(MAXV).1f / (v * (1.0 + b / 100.0 * (tm - 25.0))));
double na = floor(%(MAXV).1f / (v * (1.0 + b / 100.0 * (tm - 15.0))));
double dcac = (se * w / 1000.0) * st / %(KVA).1f;
bool band = (dcac >= %(LO).2f) && (dcac <= %(HI).2f);
code = (se > na) ? %(FC)d : ((se > nb) ? %(DI)d : (band ? %(OK)d : %(OB)d));

/* ARRANGEMENT ONE - the archive. Adjacency is order, oldest at the middle.
   Place j never moves when j+1 arrives, and the angle never aligns. */
double rad = %(SPACING).17g * sqrt((double)idx);
/* REDUCE BEFORE THE TRIG. By index 4,589 the accumulated angle is ~11,012
   rad, and CUDA and the host reduce arguments that large by different
   routes - a difference that sqrt(idx) then multiplies. fmod is exact on
   doubles, so both sides must do this identically or they disagree. */
double th  = fmod((double)idx * %(GOLDEN).17f, 6.283185307179586477);
gx = (float)(rad * cos(th));
gy = (float)(rad * sin(th));

/* ARRANGEMENT TWO - the swept space. Adjacency is one parameter, one step,
   so a verdict boundary is an edge. Hilbert curve, side 2^order. */
long long t = idx; long long hx = 0, hy = 0;
for (long long s = 1; s < (1LL << %(ORDER)d); s <<= 1) {
    long long rx = ((t / 2) %% 2) ? 1 : 0;
    long long ry = ((t ^ rx) %% 2) ? 1 : 0;
    if (ry == 0) {
        if (rx == 1) { hx = s - 1 - hx; hy = s - 1 - hy; }
        long long tmp = hx; hx = hy; hy = tmp;
    }
    hx += s * rx; hy += s * ry; t /= 4;
}
/* .17g, not .6f: a constant baked into kernel source at six
   decimals differs from the host's double by ~5e-7 relative,
   which an offset of up to 64 turns into 3e-5 absolute. That is
   how the first run failed its own 0-differ check. */
px = (float)(((double)hx - %(HALF).17g) * %(HSCALE).17g);
py = (float)(((double)hy - %(HALF).17g) * %(HSCALE).17g);
""" % {"NC": NC, "NT": NT, "NS": NS, "NN": NN, "MAXV": MAX_V,
       "KVA": INVERTER_KVA, "LO": DCAC_LO, "HI": DCAC_HI, "FC": FAIL_COLD,
       "DI": DISPUTED, "OK": OK, "OB": OUT_OF_BAND, "ORDER": ORDER,
       "SPACING": 1.0, "GOLDEN": GOLDEN, "HALF": (1 << ORDER) / 2.0,
       "HSCALE": 2.0 * np.sqrt(SIZE) / (1 << ORDER)}

WORLD = cp.ElementwiseKernel(
    "int64 idx, raw float64 voc, raw float64 beta, raw float64 wp, "
    "raw float64 tmin, raw float64 ser, raw float64 strs",
    "int64 code, float32 gx, float32 gy, float32 px, float32 py",
    _SRC, "ventus_world")


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 reference(n):
    """The same worlds on the processor, using the canonical placement."""
    gx = np.zeros(n, np.float32); gy = np.zeros(n, np.float32)
    px = np.zeros(n, np.float32); py = np.zeros(n, np.float32)
    code = np.zeros(n, np.int64)
    half, hscale = (1 << ORDER) / 2.0, 2.0 * np.sqrt(SIZE) / (1 << ORDER)
    for i in range(n):
        ci, ti, si, ni = lattice(i, RADICES)
        v, b, w = CLASSES[ci]
        tm, se, st = TMIN[ti], SERIES[si], STRINGS[ni]
        nb = np.floor(MAX_V / (v * (1 + b / 100 * (tm - 25))))
        na = np.floor(MAX_V / (v * (1 + b / 100 * (tm - 15))))
        dcac = (se * w / 1000.0) * st / INVERTER_KVA
        band = DCAC_LO <= dcac <= DCAC_HI
        code[i] = (FAIL_COLD if se > na else
                   (DISPUTED if se > nb else (OK if band else OUT_OF_BAND)))
        th = np.fmod(i * GOLDEN, 2.0 * np.pi)
        g = (np.sqrt(i) * np.cos(th), np.sqrt(i) * np.sin(th))
        gx[i], gy[i] = np.float32(g[0]), np.float32(g[1])
        hx, hy = hilbert(i, ORDER)
        px[i] = np.float32((hx - half) * hscale)
        py[i] = np.float32((hy - half) * hscale)
    return code, gx, gy, px, py


def page(code, gx, gy, px, py, path):
    """One plane, zoomable, and a handle that moves the ancestor into the
    descendant. The points never change; only the arrangement does."""
    pts = ",".join("[%d,%.4f,%.4f,%.4f,%.4f]" % (c, a, b, d, e)
                   for c, a, b, d, e in zip(code, gx, gy, px, py))
    counts = [int((code == k).sum()) for k in range(4)]
    legend = "".join(
        '<span class="k"><i style="background:%s"></i>%s <b>%s</b></span>'
        % (COLOUR[k], LABEL[k], "{:,}".format(counts[k])) for k in range(4))
    html = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Worlds</title><style>
:root{color-scheme:dark}*{box-sizing:border-box}
body{margin:0;background:#07090d;color:#cfe3f2;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;overflow:hidden}
canvas{display:block;width:100vw;height:100vh;cursor:crosshair}
.bar{position:fixed;left:0;right:0;bottom:0;padding:10px 14px;background:#0b0e14e6;border-top:1px solid #1b2030}
.k{margin-right:14px;font-size:11.5px;white-space:nowrap}
.k i{display:inline-block;width:9px;height:9px;margin-right:5px;border-radius:2px;vertical-align:middle}
.t{position:fixed;top:0;left:0;right:0;padding:10px 14px;background:#0b0e14e6;border-bottom:1px solid #1b2030;font-size:12px}
.t b{color:#fff}.t span{color:#8b93a7}
input[type=range]{width:min(320px,45vw);vertical-align:middle}
#card{position:fixed;right:14px;top:56px;max-width:290px;padding:10px 12px;background:#11151f;border:1px solid #1b2030;border-radius:8px;font-size:11.5px;display:none}
</style></head><body>
<div class="t"><b>Worlds</b> &#8212; %(n)s designs, every point generated on the card
<span>&#183; drag to pan, wheel to zoom, tap a point</span><br>
<span>ancestor</span> <input id="m" type="range" min="0" max="1000" value="1000"> <span>descendant</span>
<span id="ml">&#183; the Kuiper arrangement &#8594; the swept plane</span></div>
<canvas id="c"></canvas>
<div id="card"></div>
<div class="bar">%(legend)s</div>
<script>
const P=[%(pts)s], COL=%(col)s, LAB=%(lab)s;
const c=document.getElementById("c"),g=c.getContext("2d"),card=document.getElementById("card");
let z=1,ox=0,oy=0,t=1,drag=null;
function fit(){c.width=innerWidth*devicePixelRatio;c.height=innerHeight*devicePixelRatio;draw();}
function pos(p){const k=t*t*(3-2*t);return [p[1]+(p[3]-p[1])*k, p[2]+(p[4]-p[2])*k];}
function draw(){
 g.setTransform(1,0,0,1,0,0);g.fillStyle="#07090d";g.fillRect(0,0,c.width,c.height);
 const s=Math.min(c.width,c.height)/(2.6*Math.sqrt(P.length))*z;
 const cx=c.width/2+ox*devicePixelRatio, cy=c.height/2+oy*devicePixelRatio;
 const r=Math.max(0.7,Math.min(4.2,s*0.42))*devicePixelRatio;
 for(const p of P){const [x,y]=pos(p);
  g.fillStyle=COL[p[0]];g.beginPath();g.arc(cx+x*s,cy-y*s,r,0,6.2832);g.fill();}
}
addEventListener("resize",fit);
c.addEventListener("wheel",e=>{e.preventDefault();const k=Math.exp(-e.deltaY*0.0012);z=Math.max(0.25,Math.min(90,z*k));draw();},{passive:false});
c.addEventListener("pointerdown",e=>{drag=[e.clientX,e.clientY,ox,oy];c.setPointerCapture(e.pointerId);});
c.addEventListener("pointermove",e=>{if(!drag)return;ox=drag[2]+(e.clientX-drag[0]);oy=drag[3]+(e.clientY-drag[1]);draw();});
c.addEventListener("pointerup",e=>{
 if(drag&&Math.abs(e.clientX-drag[0])<3&&Math.abs(e.clientY-drag[1])<3){
  const s=Math.min(c.width,c.height)/(2.6*Math.sqrt(P.length))*z;
  const cx=c.width/2+ox*devicePixelRatio, cy=c.height/2+oy*devicePixelRatio;
  let best=-1,bd=1e18;
  P.forEach((p,i)=>{const [x,y]=pos(p);const dx=cx+x*s-e.clientX*devicePixelRatio,dy=cy-y*s-e.clientY*devicePixelRatio;const d=dx*dx+dy*dy;if(d<bd){bd=d;best=i;}});
  if(best>=0&&bd<(28*devicePixelRatio)**2){
   const i=best,rad=%(rad)s;let r=i,ax=[];for(const q of rad){ax.push(r%%q);r=Math.floor(r/q);}
   card.style.display="block";
   card.innerHTML="<b>index "+i+"</b><br>"+LAB[P[i][0]]+
    "<br><span style='color:#8b93a7'>class "+ax[0]+" &#183; site min "+%(tmin)s[ax[1]]+" &#176;C &#183; "+
    %(ser)s[ax[2]]+" in series &#183; "+%(strs)s[ax[3]]+" strings</span>";
  } else card.style.display="none";
 }
 drag=null;});
document.getElementById("m").addEventListener("input",e=>{t=e.target.value/1000;
 document.getElementById("ml").textContent=t<0.02?"\\u00b7 the Kuiper arrangement: adjacency is order":t>0.98?"\\u00b7 the swept plane: adjacency is one parameter, one step":"\\u00b7 the same points, moving";draw();});
fit();
</script></body></html>
""" % {"n": "{:,}".format(len(code)), "pts": pts, "legend": legend,
       "col": str(COLOUR).replace("'", '"'), "lab": str(LABEL).replace("'", '"'),
       "rad": str(RADICES), "tmin": str(TMIN), "ser": str([int(s) for s in SERIES]),
       "strs": str([int(s) for s in STRINGS])}
    io.open(path, "w", encoding="utf-8", newline="\n").write(html)


def main():
    print("world: %s designs over %d axes %s, hilbert order %d (side %d)"
          % ("{:,}".format(SIZE), len(RADICES), RADICES, ORDER, 1 << ORDER))
    t = tables(cp)
    idx = cp.arange(SIZE, dtype=cp.int64)
    cp.cuda.Stream.null.synchronize()
    t0 = time.perf_counter()
    code, gx, gy, px, py = WORLD(idx, *t)
    cp.cuda.Stream.null.synchronize()
    sec = time.perf_counter() - t0

    h = [cp.asnumpy(a) for a in (code, gx, gy, px, py)]
    r = reference(SIZE)
    worst = max(float(np.abs(h[i].astype(np.float64)
                             - r[i].astype(np.float64)).max()) for i in range(5))
    print("verified against the processor, all %s worlds: worst difference "
          "%.3e" % ("{:,}".format(SIZE), worst))
    if worst > 0:
        print("FAIL: the card and the processor drew different worlds")
        return 1
    if SIZE < 1 << 20:
        print("the card generated them in %.4f s - NOT a throughput, the "
              "space is small" % sec)
    else:
        print("%s designs/s" % "{:,.0f}".format(SIZE / sec))

    here = os.path.dirname(os.path.abspath(__file__))
    out = os.path.join(os.path.dirname(here), "worlds.html")
    page(*h, path=out)
    counts = [int((h[0] == k).sum()) for k in range(4)]
    print("\nwrote %s" % os.path.basename(out))
    for k in range(4):
        print("  %-32s %8s  %5.2f%%"
              % (LABEL[k], "{:,}".format(counts[k]), 100.0 * counts[k] / SIZE))
    print("\nThe slider moves the SAME points from the archive arrangement to")
    print("the swept one. Nothing is created or destroyed between them.")
    return 0


if __name__ == "__main__":
    sys.exit(main())