GLOBALGRID2050 / EXPLORE CODE

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

Harvest Crunch and 1 more file

A Python command-line tool in Worlds that reads worksheet, using SHA-256. It builds h1 (`build_h1`), builds h2 (`build_h2`) and builds h3 (`build_h3`).

700 lines of Python from worlds-, in 2 files. Topic: Websites and apps. Section 2030 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. Geometry ingest · worlds- / src/geometry.py lines 1–309
  2. Harvest Crunch ingest · worlds- / src/harvest_crunch.py lines 1–391

Geometry

A Python command-line tool in Worlds that uses SHA-256. It is built from the bins step (`bins`).

ingestworlds- / src/geometry.py · lines 1–309 of 309 · Entry point

What it does
It loads data. Defines bins, g, main. Uses libraries argparse, hashlib, io, json, 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 geometry.json; command-line arguments. Voltage levels named: 1500V.
Downstream impact
Used directly by 1 file: All Gates (worlds-).
What it achieves
LOGIC AS GEOMETRY. A rule is not a verdict; it is a shape. It accepts `--run`.
Why it matters
Run by All Gates.
Application
worlds- · src · Python CLI
Uses
Paths (import), argparse, hashlib, io, json, os, sys, time, numpy
Used by
run by All Gates (script call)
Produces
bins, main
Defines here
bins, g, 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/geometry.py:1-309 · blob a7467528700717252f74b6cde2a5e66f9ea3b1dd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""LOGIC AS GEOMETRY. A rule is not a verdict; it is a shape.

THE IDEA, stated before any arithmetic
A predicate over numeric axes - "this string is over 1500 V" - is usually read
as a yes or a no about one design. That is the smallest thing it is. Over a
space of designs the same predicate is a REGION: a volume of parameter space
where it holds, with a SURFACE where it stops holding.

That surface is the only part a designer should care about.

  A case deep inside the region is robust. Every neighbour agrees with it.
  Nudge a temperature by a hundredth of a degree, a rear gain by a hundredth
  of a per cent, and the answer does not move.

  A case ON the surface has a neighbour that disagrees. Its verdict is one
  step from flipping, and the step is smaller than the precision of anything
  anyone will ever measure on site.

So the question stops being "does this design pass" and becomes "how far is
this design from the nearest answer that is not its own". That is a distance,
in a space, and distances are what geometry is for.

HOW THE SURFACE IS FOUND
Each case has 2n neighbours - one step up and one step down along each axis.
A case is on the surface when any neighbour's verdict differs from its own.
This is the discrete boundary operator, and it is exactly the shape a card
wants: every thread reads its own case and 2n more, no communication, no
ordering, no host.

WHAT COMES BACK
  volume        how much of the space the rule claims
  surface       how much of it is one step from a different answer
  ratio         surface over volume - how FRAGILE the rule is here. A thin
                shell around a fat region is a robust rule. A region that is
                almost all surface is a rule the space cannot resolve.
  the points    the actual boundary cases, which are geometry, and which the
                Kuiper can draw as a shape rather than as a number.

THE PAIR RULE STILL HOLDS. Every verdict is computed twice by two different
formulations, and a case where they part is excluded from both counts and
reported on its own - because a boundary found by a rounding difference is not
a boundary of the rule, it is a boundary of the arithmetic.

    python geometry.py            the space
    python geometry.py --run      find the surfaces
"""
import argparse
import hashlib
import io
import json
import os
import sys
import time

import numpy as np

import paths

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 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
OUT = os.path.join(ROOT, "night-results", "geometry.json")

V_CEIL, STRING_A, MPPT_A, SPM, SIZING = 1500.0, 20.0, 40.0, 2.0, 1.25
BNPI_REAR = 0.135

SERIES = list(range(20, 35))
N_REAR, REAR_LO, REAR_HI = 601, 0.0, 30.0        # 0.05 % steps
N_TEMP, TEMP_LO, TEMP_HI = 901, -20.0, 25.0      # 0.05 C steps

TESTS = [(1, "over the 1500 V equipment rating", "DATASHEET, all ten bins"),
         (2, "over the 20 A string input", "NO SOURCE ANYWHERE"),
         (4, "over the 40 A machine input", "ABSENT from both documents"),
         (8, "over the max series fuse", "DATASHEET, per bin")]


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
        vals = [g(k) for k in ("voc", "isc", "imp", "beta_pct_per_K",
                               "alpha", "k_corr", "max_series_fuse_a")]
        if any(v is None for v in vals):
            continue
        voc, isc, imp, beta, alpha, kc, fuse = [float(v) for v in vals]
        out.append((voc, isc, imp, beta, alpha, (kc - 1.0) / BNPI_REAR, fuse))
    if not out:
        raise SystemExit("FAIL: no usable bins.")
    return out


B = bins()
RAD = [len(B), len(SERIES), N_REAR, N_TEMP]
SIZE = RAD[0] * RAD[1] * RAD[2] * RAD[3]

SRC = r"""
__device__ __forceinline__ int verdict(
    long long r,
    const double* voc, const double* isc, const double* imp,
    const double* beta, const double* alpha, const double* phi,
    const double* fuse, const double* ser, int expanded)
{
  int bi = (int)(r % NB); r /= NB;
  int si = (int)(r % NS); r /= NS;
  int ri = (int)(r % NR); r /= NR;
  int ti = (int)(r % NT);
  double rear = (RLO + (RHI - RLO) * (double)ri / (NR - 1.0)) / 100.0;
  double tm   =  TLO + (THI - TLO) * (double)ti / (NT - 1.0);
  double kb = 1.0 + phi[bi] * rear;
  double kt = 1.0 + alpha[bi] / 100.0 * (tm - 25.0);
  double isc_e = isc[bi] * kb * kt;
  double imp_e = imp[bi] * kb * kt;
  double b = beta[bi] / 100.0 * (tm - 25.0);
  /* the same voltage two ways: factored rounds once, expanded rounds twice */
  double v = expanded ? (ser[si] * voc[bi] + ser[si] * voc[bi] * b)
                      : (ser[si] * (voc[bi] * (1.0 + b)));
  int m = 0;
  if (!(v <= VC))                     m |= 1;
  if (!(imp_e <= SIA))                m |= 2;
  if (!(isc_e * SPMV <= MIA))         m |= 4;
  if (!(SZ * isc_e <= fuse[bi]))      m |= 8;
  return m;
}

extern "C" __global__ void surfaces(
    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__ fuse, const double* __restrict__ ser,
    long long* volume, long long* surface, long long* disagree)
{
  long long t = (long long)blockIdx.x * blockDim.x + threadIdx.x;
  if (t >= count) return;
  long long i = base + t;

  int m  = verdict(i, voc, isc, imp, beta, alpha, phi, fuse, ser, 0);
  int m2 = verdict(i, voc, isc, imp, beta, alpha, phi, fuse, ser, 1);

  /* A BOUNDARY FOUND BY A ROUNDING DIFFERENCE IS NOT A BOUNDARY OF THE RULE.
     Where the two formulations part, the case is excluded from both counts
     and reported on its own. */
  if ((m & 1) != (m2 & 1)) { atomicAdd((unsigned long long*)&disagree[0], 1ULL); return; }

  /* decode once, to step along each axis */
  long long r = i;
  int bi = (int)(r % NB); r /= NB;
  int si = (int)(r % NS); r /= NS;
  int ri = (int)(r % NR); r /= NR;
  int ti = (int)(r % NT);
  int n[4] = {NB, NS, NR, NT};
  int c[4] = {bi, si, ri, ti};
  long long stride[4] = {1, NB, (long long)NB*NS, (long long)NB*NS*NR};

  int onsurface = 0;
  for (int ax = 0; ax < 4 && !onsurface; ax++) {
    for (int d = -1; d <= 1; d += 2) {
      int q = c[ax] + d;
      if (q < 0 || q >= n[ax]) continue;          /* the edge of the sweep is
                                                     NOT a surface of the rule */
      long long j = i + (long long)d * stride[ax];
      int mj = verdict(j, voc, isc, imp, beta, alpha, phi, fuse, ser, 0);
      if (mj != m) { onsurface = 1; break; }
    }
  }

  for (int k = 0; k < 4; k++) {
    int bit = 1 << k;
    if (m & bit) {
      atomicAdd((unsigned long long*)&volume[k], 1ULL);
      if (onsurface) atomicAdd((unsigned long long*)&surface[k], 1ULL);
    }
  }
  if (onsurface) atomicAdd((unsigned long long*)&surface[4], 1ULL);
  atomicAdd((unsigned long long*)&volume[4], 1ULL);
}
"""
SRC = (SRC.replace("NB", str(RAD[0])).replace("NS", str(RAD[1]))
          .replace("NR", str(RAD[2])).replace("NT", str(RAD[3]))
          .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_A)))
          .replace("MIA", repr(float(MPPT_A))).replace("SPMV", repr(float(SPM)))
          .replace("SZ", repr(float(SIZING))))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", action="store_true")
    a = ap.parse_args()
    print("LOGIC AS GEOMETRY: every rule is a region, and the surface is")
    print("the only part a designer should care about.")
    print("  module bins        %6d" % RAD[0])
    print("  modules in series  %6d   %d..%d" % (RAD[1], SERIES[0], SERIES[-1]))
    print("  rear gain          %6d   %g..%g %%  (0.05 steps)" % (RAD[2], REAR_LO, REAR_HI))
    print("  assessment temp    %6d   %g..%g C  (0.05 steps)" % (RAD[3], TEMP_LO, TEMP_HI))
    print("                     ------")
    print("  cases              %s, each reading 8 neighbours" % "{:,}".format(SIZE))
    print("  verdicts computed  %s" % "{:,}".format(SIZE * 10))
    if not a.run:
        print("\n  --run to find the surfaces.")
        return 0

    import cupy as cp
    mod = cp.RawModule(code=SRC, backend="nvrtc")
    fn = mod.get_function("surfaces")
    cols = [np.array([b[k] for b in B], float) for k in range(7)]
    col = tuple(cp.asarray(c) for c in cols) + (
        cp.asarray(np.array(SERIES, float)),)
    vol = cp.zeros(5, dtype=cp.int64)
    sur = cp.zeros(5, dtype=cp.int64)
    dis = cp.zeros(1, dtype=cp.int64)

    threads, done, t0 = 256, 0, time.perf_counter()
    while done < SIZE:
        k = min(1 << 25, SIZE - done)
        fn(((k + threads - 1) // threads,), (threads,),
           (np.int64(done), np.int64(k)) + col + (vol, sur, dis))
        done += k
    cp.cuda.Stream.null.synchronize()
    sec = time.perf_counter() - t0
    V = [int(x) for x in cp.asnumpy(vol)]
    S = [int(x) for x in cp.asnumpy(sur)]
    D = int(cp.asnumpy(dis)[0])

    print("\n  MEASURED %s cases in %.2f s (%s verdicts/s)"
          % ("{:,}".format(SIZE), sec, "{:,.0f}".format(SIZE * 10 / sec)))
    print("  excluded, because the two formulations parted: %s" % "{:,}".format(D))

    print("\n  %-38s %14s %14s %8s" % ("rule", "volume", "surface", "ratio"))
    rows = []
    for k, (bit, name, prov) in enumerate(TESTS):
        v, s = V[k], S[k]
        r = (s / v) if v else float("nan")
        print("  %-38s %14s %14s %7.3f"
              % (name, "{:,}".format(v), "{:,}".format(s), r))
        rows.append({"rule": name, "provenance": prov, "volume": v,
                     "surface": s, "surface_over_volume": round(r, 6) if v else None})
    print("  %-38s %14s %14s %7.3f"
          % ("ANY rule (the whole decided space)", "{:,}".format(V[4]),
             "{:,}".format(S[4]), S[4] / V[4]))

    print("\n  HOW TO READ THE RATIO")
    print("    It is the share of a rule's region that has a neighbour")
    print("    disagreeing with it - one step of 0.05 C or 0.05%% rear gain.")
    print("    Near 0: a fat region with a thin skin. The rule is robust here")
    print("            and a design inside it stays inside it.")
    print("    Near 1: almost every case is one step from a different answer.")
    print("            The sweep cannot resolve the rule at this resolution,")
    print("            and neither can a site that measures to one degree.")

    thin = [r for r in rows if r["surface_over_volume"] is not None
            and r["surface_over_volume"] > 0.5]
    if thin:
        print("\n  RULES THAT ARE MOSTLY SURFACE - these are not settled by the")
        print("  design, they are settled by the last digit of an input:")
        for r in thin:
            print("    %-38s %.3f   (%s)" % (r["rule"],
                                             r["surface_over_volume"],
                                             r["provenance"]))

    body = {"schema": "ggs.geometry/1", "cases": SIZE,
            "verdicts_computed": SIZE * 10,
            "excluded_formulations_parted": D,
            "rules": rows,
            "any_rule": {"volume": V[4], "surface": S[4],
                         "surface_over_volume": round(S[4] / V[4], 6)},
            "step_sizes": {"rear_gain_pct": 0.05, "assessment_temp_c": 0.05},
            "what_a_surface_is":
                "A case is on the surface when at least one of its eight "
                "neighbours - one step up or down each axis - carries a "
                "different verdict. The edge of the swept box is NOT counted "
                "as a surface: that is a boundary of the question, not of the "
                "rule.",
            "how_to_read":
                "The ratio is the share of a rule's region that is one step "
                "from a different answer. Near zero means a fat region with a "
                "thin skin and a robust rule. Near one means the verdict is "
                "settled by the last digit of an input rather than by the "
                "design, and no site instrument will resolve it.",
            "not_claimed":
                "A surface is a property of the RULE over the SWEPT SPACE at "
                "the chosen step size, not of any installation. Halve the step "
                "and the surface halves; that is geometry, not physics. And "
                "two of the four rules measured here rest on constants with no "
                "source, so their regions are shapes in a space nobody has "
                "shown to be the right space.",
            "anonymised": "No project, site, client, maker or model anywhere."}
    digest = hashlib.sha256(
        json.dumps(body, sort_keys=True).encode("utf-8")).hexdigest()
    body["body_sha256"] = digest
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    io.open(OUT, "w", encoding="utf-8", newline="\n").write(
        json.dumps(body, indent=1, sort_keys=True) + "\n")
    print("\n  body sha256 %s" % digest[:32])
    print("  wrote night-results/geometry.json")
    return 0


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

Harvest Crunch

A Python command-line tool in Worlds that reads worksheet, using SHA-256. It builds h1 (`build_h1`), builds h2 (`build_h2`) and builds h3 (`build_h3`).

ingestworlds- / src/harvest_crunch.py · lines 1–391 of 1207 · Entry point · pattern run_one (shared by 2 files)

What it does
It loads worksheet. Defines 37 functions or classes, including refuse, module_bins, g, dot_budget, h1_values. Uses libraries argparse, hashlib, inspect, io, json. 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 harvest-crunch.json; GeoJSON file worksheet.geojson; 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
This repository is public and an absolute path names a machine and an account. It accepts `--list`, `--run` and `--ci`.
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, hashlib, inspect, io, json, math, os, re
Used by
none found
Produces
refuse, module_bins, dot_budget, h1_values, build_h1, build_h2, build_h3, build_h4, translate, to_c, build_translated, read_worksheets
Defines here
refuse, module_bins, g, dot_budget, h1_values, build_h1, ref, make, report, build_h2, ref, make, crossings, mispair
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/harvest_crunch.py:1-391 · blob 766998f04d73bf91119011cf254be9d6071f3645 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""
PATHS ARE NOT WRITTEN DOWN HERE. This repository is public and an
absolute path names a machine and an account. Set GRID_DATA (and where
needed GRID_REPOS or CLAUDE_TRANSCRIPT) in the environment instead.
See src/paths.py for why.
THE TRANSLATOR: turn a worksheet's plain-English maths into enumeration.

Everything else in this night finds problems. This file does one job: it takes
a finding's `maths` string - a statement of axes and a predicate, written for a
person - and makes the card actually count it. A sentence is not a result. A
count over the whole space is.

RUN IT WITH THE GPU INTERPRETER, NOT THE DEFAULT ONE
CuPy lives in one place on this machine and it is not on PATH:

    $GRID_PY src/harvest_crunch.py --list
    $GRID_PY src/harvest_crunch.py --run
    $GRID_PY src/harvest_crunch.py --run --ci

`python` alone will import numpy and print the space; it cannot enumerate.

THE HOUSE RULE, AND IT IS NOT NEGOTIABLE
Nothing is reported for arithmetic that cannot check itself. Every registered
finding carries TWO implementations of the same sum: a kernel compiled for the
card, and a reference written in NumPy on the processor. The runner probes them
against each other on a stride through the space before it enumerates anything.
If they differ by one case the finding is reported FAILING and its counts are
withheld. A number nobody checked is worse than no number, because it gets
quoted.

THE SHAPE OF THE FILE
  1. REGISTRY - a declarative table. Each crunchable finding id maps to a
     builder that returns its axes, its card kernel, and its processor
     reference. Adding a finding means adding a row, not editing the runner.
  2. RUNNER   - one loop. Probe, verify, refuse or enumerate in batches,
     reduce with a bincount, write the counts down.
  3. WORKSHEETS - the ten sprinters write features into the harvest
     Each feature's `maths` is parsed into axes and a predicate and registered
     automatically. Anything that cannot be translated is REFUSED BY NAME with
     the reason. Never skipped silently: a silent skip is how a finding
     disappears and everybody assumes somebody else counted it.

WHERE THE NUMBERS COME FROM
  MODULES.json      the feed's MODULES.json - every module electrical
                    number. Nothing here is remembered; if the file is missing
                    the findings that need it are refused, not guessed.
  the cartridge     the dot floors and the dot budget are read from the live
                    renderer source, not retyped here from memory.
  the worksheets    every number in an auto-translated finding comes out of
                    the worksheet file that stated it.

DETERMINISM
night-results/harvest-crunch.json is written with sorted keys and no clock in
the body. Re-running on the same inputs gives byte-identical output except for
the single `timing` block, which is quarantined at the top level for exactly
that reason and excluded from the body digest the file prints for itself.

NO NAMES
No project, site, client or manufacturer name appears anywhere in this file or
in what it writes.
"""
import argparse
import hashlib
import inspect
import io
import json
import math
import os
import re
import sys
import time

import numpy as np

import paths

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
OUT = os.path.join(ROOT, "night-results", "harvest-crunch.json")

# 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
HARVEST_DIR = paths.HARVEST
# ROUND TWO writes to its own directory, so a re-run of round one cannot
# collide with it and neither sheet has to be moved to be read.
HARVEST_DIRS = [HARVEST_DIR, paths.HARVEST2]
NIGHT_WORKSHEET = os.path.join(ROOT, "night-results", "worksheet.geojson")
CARTRIDGE_DIR = os.environ.get("GRID_REPOS", "")

BNPI_REAR = 0.135          # rear 135 W/m2 over front 1000, printed on the sheet
V_CEIL = 1500.0            # equipment rating: module max system, inverter max PV
STRING_INPUT_A = 20.0      # per-string input at the combiner
MPPT_INPUT_A = 40.0        # one machine's operating limit per MPPT
STRINGS_PER_MPPT = 2
SIZING = 1.25              # 62548-1 continuous-current factor

PROBE_N = 200_000          # cases checked card-against-processor before counting
PROBE_STRIDE = 1_000_003   # coprime with the space, so the probe walks all of it
BATCH = 1 << 23

REFUSED = []               # (name, reason) - printed and written, never dropped


def refuse(name, reason):
    REFUSED.append({"name": str(name), "reason": str(reason)})


# ---------------------------------------------------------------------------
# THE INPUTS, EACH READ FROM ITS FILE
# ---------------------------------------------------------------------------

def module_bins():
    """Every module class, with the bifaciality factor DERIVED from the sheet's
    own K_Corr at the printed BNPI condition - not assumed, and not the printed
    bifaciality percentage, which is a different quantity."""
    if not os.path.isfile(MODULES):
        return []
    try:
        d = json.load(io.open(MODULES, encoding="utf-8"))
    except Exception as e:                                  # malformed, not absent
        refuse(MODULES, "unreadable: %s" % e)
        return []
    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
        vals = [g(k) for k in ("voc", "isc", "imp", "beta_pct_per_K",
                               "alpha", "k_corr")]
        if any(v is None for v in vals):
            continue
        voc, isc, imp, beta, alpha, kc = [float(v) for v in vals]
        out.append({"id": str(g("class_id")), "voc": voc, "isc": isc,
                    "imp": imp, "beta": beta, "alpha": alpha,
                    "phi": (kc - 1.0) / BNPI_REAR})
    out.sort(key=lambda b: b["id"])          # deterministic order, always
    return out


BINS = module_bins()


def dot_budget():
    """SLD_MAX and the symbol floors, READ OUT OF THE LIVE RENDERER. They are
    not retyped here, because a constant retyped from memory is a constant that
    silently stops matching the thing it describes."""
    d = {"src": None, "max": None, "ring": None, "line": None,
         "plain_ring": None, "plain_line": None}
    if not os.path.isdir(CARTRIDGE_DIR):
        return d
    files = sorted(f for f in os.listdir(CARTRIDGE_DIR)
                   if f.endswith("kuiper-programs.js"))
    if not files:
        return d
    p = os.path.join(CARTRIDGE_DIR, files[-1])
    try:
        s = io.open(p, encoding="utf-8", errors="replace").read()
    except Exception as e:
        refuse(p, "unreadable: %s" % e)
        return d
    m = re.search(r"SLD_MAX\s*=\s*(\d+)", s)
    if m:
        d["max"] = int(m.group(1))
    # the floor line in sldLayout: symbols get (ring ? 16 : 6), the rest
    # (ring ? 5 : 2), and the rounding loop may not take a symbol below it.
    f = re.search(r"SYMBOL\(p\.tag\)\s*\?\s*\(p\.kind\s*===\s*'ring'\s*\?\s*"
                  r"(\d+)\s*:\s*(\d+)\)\s*:\s*\(p\.kind\s*===\s*'ring'\s*\?\s*"
                  r"(\d+)\s*:\s*(\d+)\)", s)
    if f:
        d["ring"], d["line"] = int(f.group(1)), int(f.group(2))
        d["plain_ring"], d["plain_line"] = int(f.group(3)), int(f.group(4))
    d["src"] = files[-1]
    return d


DOTS = dot_budget()


# ---------------------------------------------------------------------------
# H1  THE VERDICT PREDICATE
# ---------------------------------------------------------------------------

H1_LIMITS = [("the 1500 V equipment rating", V_CEIL),
             ("the 20 A string input", STRING_INPUT_A),
             ("the 40 A machine input", MPPT_INPUT_A),
             ("the 35 A maximum series fuse", 35.0)]
H1_SWEEP, H1_BITS = 1_000_000, 1_000_000


def h1_values():
    """A million ordinary values through and past every limit, a million raw
    bit patterns - a value does not have to be typeable to arrive, it can be
    computed - and every special: NaN, both infinities, -0, denormals, each
    limit and its two neighbouring doubles. The boundary and the non-finites
    are the ONLY places the two predicates can differ, so they are not
    decoration, they are the experiment."""
    v = [float("nan"), float("inf"), float("-inf"), 0.0, -0.0,
         5e-324, -5e-324, 1.7976931348623157e308, -1.7976931348623157e308]
    for _lab, L in H1_LIMITS:
        v += [L, np.nextafter(L, np.inf), np.nextafter(L, -np.inf),
              -L, L * 2.0, L / 2.0]
    special = np.array(v, dtype=np.float64)
    sweep = np.linspace(-100.0, 1700.0, H1_SWEEP, dtype=np.float64)
    rng = np.random.default_rng(20260921)          # fixed seed: same bytes twice
    bits = rng.integers(0, 1 << 63, size=H1_BITS, dtype=np.uint64)
    bits[: H1_BITS // 4] |= np.uint64(0x7FF0000000000000)   # into NaN/Inf land
    return np.concatenate([sweep, bits.view(np.float64), special]), len(special)


H1_SRC = """
long long r = idx;
int vi = (int)(r % @NV@); r /= @NV@;
int li = (int)r;
double x = vals[vi], L = lims[li];

/* THE TWO PREDICATES, on the same bits, in the same thread. */
int old_over = (x > L) ? 1 : 0;              /* what the live program does   */
int new_over = !(x <= L) ? 1 : 0;            /* the proposed replacement     */
int finite   = isfinite(x) ? 1 : 0;

int cat = (old_over == new_over) ? 0 : (finite ? 1 : 2);
/* THE DEFECT IS A DISAGREEMENT, NOT MERELY A NON-FINITE PASS. Minus infinity
   is not finite but it IS genuinely below every limit, and both forms agree it
   is inside. Counting it overstated this gate by exactly one value per limit,
   and a gate that exaggerates is a gate nobody believes twice. */
int oldpass = (!finite && old_over == 0 && new_over == 1) ? 1 : 0;
code = (long long)(cat * 2 + oldpass);
"""


def build_h1():
    vals, n_special = h1_values()
    nv = len(vals)
    size = nv * len(H1_LIMITS)
    lims = np.array([L for _lab, L in H1_LIMITS], dtype=np.float64)

    def ref(idx):
        vi = (idx % nv).astype(np.int64)
        li = (idx // nv).astype(np.int64)
        with np.errstate(invalid="ignore"):
            x, L = vals[vi], lims[li]
            old = (x > L)
            new = ~(x <= L)
        fin = np.isfinite(x)
        cat = np.where(old == new, 0, np.where(fin, 1, 2))
        oldpass = (~fin) & (~old) & new
        return (cat * 2 + oldpass.astype(np.int64)).astype(np.int64)

    def make(cp):
        k = cp.ElementwiseKernel(
            "int64 idx, raw float64 vals, raw float64 lims", "int64 code",
            H1_SRC.replace("@NV@", str(nv)), "harvest_h1")
        dv, dl = cp.asarray(vals), cp.asarray(lims)
        return lambda d: k(d, dv, dl)

    def report(c):
        agree = c[0] + c[1]
        fin = c[2] + c[3]
        nonfin = c[4] + c[5]
        oldpass = c[1] + c[3] + c[5]
        return ({"agree": int(agree),
                 "disagree_on_a_finite_number": int(fin),
                 "disagree_on_a_non_finite_number": int(nonfin),
                 "old_predicate_calls_it_inside_the_rating": int(oldpass),
                 "values_per_limit": nv, "limits": len(H1_LIMITS),
                 "specials_per_limit": n_special},
                "SETTLED: on every finite number the two forms agree exactly "
                "(%s disagreements), so this changes no real design; they part "
                "only where the value is not a number, and there the live form "
                "reports %s passes it cannot justify across %d limits."
                % ("{:,}".format(int(fin)), "{:,}".format(int(oldpass)),
                   len(H1_LIMITS)),
                int(oldpass) == 0)

    return {"id": "H1",
            "question": "Does a verdict ever report a value it cannot justify "
                        "as inside a rating?",
            "maths": "sweep value over 1,000,000 ordinary x 1,000,000 raw bit "
                     "patterns x %d specials, x 4 limits, count where "
                     "(x > limit) differs from !(x <= limit)" % n_special,
            "axes": [("value", nv, "ordinary sweep -100..1700, raw bit "
                                   "patterns, and every special"),
                     ("limit", len(H1_LIMITS),
                      ", ".join(lab for lab, _ in H1_LIMITS))],
            "size": size, "n_codes": 6, "make": make, "ref": ref,
            "report": report, "source": "seeded",
            "not_claimed": "This settles a comparison, not a design. It says "
                           "nothing about whether the limits themselves are "
                           "right and nothing about any physics."}


# ---------------------------------------------------------------------------
# H2  THE TEMPERATURE COEFFICIENT
# ---------------------------------------------------------------------------
# An earlier draft took one family's beta and used it against another family's
# Voc. Both numbers were real; the pairing was not. So the sweep carries TWO
# answers per case: one with the beta swept across the whole plausible band,
# and one with the beta the sheet actually prints for THAT bin. Where they
# disagree is exactly the size of the mistake.

H2_BETA_LO, H2_BETA_HI, H2_N_BETA = -0.30, -0.20, 101
H2_SER_LO, H2_SER_HI = 20, 34
H2_T_LO, H2_T_HI, H2_N_T = -20.0, 0.0, 81

H2_SRC = """
long long r = idx;
int bi = (int)(r % @NB@); r /= @NB@;
int ei = (int)(r % @NE@); r /= @NE@;
int si = (int)(r % @NS@); r /= @NS@;
int ti = (int)r;

double beta_sweep = @BLO@ + (@BHI@ - @BLO@) * (double)ei / (@NE@ - 1.0);
double T          = @TLO@ + (@THI@ - @TLO@) * (double)ti / (@NT@ - 1.0);
double se         = (double)(@SLO@ + si);
double vo         = voc[bi];

/* Voc rises as it gets colder; beta is negative and T is below 25. */
double v_sweep = se * vo * (1.0 + beta_sweep / 100.0 * (T - 25.0));
double v_own   = se * vo * (1.0 + beta[bi]  / 100.0 * (T - 25.0));

long long m = 0;
if (v_sweep > @VC@) m |= 1;      /* with the swept coefficient            */
if (v_own   > @VC@) m |= 2;      /* with the coefficient THIS bin prints  */
code = m;
"""


def build_h2():
    if not BINS:
        return None
    nb, ne = len(BINS), H2_N_BETA
    ns = H2_SER_HI - H2_SER_LO + 1
    nt = H2_N_T
    size = nb * ne * ns * nt
    voc = np.array([b["voc"] for b in BINS])
    beta = np.array([b["beta"] for b in BINS])

    def ref(idx):
        r = idx.astype(np.int64)
        bi = r % nb; r //= nb
        ei = r % ne; r //= ne
        si = r % ns; r //= ns
        ti = r
        bs = H2_BETA_LO + (H2_BETA_HI - H2_BETA_LO) * ei / (ne - 1.0)
        T = H2_T_LO + (H2_T_HI - H2_T_LO) * ti / (nt - 1.0)
        se = (H2_SER_LO + si).astype(np.float64)
        vo = voc[bi]
        v_sweep = se * vo * (1.0 + bs / 100.0 * (T - 25.0))
        v_own = se * vo * (1.0 + beta[bi] / 100.0 * (T - 25.0))
        return ((v_sweep > V_CEIL).astype(np.int64)
                + 2 * (v_own > V_CEIL).astype(np.int64))

    def make(cp):
        src = (H2_SRC.replace("@NB@", str(nb)).replace("@NE@", str(ne))
               .replace("@NS@", str(ns)).replace("@NT@", str(nt))
               .replace("@BLO@", repr(H2_BETA_LO)).replace("@BHI@", repr(H2_BETA_HI))
               .replace("@TLO@", repr(H2_T_LO)).replace("@THI@", repr(H2_T_HI))
               .replace("@SLO@", str(H2_SER_LO)).replace("@VC@", repr(V_CEIL)))
        k = cp.ElementwiseKernel(
            "int64 idx, raw float64 voc, raw float64 beta", "int64 code",
            src, "harvest_h2")
        dv, db = cp.asarray(voc), cp.asarray(beta)
        return lambda d: k(d, dv, db)

    def crossings():
        """The EXACT temperature at which each bin crosses 1500 V, solved
        rather than searched: 1500 = N*Voc*(1+beta/100*(T-25)) inverts."""
        rows = {}
        for b in BINS:
            per = {}
            for n in range(H2_SER_LO, H2_SER_HI + 1):
                v25 = n * b["voc"]
                if v25 > V_CEIL:
                    per[str(n)] = "over the rating at 25 C already"
                    continue
                t = 25.0 + (V_CEIL / v25 - 1.0) * 100.0 / b["beta"]
                per[str(n)] = round(t, 3)
            rows[b["id"]] = per
        return rows

    def mispair():
        """What using one family's beta against another family's Voc costs, in
        volts, at thirty in series - computed here, never recalled."""
        fams = {}
        for b in BINS:
            fams.setdefault(b["id"][0], set()).add(b["beta"])
        betas = sorted({b["beta"] for b in BINS})