GLOBALGRID2050 / EXPLORE CODE

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

Logic Loop and 2 more files

A Python command-line tool in Worlds that loads bins (`load_bins`). It is built from the build step (`build`), the cupy hist helper (`cupy_hist`) and the cupy order helper (`cupy_order`).

639 lines of Python from worlds-, in 3 files. Topic: Websites and apps. Section 2033 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. Logic Loop storage · worlds- / src/logic_loop.py lines 1–404
  2. Loop Geometry other · worlds- / src/loop_geometry.py lines 1–166
  3. Paths transform · worlds- / src/paths.py lines 1–69

Logic Loop

A Python command-line tool in Worlds that loads bins (`load_bins`). It is built from the build step (`build`), the cupy hist helper (`cupy_hist`) and the cupy order helper (`cupy_order`).

storageworlds- / src/logic_loop.py · lines 1–404 of 404 · Entry point

What it does
It loads data. Defines 7 functions or classes, including load_bins, build, cupy_hist, cupy_order, counts_from_hist. Uses libraries json, os, sys, cupy. 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 logic-loop.json. Out: JSON file. Voltage levels named: 1500V.
Downstream impact
Used directly by 1 file: All Gates (worlds-).
What it achieves
Every gate in this estate answers ONE question about ONE predicate.
Why it matters
Run by All Gates.
Application
worlds- · src · Python CLI
Uses
Paths (import), json, os, sys, cupy
Used by
run by All Gates (script call)
Produces
load_bins, build, cupy_hist, cupy_order, counts_from_hist, pattern_name, main
Defines here
load_bins, build, cupy_hist, cupy_order, counts_from_hist, pattern_name, 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/logic_loop.py:1-404 · blob f25d95aaee6334b191ec805c3fa0b2e2af232487 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""logic_loop.py - the logic-checking loop.

Every gate in this estate answers ONE question about ONE predicate.
This asks what the four predicates say about EACH OTHER: implication,
exclusion, dead rules, equivalence, and which rule binds first.

Pair rule: every count is produced twice - once by a CUDA kernel, once by a
CuPy array path - and nothing is reported unless they agree exactly.

Run with the CuPy interpreter named by GRID_PY: $GRID_PY src/logic_loop.py
"""
import json
import os
import sys

import cupy as cp

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

RULES = ["over_volts", "over_string", "over_mppt", "over_fuse"]

# ---- the stated space -------------------------------------------------
S_LO, S_HI = 20, 34          # series modules a string, inclusive
NS = S_HI - S_LO + 1         # 15
NR = 820                     # rear gain steps, 0 .. 0.30
NT = 820                     # cell temperature steps, -20 .. +25 C
REAR_STEP = 0.30 / (NR - 1)
T_LO = -20.0
T_STEP = 45.0 / (NT - 1)

V_LIMIT = 1500.0             # sourced: printed "1500V DC" on both documents
I_STRING_LIMIT = 20.0        # NO SOURCE
I_MPPT_LIMIT = 40.0          # NO SOURCE


# ---- bins -------------------------------------------------------------
def load_bins():
    paths.require(MODULES, "the module electrical data (MODULES.json)")
    d = json.load(open(MODULES, "r", encoding="utf-8"))
    bins = []
    for c in d["classes"]:
        bins.append(dict(
            class_id=c["class_id"],
            voc=float(c["voc"]["v"]),
            isc=float(c["isc"]["v"]),
            imp=float(c["imp"]["v"]),
            beta=float(c["beta_pct_per_K"]["v"]),
            alpha=float(c["alpha"]["v"]),
            phi=(float(c["k_corr"]["v"]) - 1.0) / 0.135,
            fuse=float(c["max_series_fuse_a"]["v"]),
        ))
    bins.sort(key=lambda b: b["class_id"])
    return bins


# ---- CUDA kernels -----------------------------------------------------
SRC = r'''
extern "C" {

__device__ __forceinline__ void verdicts(
    double voc, double isc, double imp, double beta, double alpha,
    double phi, double fuse, int series, double rear, double T,
    bool *v, bool *s, bool *m, bool *f)
{
    double dT = T - 25.0;
    double voc_T = voc * (1.0 + beta / 100.0 * dT);
    double g = (1.0 + phi * rear) * (1.0 + alpha / 100.0 * dT);
    double isc_T = isc * g;
    double imp_T = imp * g;
    *v = !((double)series * voc_T <= VLIM);
    *s = !(imp_T <= SLIM);
    *m = !(isc_T * 2.0 <= MLIM);
    *f = !(1.25 * isc_T <= fuse);
}

// one thread per case; histogram of the 16 joint truth patterns
__global__ void hist_kernel(const double *p, int nbins,
                            double rstep, double tlo, double tstep,
                            unsigned long long *out)
{
    __shared__ unsigned long long sh[16];
    if (threadIdx.x < 16) sh[threadIdx.x] = 0ULL;
    __syncthreads();

    long long total = (long long)nbins * NS * NR * NT;
    long long stride = (long long)blockDim.x * gridDim.x;
    for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
         i < total; i += stride) {
        long long t = i;
        int ti = (int)(t % NT); t /= NT;
        int ri = (int)(t % NR); t /= NR;
        int si = (int)(t % NS); t /= NS;
        int bi = (int)t;
        const double *b = p + bi * 7;
        bool v, s, m, f;
        verdicts(b[0], b[1], b[2], b[3], b[4], b[5], b[6],
                 20 + si, ri * rstep, tlo + ti * tstep, &v, &s, &m, &f);
        int code = (v ? 1 : 0) | (s ? 2 : 0) | (m ? 4 : 0) | (f ? 8 : 0);
        atomicAdd(&sh[code], 1ULL);
    }
    __syncthreads();
    if (threadIdx.x < 16) atomicAdd(&out[threadIdx.x], sh[threadIdx.x]);
}

// one thread per line; walks one axis safe -> unsafe, finds the first rule to fail
// axis 0 = series 20->34, axis 1 = rear 0->30%, axis 2 = T +25 down to -20 C
__global__ void order_kernel(const double *p, int nbins, int axis,
                             double rstep, double tlo, double tstep,
                             unsigned long long *out)
{
    int steps = (axis == 0) ? NS : ((axis == 1) ? NR : NT);
    long long nlines = (long long)nbins * NS * NR * NT / steps;
    long long stride = (long long)blockDim.x * gridDim.x;
    for (long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
         i < nlines; i += stride) {
        long long t = i;
        int a, b_, bi;
        if (axis == 0) { a = (int)(t % NT); t /= NT; b_ = (int)(t % NR); t /= NR; }
        else if (axis == 1) { a = (int)(t % NT); t /= NT; b_ = (int)(t % NS); t /= NS; }
        else { a = (int)(t % NR); t /= NR; b_ = (int)(t % NS); t /= NS; }
        bi = (int)t;
        const double *bp = p + bi * 7;
        int first[4] = {-1, -1, -1, -1};
        for (int k = 0; k < steps; ++k) {
            int series; double rear, T;
            if (axis == 0) { series = 20 + k; rear = b_ * rstep; T = tlo + a * tstep; }
            else if (axis == 1) { series = 20 + b_; rear = k * rstep; T = tlo + a * tstep; }
            else { series = 20 + b_; rear = a * rstep; T = tlo + (NT - 1 - k) * tstep; }
            bool v, s, m, f;
            verdicts(bp[0], bp[1], bp[2], bp[3], bp[4], bp[5], bp[6],
                     series, rear, T, &v, &s, &m, &f);
            bool r[4] = {v, s, m, f};
            for (int j = 0; j < 4; ++j)
                if (r[j] && first[j] < 0) first[j] = k;
            if (first[0] >= 0 && first[1] >= 0 && first[2] >= 0 && first[3] >= 0) break;
        }
        int best = 1 << 30;
        for (int j = 0; j < 4; ++j)
            if (first[j] >= 0 && first[j] < best) best = first[j];
        if (best == (1 << 30)) { atomicAdd(&out[4], 1ULL); continue; }
        atomicAdd(&out[5], 1ULL);
        for (int j = 0; j < 4; ++j)
            if (first[j] == best) atomicAdd(&out[j], 1ULL);
    }
}
}
'''


def build(nbins):
    opts = ("-DNS=%d" % NS, "-DNR=%d" % NR, "-DNT=%d" % NT,
            "-DVLIM=%r" % V_LIMIT, "-DSLIM=%r" % I_STRING_LIMIT,
            "-DMLIM=%r" % I_MPPT_LIMIT)
    return cp.RawModule(code=SRC, options=opts)


# ---- CuPy array path (independent implementation) ---------------------
def cupy_hist(bins):
    series = cp.arange(S_LO, S_HI + 1, dtype=cp.float64)
    rear = cp.arange(NR, dtype=cp.float64) * REAR_STEP
    T = T_LO + cp.arange(NT, dtype=cp.float64) * T_STEP
    hist = cp.zeros(16, dtype=cp.uint64)
    for b in bins:
        dT = T - 25.0
        voc_T = b["voc"] * (1.0 + b["beta"] / 100.0 * dT)           # (NT,)
        g = (1.0 + b["phi"] * rear)[:, None] * (1.0 + b["alpha"] / 100.0 * dT)[None, :]
        isc_T = b["isc"] * g                                        # (NR,NT)
        imp_T = b["imp"] * g
        v = ~(series[:, None, None] * voc_T[None, None, :] <= V_LIMIT)
        s = ~(imp_T <= I_STRING_LIMIT)
        m = ~(isc_T * 2.0 <= I_MPPT_LIMIT)
        f = ~(1.25 * isc_T <= b["fuse"])
        rest = (s.astype(cp.int32) * 2) | (m.astype(cp.int32) * 4) | (f.astype(cp.int32) * 8)
        code = v.astype(cp.int32) | rest[None, :, :]
        hist += cp.bincount(code.ravel(), minlength=16).astype(cp.uint64)
    return hist


def cupy_order(bins, axis):
    series = cp.arange(S_LO, S_HI + 1, dtype=cp.float64)
    rear = cp.arange(NR, dtype=cp.float64) * REAR_STEP
    T = T_LO + cp.arange(NT, dtype=cp.float64) * T_STEP
    out = cp.zeros(6, dtype=cp.uint64)
    for b in bins:
        dT = T - 25.0
        voc_T = b["voc"] * (1.0 + b["beta"] / 100.0 * dT)
        g = (1.0 + b["phi"] * rear)[:, None] * (1.0 + b["alpha"] / 100.0 * dT)[None, :]
        isc_T = b["isc"] * g
        imp_T = b["imp"] * g
        shape = (NS, NR, NT)
        v = cp.broadcast_to(~(series[:, None, None] * voc_T[None, None, :] <= V_LIMIT), shape)
        s = cp.broadcast_to(~(imp_T <= I_STRING_LIMIT)[None, :, :], shape)
        m = cp.broadcast_to(~(isc_T * 2.0 <= I_MPPT_LIMIT)[None, :, :], shape)
        f = cp.broadcast_to(~(1.25 * isc_T <= b["fuse"])[None, :, :], shape)
        arrs = [v, s, m, f]
        if axis == 0:      # walk series, lines indexed (rear, T)
            arrs = [cp.ascontiguousarray(a.transpose(1, 2, 0)).reshape(-1, NS) for a in arrs]
        elif axis == 1:    # walk rear, lines indexed (series, T)
            arrs = [cp.ascontiguousarray(a.transpose(0, 2, 1)).reshape(-1, NR) for a in arrs]
        else:              # walk T from +25 down, lines indexed (series, rear)
            arrs = [cp.ascontiguousarray(a[:, :, ::-1]).reshape(-1, NT) for a in arrs]
        steps = arrs[0].shape[1]
        firsts = []
        for a in arrs:
            any_ = a.any(axis=1)
            idx = cp.argmax(a, axis=1)
            firsts.append(cp.where(any_, idx, steps + 1))
        F = cp.stack(firsts, axis=0)                 # (4, lines)
        best = F.min(axis=0)
        fail = best <= steps
        out[5] += cp.uint64(int(fail.sum()))
        out[4] += cp.uint64(int((~fail).sum()))
        for j in range(4):
            out[j] += cp.uint64(int(((F[j] == best) & fail).sum()))
    return out


# ---- derive the logic from the joint histogram ------------------------
def counts_from_hist(h):
    h = [int(x) for x in h]
    single = [sum(h[c] for c in range(16) if (c >> j) & 1) for j in range(4)]
    both = [[sum(h[c] for c in range(16) if ((c >> i) & 1) and ((c >> j) & 1))
             for j in range(4)] for i in range(4)]
    a_not_b = [[single[i] - both[i][j] for j in range(4)] for i in range(4)]
    return single, both, a_not_b


def pattern_name(c):
    parts = [RULES[j] for j in range(4) if (c >> j) & 1]
    return "+".join(parts) if parts else "none"


def main():
    bins = load_bins()
    nb = len(bins)
    total = nb * NS * NR * NT
    params = cp.asarray([[b["voc"], b["isc"], b["imp"], b["beta"],
                          b["alpha"], b["phi"], b["fuse"]] for b in bins],
                        dtype=cp.float64).ravel()
    mod = build(nb)

    # ---- pair 1: joint truth-table histogram
    hk = mod.get_function("hist_kernel")
    h_gpu = cp.zeros(16, dtype=cp.uint64)
    hk((2048,), (256,), (params, cp.int32(nb), cp.float64(REAR_STEP),
                         cp.float64(T_LO), cp.float64(T_STEP), h_gpu))
    cp.cuda.Stream.null.synchronize()
    h_cupy = cupy_hist(bins)
    if not bool((h_gpu == h_cupy).all()):
        sys.stderr.write("PAIR RULE BROKEN: histogram mismatch\n%r\n%r\n"
                         % (h_gpu.tolist(), h_cupy.tolist()))
        return 2
    if int(h_gpu.sum()) != total:
        sys.stderr.write("PAIR RULE BROKEN: histogram total %d != %d\n"
                         % (int(h_gpu.sum()), total))
        return 2

    # ---- pair 2: binding order, per axis
    ok = mod.get_function("order_kernel")
    axes = ["series_20_to_34", "rear_0_to_30pct", "T_plus25_down_to_minus20C"]
    order = {}
    for ax in range(3):
        o_gpu = cp.zeros(6, dtype=cp.uint64)
        ok((2048,), (256,), (params, cp.int32(nb), cp.int32(ax),
                             cp.float64(REAR_STEP), cp.float64(T_LO),
                             cp.float64(T_STEP), o_gpu))
        cp.cuda.Stream.null.synchronize()
        o_cupy = cupy_order(bins, ax)
        if not bool((o_gpu == o_cupy).all()):
            sys.stderr.write("PAIR RULE BROKEN: order axis %d\n%r\n%r\n"
                             % (ax, o_gpu.tolist(), o_cupy.tolist()))
            return 2
        o = [int(x) for x in o_gpu.tolist()]
        order[axes[ax]] = {
            "lines_total": o[4] + o[5],
            "lines_with_no_failure": o[4],
            "lines_with_a_failure": o[5],
            "first_rule_to_fail": {RULES[j]: o[j] for j in range(4)},
        }

    single, both, a_not_b = counts_from_hist(h_gpu)

    implications, exclusions, equivalences, dead = [], [], [], []
    for i in range(4):
        if single[i] == 0:
            dead.append(RULES[i])
        for j in range(4):
            if i == j:
                continue
            if a_not_b[i][j] == 0 and single[i] > 0:
                implications.append({"antecedent": RULES[i], "consequent": RULES[j],
                                     "counterexamples": 0,
                                     "cases_where_antecedent_true": single[i]})
            if i < j:
                if both[i][j] == 0:
                    exclusions.append({"a": RULES[i], "b": RULES[j],
                                       "cases_true_together": 0})
                if a_not_b[i][j] == 0 and a_not_b[j][i] == 0 and single[i] > 0:
                    equivalences.append({"a": RULES[i], "b": RULES[j],
                                         "cases": single[i]})
    implications.sort(key=lambda d: (d["antecedent"], d["consequent"]))
    exclusions.sort(key=lambda d: (d["a"], d["b"]))
    equivalences.sort(key=lambda d: (d["a"], d["b"]))
    dead.sort()

    fail_any = total - int(h_gpu[0])
    doc = {
        "space": {
            "bins": [b["class_id"] for b in bins],
            "series": {"from": S_LO, "to": S_HI, "steps": NS},
            "rear_gain_fraction": {"from": 0.0, "to": 0.30, "steps": NR},
            "cell_temperature_C": {"from": T_LO, "to": 25.0, "steps": NT},
            "total_cases": total,
        },
        "limits": {
            "max_system_volts": {"value": V_LIMIT, "source":
                "FROM-DATASHEET: both source documents print 1500 V DC"},
            "string_current_amps": {"value": I_STRING_LIMIT, "source":
                "NO SOURCE: this limit appears nowhere in the evidence base"},
            "mppt_input_amps": {"value": I_MPPT_LIMIT, "source":
                "NO SOURCE: recorded absent from both source documents"},
            "series_fuse_amps": {"value": 35.0, "source":
                "FROM-DATASHEET: max_series_fuse_a printed on both documents"},
        },
        "pair_rule": {
            "implementations": ["cuda_raw_kernel", "cupy_array_path"],
            "agreed_exactly": True,
        },
        "joint_truth_table": {pattern_name(c): int(h_gpu[c]) for c in range(16)},
        "rule_region_sizes": {RULES[j]: single[j] for j in range(4)},
        "cases_failing_at_least_one_rule": fail_any,
        "q1_implications": implications,
        "q2_exclusions": exclusions,
        "q3_dead_rules": dead,
        "q4_equivalences": equivalences,
        "q5_binding_order": order,
        "what_this_does_not_prove": [
            "This is logic over a stated space at a stated resolution. Outside that box, or between its grid points, nothing here holds.",
            "Two of the four limits have NO SOURCE. The 20 A string limit appears nowhere in the evidence base; the 40 A MPPT limit is recorded absent from both source documents.",
            "Redundancy between two invented constants is not a fact about the world. An implication resting on an unsourced number is a fact about the number, not about any hardware.",
            "No diode, cable, inverter, tracker or wiring loss is modelled. Voc, Isc and Imp are datasheet values scaled by printed coefficients only.",
            "Rear gain is applied as a linear phi from a bin's k_corr; one source document does not define the rear-irradiance condition its k_corr comes from.",
        ],
    }
    with open(OUT, "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=2, sort_keys=True)
        fh.write("\n")

    print("cases enumerated: %d   (bins %d x series %d x rear %d x T %d)"
          % (total, nb, NS, NR, NT))
    print("pair rule: CUDA kernel and CuPy array path agree exactly on every count.")
    print("")
    print("REGION SIZES")
    for j in range(4):
        print("  %-12s true in %12d of %d cases" % (RULES[j], single[j], total))
    print("")
    print("IMPLICATIONS (zero counterexamples over the whole space)")
    if not implications:
        print("  none.")
    for d in implications:
        print("  whenever %s is true, %s is true as well." % (d["antecedent"], d["consequent"]))
        print("      so %s can never be the binding constraint on its own; it never "
              "changes an answer %s has not already changed."
              % (d["antecedent"], d["consequent"]))
    print("")
    print("DEAD RULES (never true anywhere in the space)")
    if not dead:
        print("  none - every rule fires somewhere.")
    for r in dead:
        print("  %s never fires. In a verdict list it is decoration." % r)
    print("")
    print("EXCLUSIONS (never true together)")
    if not exclusions:
        print("  none - every pair of rules overlaps somewhere.")
    for d in exclusions:
        print("  %s and %s describe disjoint regions; no design fails both." % (d["a"], d["b"]))
    print("")
    print("EQUIVALENCES (true on exactly the same set)")
    if not equivalences:
        print("  none - no two rules are one rule written twice.")
    for d in equivalences:
        print("  %s and %s are one rule written twice." % (d["a"], d["b"]))
    print("")
    print("BINDING ORDER - walking each axis from safe to unsafe")
    for ax in axes:
        o = order[ax]
        print("  %s: %d of %d lines reach a failure" %
              (ax, o["lines_with_a_failure"], o["lines_total"]))
        for r in RULES:
            print("      %-12s fails first on %12d lines" % (r, o["first_rule_to_fail"][r]))
    print("")
    print("wrote %s" % OUT)
    return 0


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

Loop Geometry

A Python command-line tool in Worlds covering cables. It is built from the conductor m helper (`conductor_m`) and the inductance h helper (`inductance_h`).

otherworlds- / src/loop_geometry.py · lines 1–166 of 166 · Entry point

What it does
Defines conductor_m, inductance_h, 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 sub33kv_design (voltage levels 3kV, 2kV (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: cables, 3kV, 2kV.
Inputs & outputs
In: JSON file loop-geometry.json; command-line arguments. Voltage levels named: 3kV, 2kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Inductance from geometry, not from a guess. Its code works with 3 kV and 2 kV. It accepts `--run`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
worlds- · src · Python CLI
Uses
argparse, io, json, math, os, sys, time, numpy
Used by
none found
Produces
conductor_m, inductance_h, main
Defines here
conductor_m, inductance_h, 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/loop_geometry.py:1-166 · blob 827ba3261bb6d10a79ef481ef36537d39c8aa6d0 · 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
"""Inductance from geometry, not from a guess.

A repository note in this estate says it plainly: carry the loop-area caveat
rather than computing an inductance nobody can source, and avoid inventing
inductance from unevidenced geometry. An earlier sweep here swept L from 40 to
400 uH, which is the same invention with a range around it.

So derive it. For a two-conductor line the inductance per metre is

    L' = (mu0 / pi) * ( ln(d / r) + 1/4 )        H/m

where d is the separation between go and return and r is the conductor radius.
Both are SOURCEABLE: r from the conductor cross-section, d from the routing.
Length comes from R6, which is already ours and already proven.

THE CONSEQUENCE NOBODY HAS PUT TOGETHER
The turned (leapfrog) routing costs about 1.09 m of lead for every 1 m of site
cable it saves, so it never wins on metres. But it brings go and return
alongside each other, so d is small. The sequential routing is shorter but
carries a long return down the row, so d is large - and L' depends on ln(d/r).

Metres is the argument everyone has. Loop area is the one that decides what the
arc suppressor has to survive, and it points the other way.

    python loop_geometry.py --run
"""
import argparse
import io
import json
import math
import os
import sys
import time

import numpy as np

MU0 = 4e-7 * math.pi

# conductor cross-sections in use, mm2 -> radius m
CSA = [4.0, 6.0, 10.0]
RAD_M = [math.sqrt(c / 1e6 / math.pi) for c in CSA]

# separation between go and return, metres. The two routings differ HERE.
#   turned: the pair runs together along the structure
#   sequential: the return comes back down the row, so the loop is the row
D_TURNED = [0.02, 0.05, 0.10, 0.20]          # cable-tie spacing to a tray width
D_SEQUENTIAL = [0.60, 1.00, 1.30, 2.00]      # module width to a row pitch

SERIES = list(range(20, 35))
PITCH = [1.134, 1.303]                        # module width, m, from datasheets
HOME_RUN = [10.0, 30.0, 60.0, 100.0]          # one-way to the combiner, m
ROUTING = ["turned", "sequential"]
CURRENT = [17.35, 20.19, 25.0, 40.0]          # operating, bifacial, fault, backfeed
BREAK_US = [0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0]

WITHSTAND_LO, WITHSTAND_HI = 2000.0, 3000.0
SURV, MARG, EXC = 0, 1, 2
LABEL = ["under 2 kV", "2 to 3 kV, no margin", "over 3 kV, beyond withstand"]


def conductor_m(routing, n, pitch, home):
    """R6, ours and proven: metres of conductor in the string loop."""
    if routing == "turned":
        return 2.006 * n + 2 * home
    return 0.63 * n + (n - 2) * pitch + 0.848 + 2 * home


def inductance_h(d, r, length):
    return (MU0 / math.pi) * (math.log(d / r) + 0.25) * length


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

    rows, cases = [], 0
    for ri, routing in enumerate(ROUTING):
        ds = D_TURNED if routing == "turned" else D_SEQUENTIAL
        for d in ds:
            for csa, r in zip(CSA, RAD_M):
                for n in SERIES:
                    for pitch in PITCH:
                        for home in HOME_RUN:
                            ln = conductor_m(routing, n, pitch, home)
                            L = inductance_h(d, r, ln)
                            for I in CURRENT:
                                for t in BREAK_US:
                                    v = L * I / (t * 1e-6)
                                    cases += 1
                                    rows.append((ri, d, csa, n, pitch, home,
                                                 ln, L, I, t, v))
    print("LOOP GEOMETRY -> INDUCTANCE -> TRANSIENT")
    print("  every inductance DERIVED from separation, conductor radius and")
    print("  R6 length. None swept, none invented.")
    print("  cases: %s" % "{:,}".format(cases))

    arr = np.array([(r[0], r[7], r[8], r[9], r[10], r[6], r[1])
                    for r in rows], dtype=np.float64)
    turned = arr[arr[:, 0] == 0]
    seq = arr[arr[:, 0] == 1]

    print("\n  INDUCTANCE, the thing that was being guessed at")
    for nm, s in (("turned (pair runs together)", turned),
                  ("sequential (return down the row)", seq)):
        print("    %-34s %7.1f to %7.1f uH   median %7.1f"
              % (nm, s[:, 1].min() * 1e6, s[:, 1].max() * 1e6,
                 float(np.median(s[:, 1])) * 1e6))

    print("\n  CONDUCTOR METRES, the argument everyone has")
    for nm, s in (("turned", turned), ("sequential", seq)):
        print("    %-34s %7.1f to %7.1f m       median %7.1f"
              % (nm, s[:, 5].min(), s[:, 5].max(), float(np.median(s[:, 5]))))

    print("\n  TRANSIENT at the declared sub-microsecond target (t = 0.5 us)")
    for nm, s in (("turned", turned), ("sequential", seq)):
        sub = s[s[:, 3] == 0.5]
        over = int((sub[:, 4] > WITHSTAND_HI).sum())
        print("    %-34s median %8.0f V, %s of %s over 3 kV"
              % (nm, float(np.median(sub[:, 4])), "{:,}".format(over),
                 "{:,}".format(len(sub))))

    codes = np.where(arr[:, 4] > WITHSTAND_HI, EXC,
                     np.where(arr[:, 4] > WITHSTAND_LO, MARG, SURV))
    print("\n  WHOLE SPACE")
    for k in range(3):
        c = int((codes == k).sum())
        print("    %-30s %9s  %6.2f%%" % (LABEL[k], "{:,}".format(c),
                                          100.0 * c / len(codes)))

    print("\n  THE FINDING")
    tm, sm = float(np.median(turned[:, 1])), float(np.median(seq[:, 1]))
    tl, sl = float(np.median(turned[:, 5])), float(np.median(seq[:, 5]))
    print("    the turned routing costs %.0f%% MORE conductor and carries"
          % (100 * (tl / sl - 1)))
    print("    %.0f%% LESS loop inductance, because go and return run together."
          % (100 * (1 - tm / sm)))
    print("    Metres is the argument everyone has. Loop area decides what the")
    print("    suppressor must survive, and it points the other way.")
    print("\n  NOT CLAIMED: a two-wire line is a first-order model for a string")
    print("  loop. No coiled slack, no ground plane, no mutual coupling between")
    print("  strings, no frequency dependence. It sources the inductance from")
    print("  geometry instead of guessing it, which is the whole improvement.")

    if a.run:
        out = {"cases": cases,
               "median_uH": {"turned": round(tm * 1e6, 1),
                             "sequential": round(sm * 1e6, 1)},
               "median_metres": {"turned": round(tl, 1),
                                 "sequential": round(sl, 1)},
               "verdicts": {LABEL[k]: int((codes == k).sum()) for k in range(3)},
               "model": "L' = (mu0/pi)(ln(d/r) + 1/4) per metre, length from R6. "
                        "First order: no coiled slack, no ground plane, no "
                        "mutual coupling, no frequency dependence.",
               "anonymised": "No maker, model, project or site."}
        p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                         "night-results", "loop-geometry.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/loop-geometry.json")
    return 0


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

Paths

A Python module in Worlds that works with require any (`require_any`). It is built from the require step (`require`).

transformworlds- / src/paths.py · lines 1–69 of 69 · pattern require (shared by 53 files)

What it does
It calculates its inputs. Defines require, require_any. Uses libraries os.
Inputs & outputs
In: JSON file MODULES.json.
Downstream impact
Used directly by 14 files: Substation (worlds-); Atlas Lattice (worlds-); Check No Private Paths (worlds-); Annihilate (worlds-); and 10 more. Reached from 6 other entry points, including Weekly Gates Workflow (worlds-); All Gates (worlds-); To Kuiper (worlds-).
What it achieves
Where the data lives, without saying where the data lives.
Why it matters
Imported by 13 files, including Substation, Atlas Lattice and Annihilate. Run by Check No Private Paths.
Application
worlds- · src · Python module
Uses
os
Used by
imported by Substation (import), imported by Atlas Lattice (import), run by Check No Private Paths (script call), imported by Annihilate (import), imported by Arc Break (import), imported by Bifacial Chain (import), imported by Furnace (import), imported by Geometry (import), and 6 more
Produces
require, require_any
Defines here
require, require_any
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/paths.py:1-69 · blob da1a6b63284fd4082e973eb536954af06554c32c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Where the data lives, without saying where the data lives.

WHY THIS FILE EXISTS
This repository is public. Every sweep in it read its inputs from an absolute
path typed into the source - a working drive, a feed directory, and in six
places an account name. One of those lines published the on-disk location of a
private conversation transcript. The estate's rule is "trail private, work
produced public", and a hard-coded path is the trail walking into the work.

So no path is written here. A root comes from the environment, and everything
else hangs off it:

    set GRID_DATA=E:\\<wherever it is>      (Windows)
    export GRID_DATA=/mnt/<wherever>        (elsewhere)

If GRID_DATA is not set, the fallback is a `data` directory beside the
repository - which is wrong on this machine, and deliberately so. A script that
cannot find its input should say so loudly rather than quietly reading from a
place it should not be naming.

NOTHING HERE IS A SECRET. The paths were never sensitive because of what they
point at; they were sensitive because of what they reveal about the machine and
the person. An environment variable reveals neither.
"""
import os

# The one thing a reader must supply. No default that names anybody.
ROOT = os.environ.get("GRID_DATA") or os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data")

FEED = os.path.join(ROOT, "feed")
MODULES = os.path.join(FEED, "MODULES.json")
HARVEST = os.path.join(ROOT, "harvest")
HARVEST2 = os.path.join(ROOT, "harvest2")
HARVEST3 = os.path.join(ROOT, "harvest3")
HARVEST_DIRS = [HARVEST, HARVEST2, HARVEST3]
TUBE = os.path.join(ROOT, "grid", "tube", "out", "TUBE-DATA.js")
NIGHT = os.path.join(ROOT, "night")

# The interpreter that has CuPy is not on PATH and is not written down. Scripts
# that need it say GRID_PY rather than naming a venv inside somebody's account.
PY_HINT = "the CuPy interpreter named by GRID_PY"


def require(path, what):
    """Refuse loudly rather than guess. A sweep that cannot find its numbers
    must not fall back on remembered ones - that is how a file of real
    measurements gets quietly replaced by a plausible invention."""
    if not os.path.exists(path):
        raise SystemExit(
            "FAIL: %s not found.\n"
            "  looked in: %s\n"
            "  Set GRID_DATA to the directory that holds it. Nothing is\n"
            "  enumerated on remembered numbers." % (what, path))
    return path


def require_any(paths, what):
    """The same refusal for a set of directories. A sweep that reads three
    places and finds two of them missing is not a smaller sweep, it is a
    different one, and its counts mean something nobody asked for."""
    found = [p for p in paths if os.path.exists(p)]
    if not found:
        raise SystemExit(
            "FAIL: %s not found.\n"
            "  looked in %d place(s) under the configured root.\n"
            "  Set GRID_DATA to the directory that holds them. Nothing is\n"
            "  enumerated on remembered numbers." % (what, len(paths)))
    return found