GLOBALGRID2050 / EXPLORE CODE

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

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`).

700 lines of Python from worlds-, in 1 file. Topic: Websites and apps. Section 2031 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. Harvest Crunch ingest · worlds- / src/harvest_crunch.py lines 392–1091

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 392–1091 of 1207 (continued from section 2030) · 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
report, build_h3, ref, make, thresholds, report, build_h4, ref, make, sheet_row, report, translate, to_c, build_translated, _vectorise, ref, make, report, read_worksheets, registry, run_one, describe
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:392-1091 · 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
        rows = {}
        if len(betas) < 2:
            return rows
        for b in BINS:
            for wrong in betas:
                if wrong == b["beta"]:
                    continue
                per = {}
                for T in (0.0, -5.0, -10.0, -10.6, -15.0, -20.0):
                    d = 30 * b["voc"] * ((b["beta"] - wrong) / 100.0) * (T - 25.0)
                    per["%.1f C" % T] = round(d, 3)
                rows["%s with %+.2f in place of %+.2f" % (b["id"], wrong,
                                                          b["beta"])] = per
        return rows

    def report(c):
        sweep_over = c[1] + c[3]
        own_over = c[2] + c[3]
        differ = c[1] + c[2]
        return ({"over_1500_with_the_swept_coefficient": int(sweep_over),
                 "over_1500_with_each_bin_s_own_coefficient": int(own_over),
                 "cases_where_the_two_coefficients_disagree": int(differ),
                 "clear_on_both": int(c[0]),
                 "exact_crossing_temperature_C": crossings(),
                 "cost_of_pairing_the_wrong_coefficient_v_at_30_series":
                     mispair(),
                 "coefficients_read_from_the_file":
                     {b["id"]: b["beta"] for b in BINS}},
                "SETTLED: %s of %s cases cross 1500 V on each bin's own printed "
                "coefficient, and the exact crossing temperature is solved for "
                "every bin and series count; %s cases turn on WHICH "
                "coefficient is used, which is the whole of the earlier "
                "mistake."
                % ("{:,}".format(int(own_over)), "{:,}".format(size),
                   "{:,}".format(int(differ))),
                int(own_over) == 0)

    return {"id": "H2",
            "question": "Where does the series string cross the 1500 V rating, "
                        "and how much of the answer depends on which "
                        "temperature coefficient is paired with which Voc?",
            "maths": "sweep beta %.2f..%.2f x series %d..%d x temperature "
                     "%.0f..%.0f C x %d module bins, count where "
                     "N*Voc*(1+beta/100*(T-25)) > 1500"
                     % (H2_BETA_LO, H2_BETA_HI, H2_SER_LO, H2_SER_HI,
                        H2_T_LO, H2_T_HI, nb),
            "axes": [("module bin", nb, "every class in the file, Voc and beta "
                                        "taken together per bin"),
                     ("beta swept", ne, "%.2f..%.2f %%/K" % (H2_BETA_LO,
                                                             H2_BETA_HI)),
                     ("modules in series", ns, "%d..%d" % (H2_SER_LO,
                                                           H2_SER_HI)),
                     ("assessment temperature", nt,
                      "%.0f..%.0f C" % (H2_T_LO, H2_T_HI))],
            "size": size, "n_codes": 4, "make": make, "ref": ref,
            "report": report, "source": "seeded",
            "not_claimed": "This settles where a printed Voc and a printed "
                           "coefficient put the string voltage. It does not "
                           "settle the site's design minimum temperature, "
                           "which is a meteorological input this file does not "
                           "hold, and it does not model the rise of Voc with "
                           "irradiance, which makes the real answer worse "
                           "rather than better."}


# ---------------------------------------------------------------------------
# H3  THE DOT BUDGET
# ---------------------------------------------------------------------------
# A symbol is not a length. The renderer hands every SYMBOL piece a floor of
# dots so it reads as the thing it is, and the rounding loop may not take a
# symbol below that floor. Floors do not negotiate: if the floors alone add up
# past the budget, the loop runs out and a piece of the drawing is handed
# nothing at all. That is a drawing with a missing part, and the only way to
# see it is to count the shapes, not to look at one of them.

H3_P_MAX = 384              # pieces in a drawing
H3_S_MAX = 96               # of which symbols
H3_R_MAX = 96               # of which rings

H3_SRC = """
long long r = idx;
int pi = (int)(r % @NP@); r /= @NP@;
int si = (int)(r % @NS@); r /= @NS@;
int ri = (int)(r % @NR@); r /= @NR@;
int ni = (int)r;

int P = pi + 1;      /* pieces in the drawing                */
int S = si;          /* how many of them are symbols         */
int SR = ri;         /* how many symbols are rings           */
int NR = ni;         /* how many plain pieces are rings      */

if (S > P || SR > S || NR > P - S) { code = 0; }   /* not a shape at all */
else {
  long long floors = (long long)SR * @FR@ + (long long)(S - SR) * @FL@
                   + (long long)NR * @PR@ + (long long)(P - S - NR) * @PL@;
  code = (floors > @MAX@) ? 2 : 1;
}
"""


def build_h3():
    if None in (DOTS["max"], DOTS["ring"], DOTS["line"],
                DOTS["plain_ring"], DOTS["plain_line"]):
        return None
    np_, ns, nr, nn = H3_P_MAX, H3_S_MAX + 1, H3_R_MAX + 1, H3_R_MAX + 1
    size = np_ * ns * nr * nn
    FR, FL = DOTS["ring"], DOTS["line"]
    PR, PL, MX = DOTS["plain_ring"], DOTS["plain_line"], DOTS["max"]

    def ref(idx):
        r = idx.astype(np.int64)
        pi = r % np_; r //= np_
        si = r % ns; r //= ns
        ri = r % nr; r //= nr
        ni = r
        P, S, SR, NR = pi + 1, si, ri, ni
        bad = (S > P) | (SR > S) | (NR > P - S)
        floors = SR * FR + (S - SR) * FL + NR * PR + (P - S - NR) * PL
        return np.where(bad, 0, np.where(floors > MX, 2, 1)).astype(np.int64)

    def make(cp):
        src = (H3_SRC.replace("@NP@", str(np_)).replace("@NS@", str(ns))
               .replace("@NR@", str(nr)).replace("@FR@", str(FR))
               .replace("@FL@", str(FL)).replace("@PR@", str(PR))
               .replace("@PL@", str(PL)).replace("@MAX@", str(MX)))
        k = cp.ElementwiseKernel("int64 idx", "int64 code", src, "harvest_h3")
        return lambda d: k(d)

    def thresholds():
        """The smallest shape of each kind that starves a piece - solved, so it
        can be read straight off and checked by hand."""
        return {"symbol rings alone": int(MX // FR) + 1,
                "symbol lines alone": int(MX // FL) + 1,
                "plain rings alone": int(MX // PR) + 1,
                "plain lines alone": int(MX // PL) + 1,
                "note": "the count at which the floors first exceed the "
                        "budget, so the rounding loop cannot give every piece "
                        "its floor and a piece receives zero dots"}

    def report(c):
        shapes = c[1] + c[2]
        return ({"budget": MX, "floor_symbol_ring": FR, "floor_symbol_line": FL,
                 "floor_plain_ring": PR, "floor_plain_line": PL,
                 "floors_read_from": DOTS["src"],
                 "shapes_examined": int(shapes),
                 "shapes_that_fit": int(c[1]),
                 "shapes_where_the_floors_alone_exceed_the_budget": int(c[2]),
                 "combinations_that_are_not_shapes": int(c[0]),
                 "smallest_starving_count": thresholds()},
                "SETTLED: of %s real shapes, %s leave the floors alone over the "
                "%d dot budget, so a piece of the drawing is handed zero dots; "
                "%d symbol rings on their own are enough to do it."
                % ("{:,}".format(int(shapes)), "{:,}".format(int(c[2])), MX,
                   int(MX // FR) + 1),
                int(c[2]) == 0)

    return {"id": "H3",
            "question": "Can a drawing ask for more floor dots than the budget "
                        "holds, so that a piece of it is drawn with nothing?",
            "maths": "sweep pieces 1..%d x symbols 0..%d x symbol rings 0..%d "
                     "x plain rings 0..%d, count where "
                     "SR*%d + (S-SR)*%d + NR*%d + (P-S-NR)*%d > %d"
                     % (H3_P_MAX, H3_S_MAX, H3_R_MAX, H3_R_MAX,
                        FR, FL, PR, PL, MX),
            "axes": [("pieces", np_, "1..%d" % H3_P_MAX),
                     ("symbol pieces", ns, "0..%d, matched by a PREFIX test on "
                                           "the tag" % H3_S_MAX),
                     ("symbol rings", nr, "0..%d of the symbols" % H3_R_MAX),
                     ("plain rings", nn, "0..%d of the rest" % H3_R_MAX)],
            "size": size, "n_codes": 3, "make": make, "ref": ref,
            "report": report, "source": "seeded",
            "not_claimed": "This settles the arithmetic of the floors against "
                           "the budget. It does not say which real drawings "
                           "reach those shapes, and it does not check that a "
                           "piece given its floor is legible - only that it is "
                           "given something."}


# ---------------------------------------------------------------------------
# H4  THE BIFACIAL CURRENT CHAIN
# ---------------------------------------------------------------------------
# Rear irradiance raises string current, and that current eats the string input
# and the machine input at the same time. The bifaciality factor is DERIVED
# from each bin's own K_Corr at the printed BNPI condition - front 1000, rear
# 135 W/m2 - never assumed, and never the printed bifaciality percentage, which
# is a different quantity measured a different way.

H4_REAR_LO, H4_REAR_HI, H4_N_REAR = 0.0, 0.30, 61
H4_T_LO, H4_T_HI, H4_N_T = -20.0, 25.0, 91
H4_SER_LO, H4_SER_HI = 20, 34
H4_TABLE_TOP = 0.25        # the highest rear gain the sheet itself publishes

H4_SRC = """
long long r = idx;
int bi = (int)(r % @NB@); r /= @NB@;
int ri = (int)(r % @NR@); r /= @NR@;
int ti = (int)(r % @NT@); r /= @NT@;
int si = (int)r;

double rear = @RLO@ + (@RHI@ - @RLO@) * (double)ri / (@NR@ - 1.0);
double T    = @TLO@ + (@THI@ - @TLO@) * (double)ti / (@NT@ - 1.0);
double se   = (double)(@SLO@ + si);

double kb = 1.0 + phi[bi] * rear;                    /* rear-side current gain */
double kt = 1.0 + alpha[bi] / 100.0 * (T - 25.0);    /* cold trims it back     */
double imp_e = imp[bi] * kb * kt;
double isc_e = isc[bi] * kb * kt;
double v_str = se * voc[bi] * (1.0 + beta[bi] / 100.0 * (T - 25.0));

long long m = 0;
if (imp_e > @SIA@) m |= 1;                           /* the string input   */
if (@SZ@ * isc_e * @SPM@.0 > @MIA@) m |= 2;          /* the machine input  */
if (v_str > @VC@) m |= 4;                            /* the voltage rating */
code = m;
"""


def build_h4():
    if not BINS:
        return None
    nb, nr, nt = len(BINS), H4_N_REAR, H4_N_T
    ns = H4_SER_HI - H4_SER_LO + 1
    size = nb * nr * nt * ns
    cols = {k: np.array([b[k] for b in BINS])
            for k in ("voc", "isc", "imp", "beta", "alpha", "phi")}

    def ref(idx):
        r = idx.astype(np.int64)
        bi = r % nb; r //= nb
        ri = r % nr; r //= nr
        ti = r % nt; r //= nt
        si = r
        rear = H4_REAR_LO + (H4_REAR_HI - H4_REAR_LO) * ri / (nr - 1.0)
        T = H4_T_LO + (H4_T_HI - H4_T_LO) * ti / (nt - 1.0)
        se = (H4_SER_LO + si).astype(np.float64)
        kb = 1.0 + cols["phi"][bi] * rear
        kt = 1.0 + cols["alpha"][bi] / 100.0 * (T - 25.0)
        imp_e = cols["imp"][bi] * kb * kt
        isc_e = cols["isc"][bi] * kb * kt
        v_str = se * cols["voc"][bi] * (1.0 + cols["beta"][bi] / 100.0 * (T - 25.0))
        return ((imp_e > STRING_INPUT_A).astype(np.int64)
                + 2 * (SIZING * isc_e * STRINGS_PER_MPPT > MPPT_INPUT_A).astype(np.int64)
                + 4 * (v_str > V_CEIL).astype(np.int64)).astype(np.int64)

    def make(cp):
        src = (H4_SRC.replace("@NB@", str(nb)).replace("@NR@", str(nr))
               .replace("@NT@", str(nt)).replace("@RLO@", repr(H4_REAR_LO))
               .replace("@RHI@", repr(H4_REAR_HI)).replace("@TLO@", repr(H4_T_LO))
               .replace("@THI@", repr(H4_T_HI)).replace("@SLO@", str(H4_SER_LO))
               .replace("@SIA@", repr(STRING_INPUT_A))
               .replace("@SZ@", repr(SIZING)).replace("@SPM@", str(STRINGS_PER_MPPT))
               .replace("@MIA@", repr(MPPT_INPUT_A)).replace("@VC@", repr(V_CEIL)))
        k = cp.ElementwiseKernel(
            "int64 idx, raw float64 voc, raw float64 isc, raw float64 imp, "
            "raw float64 beta, raw float64 alpha, raw float64 phi",
            "int64 code", src, "harvest_h4")
        d = [cp.asarray(cols[n]) for n in
             ("voc", "isc", "imp", "beta", "alpha", "phi")]
        return lambda q: k(q, *d)

    def sheet_row():
        """The sheet's own top published rear-gain row, at the condition the
        sheet states it for: 25 C. Nothing swept, nothing extrapolated."""
        rows = {}
        for b in BINS:
            kb = 1.0 + b["phi"] * H4_TABLE_TOP
            imp_e, isc_e = b["imp"] * kb, b["isc"] * kb
            rows[b["id"]] = {
                "phi_derived": round(b["phi"], 4),
                "string_current_a": round(imp_e, 3),
                "over_the_%.0f_a_string_input" % STRING_INPUT_A:
                    bool(imp_e > STRING_INPUT_A),
                "sized_machine_current_a": round(SIZING * isc_e * STRINGS_PER_MPPT, 3),
                "over_the_%.0f_a_machine_input" % MPPT_INPUT_A:
                    bool(SIZING * isc_e * STRINGS_PER_MPPT > MPPT_INPUT_A)}
        return rows

    def report(c):
        s = sum(c[m] for m in range(8) if m & 1)
        mm = sum(c[m] for m in range(8) if m & 2)
        vv = sum(c[m] for m in range(8) if m & 4)
        both = sum(c[m] for m in range(8) if (m & 1) and (m & 2))
        row = sheet_row()
        all_bins = all(v["over_the_%.0f_a_string_input" % STRING_INPUT_A]
                       and v["over_the_%.0f_a_machine_input" % MPPT_INPUT_A]
                       for v in row.values())
        return ({"over_the_string_input": int(s),
                 "over_the_machine_input": int(mm),
                 "over_the_voltage_rating": int(vv),
                 "over_both_current_inputs": int(both),
                 "clears_everything": int(c[0]),
                 "phi_source": "(K_Corr - 1) / %.3f, both printed on the sheet"
                               % BNPI_REAR,
                 "at_the_sheets_own_top_rear_row": {
                     "rear_gain": H4_TABLE_TOP,
                     "condition": "25 C, the condition the row is printed for",
                     "every_bin_over_both_inputs": bool(all_bins),
                     "per_bin": row}},
                "SETTLED: %s of %s cases exceed the %.0f A string input and %s "
                "the %.0f A machine input; at the sheet's own %.0f%% rear row "
                "%s bin exceeds both."
                % ("{:,}".format(int(s)), "{:,}".format(size), STRING_INPUT_A,
                   "{:,}".format(int(mm)), MPPT_INPUT_A, H4_TABLE_TOP * 100,
                   "EVERY" if all_bins else "not every"),
                int(s) == 0 and int(mm) == 0)

    return {"id": "H4",
            "question": "Where does rear-side irradiance take the string "
                        "current past the string and machine inputs?",
            "maths": "sweep rear gain %.0f..%.0f%% x temperature %.0f..%.0f C "
                     "x series %d..%d x %d bins, count where "
                     "Imp*(1+phi*rear)*(1+alpha/100*(T-25)) > %.0f or "
                     "%.2f*Isc*(1+phi*rear)*(1+alpha/100*(T-25))*%d > %.0f"
                     % (H4_REAR_LO * 100, H4_REAR_HI * 100, H4_T_LO, H4_T_HI,
                        H4_SER_LO, H4_SER_HI, nb, STRING_INPUT_A, SIZING,
                        STRINGS_PER_MPPT, MPPT_INPUT_A),
            "axes": [("module bin", nb, "every class in the file"),
                     ("rear gain", nr, "%.0f..%.0f%%, the sheet's table tops "
                                       "at %.0f%%" % (H4_REAR_LO * 100,
                                                      H4_REAR_HI * 100,
                                                      H4_TABLE_TOP * 100)),
                     ("assessment temperature", nt,
                      "%.0f..%.0f C" % (H4_T_LO, H4_T_HI)),
                     ("modules in series", ns, "%d..%d" % (H4_SER_LO,
                                                           H4_SER_HI))],
            "size": size, "n_codes": 8, "make": make, "ref": ref,
            "report": report, "source": "seeded",
            "not_claimed": "This settles current against two printed input "
                           "ratings. It does not model non-uniform rear "
                           "illumination along a string, the transient, or the "
                           "fact that high albedo and low ambient are the same "
                           "weather - which means the joint corner is present "
                           "in the count but its real likelihood is understated "
                           "by reading either axis on its own."}


# ---------------------------------------------------------------------------
# THE WORKSHEETS: turning a sentence into a cross-product
# ---------------------------------------------------------------------------
# A `maths` string is a promise that the finding is countable. This turns the
# promise into a kernel, or it refuses out loud. There is no third outcome.

AXIS_RE = re.compile(r"([A-Za-z_]\w*)\s*(-?\d+(?:\.\d+)?)\s*\.\.\s*"
                     r"(-?\d+(?:\.\d+)?)\s*(?:step\s*(\d+(?:\.\d+)?))?")
# the ten sprinters write in different hands; these are the introducers seen
PRED_RE = re.compile(r"(?:count(?:\s+\w+){0,3}\s+where|predicate\s*:)",
                     re.IGNORECASE)
# a word is not a quantity. 'sweep x 0..5' names no axis, it names a cross.
STOPWORDS = {"in", "x", "and", "or", "to", "from", "at", "of", "by", "step",
             "over", "the", "a", "an", "for", "with", "per", "is", "are",
             "sweep", "enumerate", "count", "each", "all", "every", "case",
             "cases", "where", "than", "into", "on", "up", "down"}
IDENT_RE = re.compile(r"[A-Za-z_]\w*")
FUNCS = {"abs": "fabs", "min": "fmin", "max": "fmax", "exp": "exp",
         "log": "log", "sqrt": "sqrt", "floor": "floor", "ceil": "ceil"}
SAFE_CHARS = set("0123456789.+-*/()<>=!& |_,ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                 "abcdefghijklmnopqrstuvwxyz")
FLOAT_SAMPLES = 101        # a swept real axis becomes this many samples
MAX_SPACE = 5_000_000_000  # past this, a person must narrow the sweep


def translate(fid, maths):
    """Return an axis list and a predicate, or raise ValueError with the reason
    a person needs to hear."""
    if not isinstance(maths, str) or not maths.strip():
        raise ValueError("no maths statement")
    m = PRED_RE.search(maths)
    if not m:
        raise ValueError("the maths states no countable predicate: no "
                         "'count ... where' and no 'predicate:'")
    left, pred = maths[:m.start()], maths[m.end():].strip()
    pred = pred.split(",")[0].split(";")[0].strip().rstrip(".")
    if not pred:
        raise ValueError("the predicate introducer is followed by nothing")
    axes = []
    for name, lo, hi, step in AXIS_RE.findall(left):
        if name.lower() in STOPWORDS:
            raise ValueError("'%s %s..%s' names no quantity - '%s' is a word, "
                             "so the axis cannot be built" % (name, lo, hi, name))
        integral = ("." not in lo) and ("." not in hi) and not step
        lo_f, hi_f = float(lo), float(hi)
        if hi_f < lo_f:
            raise ValueError("axis '%s' runs backwards (%s..%s)"
                             % (name, lo, hi))
        if integral:
            n = int(hi_f) - int(lo_f) + 1
            kind = "integer"
        elif step:
            n = int(round((hi_f - lo_f) / float(step))) + 1
            kind = "real"
        else:
            n, kind = FLOAT_SAMPLES, "real"
        if n > 1_000_000:
            raise ValueError("axis '%s' has %s steps; narrow it"
                             % (name, "{:,}".format(n)))
        if n < 2:
            raise ValueError("axis '%s' has fewer than two steps, so it is a "
                             "constant and not an axis" % name)
        axes.append({"name": name, "n": n, "lo": lo_f, "hi": hi_f, "kind": kind})
    if not axes:
        raise ValueError("no axis of the form 'name lo..hi' in the maths")
    names = [a["name"] for a in axes]
    if len(set(names)) != len(names):
        raise ValueError("two axes share a name")
    bad = [c for c in pred if c not in SAFE_CHARS]
    if bad:
        raise ValueError("the predicate holds characters this translator will "
                         "not compile: %s" % "".join(sorted(set(bad))))
    if "**" in pred:
        raise ValueError("the predicate uses '**'; write it out as a product")
    used = set(IDENT_RE.findall(pred))
    unknown = sorted(used - set(names) - set(FUNCS)
                     - {"and", "or", "not", "True", "False"})
    if unknown:
        raise ValueError("the predicate names %s, which is not an axis and not "
                         "a number from a file" % ", ".join(unknown))
    size = 1
    for a in axes:
        size *= a["n"]
    if size > MAX_SPACE:
        raise ValueError("the cross-product is %s cases; narrow the sweep"
                         % "{:,}".format(size))
    return axes, pred


def to_c(pred):
    s = " %s " % pred
    s = s.replace(" and ", " && ").replace(" or ", " || ")
    s = re.sub(r"\bnot\b", "!", s)
    s = s.replace("True", "1").replace("False", "0")
    for py, c in FUNCS.items():
        s = re.sub(r"\b%s\s*\(" % py, "%s(" % c, s)
    return s.strip()


def build_translated(fid, feature, where):
    axes, pred = translate(fid, feature.get("maths"))
    size = 1
    for a in axes:
        size *= a["n"]
    c_pred = to_c(pred)
    lines = ["long long r = idx;"]
    for i, a in enumerate(axes):
        lines.append("long long a%d = r %% %d; r /= %d;" % (i, a["n"], a["n"]))
    for i, a in enumerate(axes):
        if a["kind"] == "integer":
            lines.append("double %s = (double)(%d + a%d);"
                         % (a["name"], int(a["lo"]), i))
        else:
            lines.append("double %s = %.17g + (%.17g - %.17g) * (double)a%d "
                         "/ (%d - 1.0);"
                         % (a["name"], a["lo"], a["hi"], a["lo"], i, a["n"]))
    lines.append("code = (%s) ? 1 : 0;" % c_pred)
    src = "\n".join(lines)

    # THE REFERENCE RUNS ON THE CARD TOO, AND IT IS STILL A SECOND
    # IMPLEMENTATION. One side is a fused kernel NVRTC compiles from C; this
    # side is CuPy's array-operator graph over the same axes. Different
    # compilers, different execution paths, same arithmetic - which is what the
    # pair is for. Keeping it on the processor made the processor the throttle:
    # measured 0.4% mean card utilisation at 32 W while NumPy did the work.
    #
    # AND `and` DOES NOT VECTORISE. Python's and/or/not call __bool__ on the
    # whole array and raise "the truth value of an array is ambiguous". A
    # translated sentence that joined two comparisons with `and` crashed the
    # run. They are rewritten to the bitwise operators, which is what an array
    # predicate needs, with parentheses so precedence does not change meaning.
    def _vectorise(e):
        e = re.sub(r"not", "~", e)
        e = re.sub(r"and", "&", e)
        e = re.sub(r"or", "|", e)
        return e

    def ref(idx, xp=None):
        xp = xp if xp is not None else np
        r = idx.astype(xp.int64) if hasattr(idx, "astype") else xp.asarray(idx)
        # An EMPTY builtins map is too tight for the card. CuPy's ufunc
        # machinery reaches for __import__ while it names the kernel it is
        # about to compile, and an empty map raises KeyError there - the
        # sandbox strangled the very thing it was meant to let through.
        # __import__ alone is restored; nothing else is. The safety that
        # matters is upstream anyway: the predicate's names were checked
        # against the declared axes before it ever reached here, so it cannot
        # reference anything to import.
        env = {"__builtins__": {"__import__": __import__}}
        for f in FUNCS:
            env[f] = getattr(xp, {"abs": "fabs", "min": "minimum",
                                  "max": "maximum"}.get(f, f))
        for a in axes:
            q = r % a["n"]
            r = r // a["n"]
            if a["kind"] == "integer":
                env[a["name"]] = (int(a["lo"]) + q).astype(xp.float64)
            else:
                env[a["name"]] = (a["lo"] + (a["hi"] - a["lo"]) * q
                                  / (a["n"] - 1.0))
        v = eval(_vectorise(pred), env, {})   # axes only; names already checked
        return xp.asarray(v, dtype=bool).astype(xp.int64)

    def make(cp):
        k = cp.ElementwiseKernel("int64 idx", "int64 code", src,
                                 "harvest_%s" % re.sub(r"\W", "_", fid))
        return lambda d: k(d)

    def report(c):
        hit, tot = int(c[1]), int(c[0] + c[1])
        return ({"cases_where_the_predicate_holds": hit,
                 "cases_where_it_does_not": int(c[0]),
                 "predicate": pred, "worksheet": where},
                "SETTLED: the predicate holds in %s of %s cases (%.6f%% of the "
                "space stated in the worksheet)."
                % ("{:,}".format(hit), "{:,}".format(tot),
                   100.0 * hit / tot if tot else 0.0),
                hit == 0)

    return {"id": fid,
            "question": str(feature.get("what") or "")[:400],
            "maths": feature.get("maths"),
            "axes": [(a["name"], a["n"],
                      "%g..%g %s" % (a["lo"], a["hi"], a["kind"]))
                     for a in axes],
            "size": size, "n_codes": 2, "make": make, "ref": ref,
            "report": report, "source": where,
            "not_claimed": "This counts the predicate the worksheet wrote "
                           "down, over the axes the worksheet named. It does "
                           "not check that the predicate is the right question "
                           "or that the axes cover the real range - only a "
                           "person can settle that."}


def read_worksheets():
    """Every worksheet, by name. A missing file is refused by name. A malformed
    file is refused by name. A feature that cannot be translated is refused by
    its own id. Nothing is ever skipped quietly, because a quiet skip is how a
    finding vanishes while everybody assumes somebody else counted it."""
    sheet_files = []
    for d in HARVEST_DIRS:
        if os.path.isdir(d):
            sheet_files += [os.path.join(d, f) for f in sorted(os.listdir(d))
                      if f.lower().endswith(".geojson")]
        else:
            refuse(d, "the worksheet directory does not exist")
    sheet_files.append(NIGHT_WORKSHEET)

    built, seen, stats = [], set(), {"files": 0, "features": 0,
                                     "crunchable": 0, "translated": 0}
    for p in sheet_files:
        if not os.path.isfile(p):
            refuse(p, "no such file: the worksheet was not written")
            continue
        try:
            d = json.load(io.open(p, encoding="utf-8"))
        except Exception as e:
            refuse(p, "not readable as JSON: %s" % e)
            continue
        feats = d.get("features") if isinstance(d, dict) else None
        if not isinstance(feats, list):
            refuse(p, "no 'features' list: not a worksheet this can read")
            continue
        stats["files"] += 1
        base = os.path.basename(p)
        for n, f in enumerate(feats):
            props = f.get("properties") if isinstance(f, dict) else None
            if not isinstance(props, dict):
                refuse("%s#%d" % (base, n), "feature has no properties block")
                continue
            stats["features"] += 1
            fid = str(props.get("id") or props.get("what") or
                      "%s#%d" % (base, n))[:80]
            # A FEATURE IS JUDGED BY ITS SENTENCE, NOT BY A FLAG. Round one set
            # gpu_crunchable and wrote prose; round two dropped the flag and wrote a
            # sweep sentence. Gating on the flag meant 157 features were read and
            # none translated - the reader was asking the wrong question. If there is
            # a maths sentence, try it; if it does not parse it is refused BY NAME
            # below, which is the honest outcome either way.
            if not (props.get("gpu_crunchable") or props.get("maths")):
                continue
            stats["crunchable"] += 1
            if fid in seen:
                refuse(fid, "a second finding claims this id in %s" % base)
                continue
            try:
                spec = build_translated(fid, props, base)
            except ValueError as e:
                refuse(fid, "not translated (%s): %s" % (base, e))
                continue
            except Exception as e:                       # never let one poison the run
                refuse(fid, "not translated (%s): %s: %s"
                       % (base, type(e).__name__, e))
                continue
            seen.add(fid)
            stats["translated"] += 1
            built.append(spec)
    return built, stats


# ---------------------------------------------------------------------------
# THE REGISTRY
# ---------------------------------------------------------------------------

SEEDS = [("H1", build_h1), ("H2", build_h2), ("H3", build_h3),
         ("H4", build_h4)]


def registry():
    out = []
    for fid, fn in SEEDS:
        try:
            s = fn()
        except Exception as e:
            refuse(fid, "could not be built: %s: %s" % (type(e).__name__, e))
            continue
        if s is None:
            refuse(fid, "its inputs are not on this machine, so it is not "
                        "enumerated on remembered numbers")
            continue
        out.append(s)
    built, stats = read_worksheets()
    out += built
    return out, stats


# ---------------------------------------------------------------------------
# THE RUNNER
# ---------------------------------------------------------------------------

def run_one(cp, spec):
    """Probe, verify, then enumerate. A finding that fails its own check is
    reported FAILING with its counts WITHHELD - not reported quietly wrong."""
    size, t0 = spec["size"], time.perf_counter()
    fn = spec["make"](cp)

    stride = PROBE_STRIDE
    while math.gcd(stride, size) != 1:
        stride += 2
    probe = (np.arange(min(PROBE_N, size), dtype=np.int64) * stride) % size
    # TWO CHANNELS, AND THE SECOND ONE RUNS WHEREVER IT WAS WRITTEN TO RUN.
    # A translated sentence builds a reference that takes the array module, so
    # its channel opens on the card beside the kernel. The four seeded findings
    # carry hand-written references that were written against the processor and
    # take the index array alone. Asking every reference for two arguments broke
    # those four - so the signature is inspected rather than assumed, and each
    # is given what it was built for. Both are still a SECOND implementation,
    # which is the only property the pair rule actually needs.
    dprobe = cp.asarray(probe)
    got = fn(dprobe)
    ref = spec["ref"]
    try:
        nargs = len(inspect.signature(ref).parameters)
    except (TypeError, ValueError):
        nargs = 1
    if nargs >= 2:
        want = ref(dprobe, cp)                      # the positron, on the card
        differ = int((got != want).sum())
    else:
        want = ref(probe)                           # a seeded reference, host
        differ = int((cp.asnumpy(got) != want).sum())
    if differ:
        return {"cases": 0, "checked": int(len(probe)), "verified_differ": differ,
                "state": "FAILING",
                "settled": "NOT SETTLED: the card and the processor disagree on "
                           "%d of %d probed cases. Nothing is reported for "
                           "arithmetic that cannot check itself."
                           % (differ, len(probe))}, 0.0

    counts = cp.zeros(spec["n_codes"], dtype=cp.int64)
    done = 0
    while done < size:
        n = min(BATCH, size - done)
        c = fn(cp.arange(done, done + n, dtype=cp.int64))
        counts += cp.bincount(c, minlength=spec["n_codes"])[:spec["n_codes"]]
        done += n
    cp.cuda.Stream.null.synchronize()
    sec = time.perf_counter() - t0
    c = [int(x) for x in cp.asnumpy(counts)]
    if sum(c) != size:
        return {"cases": size, "checked": int(len(probe)),
                "verified_differ": differ, "state": "FAILING",
                "settled": "NOT SETTLED: the reduction lost %d cases."
                           % (size - sum(c))}, sec
    body, verdict, clean = spec["report"](c)
    row = {"cases": size, "checked": int(len(probe)), "verified_differ": 0,
           "state": "CLEAN" if clean else "FINDING STANDS",
           "counts": body, "settled": verdict}
    return row, sec


def describe(specs, stats):
    print("HARVEST CRUNCH: worksheet sentences turned into counted arithmetic")
    print("  module classes read   %d from %s" % (len(BINS), MODULES))
    print("  dot budget read       %s from %s"
          % (DOTS["max"], DOTS["src"] or "NOT FOUND"))
    print("  worksheets read       %d files, %d features, %d marked crunchable,"
          " %d translated"
          % (stats["files"], stats["features"], stats["crunchable"],
             stats["translated"]))
    print()
    total = 0
    for s in specs:
        total += s["size"]