GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / ventus-grid-engine / sources/deeplink-extracts/receiver

Substation and 1 more file

A Python command-line tool in Worlds that reads substations and 33kV. It is built from the bins step (`bins`) and the reference step (`reference`).

449 lines of Python and JavaScript from ventus-grid-engine, worlds-, in 2 files. Topic: Grid network and substations. Section 465 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. Single-Line Diagram (SLD) Sandbox Technology Vocabulary Excerpt electrical · ventus-grid-engine / sources/deeplink-extracts/receiver/sld-sandbox-technology-vocabulary.excerpt.js lines 1–166
  2. Substation electrical · worlds- / src/substation.py lines 1–283

Single-Line Diagram (SLD) Sandbox Technology Vocabulary Excerpt

A JavaScript file in the receiver folder of Ventus Grid Engine covering grid substations, wind, solar and battery storage (BESS).

electricalventus-grid-engine / sources/deeplink-extracts/receiver/sld-sandbox-technology-vocabulary.excerpt.js · lines 1–166 of 166 · Not reached from any entry point (candidate for review) · pattern layerIdForBucket (shared by 9 files)

What it does
Defines coverage, isProjectTech, layerIdForBucket. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: wind, solar, battery storage (BESS).
Inputs & outputs
In: GeoJSON file grid_substations.geojson.
What it achieves
It is built from the coverage step (`coverage`), the is project tech helper (`isProjectTech`) and the layer id for bucket helper (`layerIdForBucket`). `head_sha` (GridAtlas).
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · sources/deeplink-extracts/receiver · script
Uses
none found
Used by
none found
Produces
coverage, isProjectTech, layerIdForBucket
Defines here
coverage, isProjectTech, layerIdForBucket
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 sources/deeplink-extracts/receiver/sld-sandbox-technology-vocabulary.excerpt.js:1-166 · blob 5f0bc8e70f683f8577051501096653a69b57c46d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
/*
 * PROVENANCE (excerpt)
 * source_repo: gridatlas
 * source_path: atlas/parts/202609041234-sld-sandbox-technology-buckets.js
 * head_sha (gridatlas): 64268fd06a0da54ddffbcdaaaee382e314e829f7
 * lines: 145-276
 *
 * Assembled into the LIVE cartridge "sld-sandbox" (current.json generation
 * 202609041244, v9.109) via
 * atlas/manifests/202609041244-sld-sandbox-v9-8-parts.json ('part' role).
 * Loaded as the FOURTH and last script the shell loads (replaces
 * 202608292126-pre-snapped-config-adapter.js).
 *
 * THIS IS THE v9.109 FIX. Version ledger entry for generation 202609041244:
 * "Pipeline News' three broken technology buckets (wind_onshore, wind_offshore,
 * other) resolve to the engine's real layer id through one table instead of a
 * set-membership test that read enabled while the layer sat off, on a third of
 * the register." (atlas/modules/202609030157-version-ledger.js, VERSION_LEDGER
 * entry g=202609041244, v=v9.109.)
 *
 * Before this table existed, isProjectTech('wind_onshore') returning true was
 * read as "the layer is enabled" even though no DOM control named
 * data-layer-id="wind_onshore" has ever existed -- the engine's own layer id is
 * 'wind' (see REPD_IDS in ventus-corev8engine-exact-repd-delegation.excerpt.js).
 * 2,508 of 7,680 register rows (a third) had a MAP button that silently did
 * nothing.
 *
 * LAYER_ID_FOR_BUCKET is the canonical mapping table, verbatim from source:
 *   wind_onshore -> 'wind'
 *   wind_offshore -> 'wind'
 *   other -> null   (no layer exists; the caller must say so, not search for one)
 *   any other bucket -> itself unchanged (solar, bess, biomass, hydro, hydrogen,
 *     tidal, geothermal, flywheel, caes, act all already match a real layer id)
 */
  const LINK_COUNT = 5;              // how many substations to reach for
  const MAX_LINK_KM = 40;            // beyond this, silence is more honest
  const SUBS_URL = 'data/grid_substations.geojson';
  const SUBS_LAYER_ID = 'l-subs';    // engine convention: layer `l-<id>`, source `src-<id>`

  // Project technologies this fires for. Onshore only: an offshore turbine's
  // export route is nothing like a straight line to the nearest onshore
  // substation, so drawing one would be a picture of a lie.
  /* Every technology the register actually uses, and then some.
     ----------------------------------------------------------------------
     This set was solar, bess and two spellings of wind, and it silently
     rejected the rest. Counted against the shipped register: 2,399 onshore
     wind projects and 109 offshore, so 2,508 of 7,680 — a third of the
     register — had a MAP button that did nothing at all. Not an error, not a
     message, nothing: the deep link tested membership and returned.

     The register writes `wind_onshore`. The engine has had a `wind_onshore`
     layer the whole time. Only this list disagreed with both.

     So it no longer decides alone. The list below is the fast path, and
     anything the ENGINE has a layer control for is accepted too — the engine
     owns the layers, so the engine's vocabulary is the authority and this
     stops being a place a technology can be forgotten. */
  const PROJECT_TECHS = new Set([
    'solar', 'solar_operational', 'solar_roof',
    'bess', 'bess_operational',
    'wind', 'wind_onshore', 'wind_onshore_operational',
    'wind_offshore', 'wind_offshore_operational',
    // The rest of the engine's own generation and storage dashboard, read off
    // the live page rather than guessed. Note wind_onshore is NOT among the
    // engine's layer ids -- it has `wind` and `wind_onshore_operational` --
    // yet the register writes wind_onshore for 2,399 projects. Asking the
    // engine alone would still have missed every one of them, which is why the
    // explicit entry above is not redundant with the lookup below.
    'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal',
    'flywheel', 'caes', 'act',
    /* `other` is what the register writes for a category it has no
       bucket for. Over the 11,069-row REPD product this Atlas's search
       lane reads, 25 DESNZ categories normalise to 14 ids and `other` was
       the only one missing here - 4 projects, 2 Unknown and 2 Air Source
       Heat Pumps. Not many; not zero; and written again the next time the
       register gains a category. */
    'other'
  ]);

  /* Which technologies measure, and what each measurement is OF, is owned by
     the technology-coverage module rather than by this file. It is assembled
     into this cartridge ahead of this part, so it is here by the time any of
     this runs; the fallback below exists only so a proof can load this part
     alone, and it reproduces the module's answer rather than a different one.

     Offshore NO LONGER WITHHOLDS. It used to open a card and draw nothing, on
     reasoning about export cables and landfalls that was right about routes
     and wrong about whether to measure at all. An offshore project's export
     cable does land at an onshore substation, so the distance is a
     measurement of something real. What changed is the answer; what did not
     change is a single word of the route reasoning, which the module now
     prints beside the number instead of instead of it. */
  const coverage = (() => {
    try {
      const module = window.__GRIDATLAS_MODULES__?.technologyCoverage;
      if (module && typeof module.policy === 'function') return module;
    } catch (_) { /* fall through to the local reproduction */ }
    const OFF = new Set(['wind_offshore', 'wind_offshore_operational']);
    return {
      policy: (tech) => ({ technology: tech || null, measure: true,
        offshore: OFF.has(String(tech || '')),
        sample: 'nearest of the mapped substations at or above the voltage '
          + 'floor that this search could see',
        notes: [] }),
      namedOffshore: () => false
    };
  })();
  const OFFSHORE_TECHS = new Set(['wind_offshore', 'wind_offshore_operational']);

  function isProjectTech(tech) {
    if (!tech) return false;
    if (PROJECT_TECHS.has(tech)) return true;
    // Ask the engine. If it has a control for this layer, it is a technology
    // this map knows about, whatever this cartridge was written knowing.
    try {
      return Boolean(document.querySelector(
        'input[type=checkbox][data-layer-id="' + String(tech).replace(/"/g, '') + '"]'));
    } catch (error) {
      return false;
    }
  }

  /* Pipeline News' MAP link sends a technology BUCKET, not a layer id, and
     the two are not the same vocabulary. There are exactly thirteen buckets
     it can send -- the four-member spine solar/bess/wind_onshore/
     wind_offshore, plus the nine wider-fleet buckets biomass/hydro/
     hydrogen/act/tidal/geothermal/caes/flywheel/other -- see
     atlas/modules/202609031310-technology-coverage.js SPINE and
     widerFleetBuckets(), which is the one place that list is owned.

     isProjectTech() above tests membership of PROJECT_TECHS, which
     deliberately contains wind_onshore, wind_offshore and other so that an
     arrival for one of them is not abandoned. That membership test answers
     "is this a technology the map recognises", not "is there a layer
     control with this exact id" -- and those are different questions here:

       - wind_onshore and wind_offshore are not layer ids. The engine
         publishes one combined `wind` layer, filtered on tech === 'wind',
         which is inclusive of both orientations and every status (see
         ukConfig's REPD layer group); wind_onshore_operational and
         wind_offshore_operational are narrower operational-only subsets,
         not the general layer. A deep link for either bucket wants the
         general layer switched on, so both resolve to 'wind'.
       - other has never had a layer control at all. 25 DESNZ categories
         normalise to 14 register ids and `other` is the one bucket that
         genuinely has nothing to switch on -- not a bug to retry, a fact
         to state.

     Measured live on v9.107: because isProjectTech('wind_onshore') is
     true, the arrival's own technology_layer.enabled read true while the
     DOM search for a control literally named "wind_onshore" failed every
     time -- 2,508 of 7,680 register rows, a third of it. One table here,
     consulted at the one place a control is actually looked up, so a
     bucket cannot go missing from it the way these three did while still
     passing the membership test that was supposed to catch that. */
  const LAYER_ID_FOR_BUCKET = Object.freeze({
    wind_onshore: 'wind',
    wind_offshore: 'wind',
    other: null   // no layer exists; the caller must say so, not search for one
  });

  function layerIdForBucket(tech) {
    const id = String(tech == null ? '' : tech);
    return Object.prototype.hasOwnProperty.call(LAYER_ID_FOR_BUCKET, id)
      ? LAYER_ID_FOR_BUCKET[id] : id;
  }

Substation

A Python command-line tool in Worlds that reads substations and 33kV. It is built from the bins step (`bins`) and the reference step (`reference`).

electricalworlds- / src/substation.py · lines 1–283 of 283 · Entry point · pattern reference (shared by 15 files)

What it does
It loads substations and 33kV. Defines bins, g, reference, main. Uses libraries argparse, io, json, math, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 33kV, 400kV, 1500V, 0.8kV.
Inputs & outputs
In: JSON file substation.json; command-line arguments. Voltage levels named: 400kV, 33kV, 1500V, 0.8kV.
Downstream impact
Used directly by 1 file: Watch Ulp (worlds-).
What it achieves
500MW down to one substation, every loop enumerated. Its code works with 500 MW, 33 kV and 0.8 kV. It accepts `--run`.
Why it matters
Imported by Watch Ulp.
Application
worlds- · src · Python CLI
Uses
Paths (import), argparse, io, json, math, os, sys, time, numpy
Used by
imported by Watch Ulp (import)
Produces
bins, reference, main
Defines here
bins, g, reference, 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/substation.py:1-283 · blob 6910715f99d6cda0d69955350cc407604b7850b6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
"""500 MW down to one substation, every loop enumerated.

ANONYMISED. The hierarchy is ordinary practice, taken as a shape and nothing
else: module -> string -> inverter at 0.8 kV -> block -> one 33 kV collection
substation -> 400 kV interface. No project, client, site, maker or model
appears here or in any output. 500 MW DC is not the size of anything real.

WHAT IS ENUMERATED, AND WHY IT IS THE LOOP
Every string is a loop. Its inductance is DERIVED from geometry - conductor
separation, conductor radius, and the R6 length that is ours and proven -
never swept as an invented quantity. That loop decides three things at once:

  the cold-voltage verdict        does the string breach the 1500 V rating
  the DC:AC verdict               against the AMBIENT-DERATED inverter rating
  the transient at disconnection  V = L*I/t, which the arc suppressor must eat

Those have always been three separate arguments. They are one geometry.

    python substation.py            the space
    python substation.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
MU0 = 4e-7 * math.pi

# ---- the hierarchy, from the drawing's shape only
TARGET_DC_MW = 500.0
BLOCK_MW = 9.856
AC_V, COLLECT_KV, GRID_KV = 800.0, 33.0, 400.0
BLOCKS_PER_SUBSTATION = [4, 6, 8]          # one 33 kV substation serves these

# ---- axes
SERIES = list(range(20, 35))                          # 15
STRINGS = [24, 28, 32]                                # 3 machine variants
INV_KVA = [352.0, 320.0, 295.0]                       # 30 / 40 / 50 C derated
CSA = [4.0, 6.0, 10.0]                                # 3
RAD_M = [math.sqrt(c / 1e6 / math.pi) for c in CSA]
N_SEP, SEP_LO, SEP_HI = 41, 0.02, 2.00                # separation, m
N_HOME, HOME_LO, HOME_HI = 41, 5.0, 150.0             # one-way home run, m
N_BRK, BRK_LO, BRK_HI = 51, 0.1e-6, 10.0e-6           # break time, s
N_CUR, CUR_LO, CUR_HI = 41, 5.0, 45.0                 # interrupted current, A
TMIN = [-14.0, -12.0, -11.0, -10.0, -8.0, -6.0]       # 6
ROUTING = [0, 1]                                      # 0 turned, 1 sequential
PITCH = 1.303

MAX_V = 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40     # OURS. No maker and no contract publishes one.
WITH_HI = 3000.0                  # series pair of 1700 V devices

OK, DISP, COLD, BAND, TRANS = 0, 1, 2, 3, 4
LABEL = ["clears every test", "disputed: the clause decides it",
         "breaches the 1500 V rating", "DC:AC outside our chosen band",
         "transient beyond the suppressor withstand"]


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
    if isinstance(e, dict):
        e = list(e.values())
    out = []
    for m in e:
        def g(k):
            v = m.get(k)
            return v.get("v") if isinstance(v, dict) else v
        voc, beta, wp, isc = g("voc"), g("beta_pct_per_K"), g("wp"), g("isc")
        if None in (voc, beta, wp, isc):
            continue
        out.append((float(voc), float(beta), float(wp), float(isc)))
    if not out:
        raise SystemExit("FAIL: no usable bins.")
    return out


B = bins()
RAD = [len(B), len(SERIES), len(STRINGS), len(INV_KVA), len(CSA), N_SEP,
       N_HOME, N_BRK, N_CUR, len(TMIN), len(ROUTING)]
SIZE = int(np.prod([float(x) for x in RAD]))

SRC = """
long long r = idx;
int bi = (int)(r %% %(R0)d); r /= %(R0)d;
int si = (int)(r %% %(R1)d); r /= %(R1)d;
int ni = (int)(r %% %(R2)d); r /= %(R2)d;
int ii = (int)(r %% %(R3)d); r /= %(R3)d;
int ci = (int)(r %% %(R4)d); r /= %(R4)d;
int pi = (int)(r %% %(R5)d); r /= %(R5)d;
int hi = (int)(r %% %(R6)d); r /= %(R6)d;
int qi = (int)(r %% %(R7)d); r /= %(R7)d;
int ai = (int)(r %% %(R8)d); r /= %(R8)d;
int ti = (int)(r %% %(R9)d); r /= %(R9)d;
int ro = (int)(r %% %(R10)d);

double voc = tvoc[bi], bet = tbeta[bi], w = twp[bi];
double se = ser[si], sn = strs[ni], kva = inv[ii];
double rad = trad[ci], tm = tmin[ti];
double d    = %(SLO).17g + (%(SHI).17g - %(SLO).17g) * (double)pi / (%(R5)d - 1.0);
double home = %(HLO).17g + (%(HHI).17g - %(HLO).17g) * (double)hi / (%(R6)d - 1.0);
double brk  = %(BLO).17g + (%(BHI).17g - %(BLO).17g) * (double)qi / (%(R7)d - 1.0);
double cur  = %(CLO).17g + (%(CHI).17g - %(CLO).17g) * (double)ai / (%(R8)d - 1.0);

/* R6, ours: metres of conductor in the loop */
double len = (ro == 0) ? (2.006 * se + 2.0 * home)
                       : (0.63 * se + (se - 2.0) * %(PITCH).17g + 0.848 + 2.0 * home);
/* inductance DERIVED from geometry, never swept */
double L = (%(MU0).17g / %(PI).17g) * (log(d / rad) + 0.25) * len;

double voc_cold = voc * (1.0 + bet / 100.0 * (tm - 25.0));
double v_str    = se * voc_cold;
double v_str_a  = se * voc * (1.0 + bet / 100.0 * (tm + 10.0 - 25.0));
double dcac     = (se * w / 1000.0) * sn / kva;
double v_kick   = L * cur / brk;

if (v_str_a > %(MAXV).17g)                       code = %(COLD)d;
else if (v_str > %(MAXV).17g)                    code = %(DISP)d;
else if (dcac < %(LO).17g || dcac > %(HI).17g)   code = %(BAND)d;
else if (v_str + v_kick > %(WHI).17g)            code = %(TRANS)d;
else                                             code = %(OK)d;
""" % {"R0": RAD[0], "R1": RAD[1], "R2": RAD[2], "R3": RAD[3], "R4": RAD[4],
       "R5": RAD[5], "R6": RAD[6], "R7": RAD[7], "R8": RAD[8], "R9": RAD[9],
       "R10": RAD[10], "SLO": SEP_LO, "SHI": SEP_HI, "HLO": HOME_LO,
       "HHI": HOME_HI, "BLO": BRK_LO, "BHI": BRK_HI, "CLO": CUR_LO,
       "CHI": CUR_HI, "PITCH": PITCH, "MU0": MU0, "PI": math.pi, "MAXV": MAX_V,
       "LO": DCAC_LO, "HI": DCAC_HI, "WHI": WITH_HI, "COLD": COLD,
       "DISP": DISP, "BAND": BAND, "TRANS": TRANS, "OK": OK}


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, ni, ii, ci, pi_, hi, qi, ai, ti, ro = v
        voc, bet, w, _isc = B[bi]
        se, sn, kva = SERIES[si], STRINGS[ni], INV_KVA[ii]
        rad, tm = RAD_M[ci], TMIN[ti]
        d = SEP_LO + (SEP_HI - SEP_LO) * pi_ / (N_SEP - 1.0)
        home = HOME_LO + (HOME_HI - HOME_LO) * hi / (N_HOME - 1.0)
        brk = BRK_LO + (BRK_HI - BRK_LO) * qi / (N_BRK - 1.0)
        cur = CUR_LO + (CUR_HI - CUR_LO) * ai / (N_CUR - 1.0)
        ln = (2.006 * se + 2 * home) if ro == 0 else \
             (0.63 * se + (se - 2) * PITCH + 0.848 + 2 * home)
        L = (MU0 / math.pi) * (math.log(d / rad) + 0.25) * ln
        # ASSOCIATE EXACTLY AS THE KERNEL DOES. The kernel forms the cold
        # voltage through a voc_cold intermediate, se * (voc * k); this read
        # (se * voc) * k. Both are valid IEEE doubles and they differ at the
        # last bit constantly - 2,659,568 of 9,000,150 cases in one sweep.
        # Enumerating 18,980,843,400 cases found ZERO that land on opposite
        # sides of 1500 V or 3000 V, so no published count moves. What moves
        # is what '0 differ' MEANS: a probe of 200,000 would have missed a
        # difference this thin with probability 0.999968. The certificate was
        # nearly powerless; it simply had nothing to catch.
        vs = se * (voc * (1 + bet / 100 * (tm - 25)))
        va = se * voc * (1 + bet / 100 * (tm + 10 - 25))
        dcac = (se * w / 1000.0) * sn / kva
        vk = L * cur / brk
        if va > MAX_V: out[j] = COLD
        elif vs > MAX_V: out[j] = DISP
        elif dcac < DCAC_LO or dcac > DCAC_HI: out[j] = BAND
        elif vs + vk > WITH_HI: out[j] = TRANS
        else: out[j] = OK
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", action="store_true")
    a = ap.parse_args()
    names = ["module bin", "modules in series", "strings per inverter",
             "ambient-derated rating", "conductor mm2", "conductor separation",
             "home run length", "break time", "interrupted current",
             "site min temp", "routing"]
    print("500 MW DC DOWN TO ONE SUBSTATION - anonymised, every loop")
    print("  module -> string -> inverter at %.1f kV -> block of %g MW ->"
          % (AC_V / 1000, BLOCK_MW))
    print("  one %g kV collection substation -> %g kV interface"
          % (COLLECT_KV, GRID_KV))
    print("  blocks in the plant: %d    one substation serves %s"
          % (math.ceil(TARGET_DC_MW / BLOCK_MW), BLOCKS_PER_SUBSTATION))
    for nm, n in zip(names, RAD):
        print("    %-24s %6d" % (nm, n))
    print("    %-24s %6s" % ("", "------"))
    print("    %-24s %s cases" % ("", "{:,}".format(SIZE)))
    if not a.run:
        print("\n  --run to enumerate on the card.")
        return 0

    import cupy as cp
    K = cp.ElementwiseKernel(
        "int64 idx, raw float64 tvoc, raw float64 tbeta, raw float64 twp, "
        "raw float64 ser, raw float64 strs, raw float64 inv, raw float64 trad, "
        "raw float64 tmin", "int64 code", SRC, "ventus_substation")
    T = (cp.asarray(np.array([b[0] for b in B])),
         cp.asarray(np.array([b[1] for b in B])),
         cp.asarray(np.array([b[2] for b in B])),
         cp.asarray(np.array(SERIES, float)),
         cp.asarray(np.array(STRINGS, float)),
         cp.asarray(np.array(INV_KVA, float)),
         cp.asarray(np.array(RAD_M)),
         cp.asarray(np.array(TMIN, float)))

    stride = 1000003
    while np.gcd(stride, SIZE) != 1:
        stride += 2
    probe = (np.arange(200000, dtype=np.int64) * stride) % SIZE
    differ = int((cp.asnumpy(K(cp.asarray(probe), *T)) != reference(probe)).sum())
    print("\n  verified: processor vs card on 200,000 cases, %d differ" % differ)
    if differ:
        print("  FAIL: nothing reported for arithmetic that differs."); return 1

    free, _ = cp.cuda.Device(0).mem_info
    batch = max(1 << 16, min(1 << 23, int(free * 0.25 / 16)))
    tot = cp.zeros(5, dtype=cp.int64)
    done, t0 = 0, time.perf_counter()
    while done < SIZE:
        n = min(batch, SIZE - done)
        tot += cp.bincount(K(cp.arange(done, done + n, dtype=cp.int64), *T),
                           minlength=5)[:5]
        done += n
    cp.cuda.Stream.null.synchronize()
    sec = time.perf_counter() - t0
    got = [int(x) for x in cp.asnumpy(tot)]
    if sum(got) != SIZE:
        print("  FAIL: reduction lost cases."); return 1
    print("  ENUMERATED %s in %.1f s (%s loops/s)"
          % ("{:,}".format(SIZE), sec, "{:,.0f}".format(SIZE / sec)))
    for k in range(5):
        print("    %-44s %16s %7.3f%%"
              % (LABEL[k], "{:,}".format(got[k]), 100.0 * got[k] / SIZE))

    blocks = math.ceil(TARGET_DC_MW / BLOCK_MW)
    print("\n  THE SUBSTATION, at 30 in series, 24 strings, 660 Wp:")
    for bps in BLOCKS_PER_SUBSTATION:
        mw = bps * BLOCK_MW
        inv = math.ceil(mw * 1000 / 475.2)
        print("    %d blocks = %6.2f MW DC, %3d inverters, %6s strings, %7s modules"
              % (bps, mw, inv, "{:,}".format(inv * 24), "{:,}".format(inv * 24 * 30)))
    print("    plant total: %d blocks, %d substations at 8 blocks each"
          % (blocks, math.ceil(blocks / 8)))

    out = {"cases": SIZE, "seconds": round(sec, 2), "verified_differ": differ,
           "axes": dict(zip(names, RAD)), "verdicts": dict(zip(LABEL, got)),
           "hierarchy": {"target_dc_mw": TARGET_DC_MW, "block_mw": BLOCK_MW,
                         "blocks": blocks, "ac_v": AC_V,
                         "collect_kv": COLLECT_KV, "grid_kv": GRID_KV,
                         "blocks_per_substation": BLOCKS_PER_SUBSTATION},
           "inductance": "DERIVED from conductor separation, conductor radius "
                         "and R6 length. Never swept as an invented quantity.",
           "dcac_band": "1.15-1.40 is OURS. No manufacturer and no contract "
                        "read this night publishes one.",
           "what_this_is_not": "DC sizing and a first-order transient screen. "
                               "Not a design, not a study, not a connection "
                               "assessment. No AC analysis, no protection "
                               "coordination, no clamping or snubber modelled.",
           "anonymised": "Architecture only. No project, client, site, maker "
                         "or model. 500 MW DC is not the size of anything real."}
    p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                     "night-results", "substation.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/substation.json")
    return 0


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