GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / faraday / bench

Tests and 6 more files

A Python module in the bench folder of Faraday that tests grid 11kV UK Power Networks (UKPN), substations and cables, using SHA-256.

682 lines of Python and JavaScript from faraday, in 7 files. Topic: Grid network and substations. Section 323 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. Tests test · faraday / bench/tests.py lines 1–333
  2. Topo storage · faraday / bench/topo.py lines 1–200
  3. Topo Check ingest · faraday / bench/topo_check.mjs lines 1–22
  4. Traction Cases transform · faraday / bench/traction_cases.py lines 1–45
  5. E036 other · faraday / experiments/e036.mjs lines 1–29
  6. E037 other · faraday / experiments/e037.mjs lines 1–22
  7. E038 other · faraday / experiments/e038.mjs lines 1–31

Tests

A Python module in the bench folder of Faraday that tests grid 11kV UK Power Networks (UKPN), substations and cables, using SHA-256.

testfaraday / bench/tests.py · lines 1–333 of 333 · Entry point · pattern adder (shared by 2 files)

What it does
It tests grid 11kV UKPN, substations and cables. Defines 23 functions or classes, including points, km, shape, nearest_gap, t_arrangement. Uses libraries cmath, glob, hashlib, json, math. Side effects: uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 11kV (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: substations, cables, 11kV.
Inputs & outputs
In: Parquet file grid_11kv_ukpn.parquet. Voltage levels named: 11kV.
Downstream impact
Used directly by 1 file: One (faraday).
What it achieves
It is built from the points step (`points`), the shape step (`shape`) and the nearest gap helper (`nearest_gap`). Each test is a pure function of its id: same id, same answer, on any machine. Its code works with 11 kV.
Why it matters
Imported by One.
Application
faraday · bench · Python module
Uses
Site Cases (import), Cable Cases (import), Energy Cases (import), Traction Cases (import), National Cases (import), cmath, glob, hashlib, json, math, os, random, pyarrow.parquet
Used by
imported by One (import)
Produces
points, km, shape, nearest_gap, t_arrangement, t_gate, t_pulse, Cells, adder, t_logic, feeder, sweep
Defines here
points, km, shape, nearest_gap, t_arrangement, t_gate, t_pulse, Cells, __init__, inp, nand, NOT, AND, OR, XOR, run, adder, t_logic, feeder, sweep, t_feeder, registry, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/tests.py:1-333 · blob bf1a86677467eff3f0e30e2abf00fb780921dc40 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/tests.py - the hundred. Each test is a pure function of its id: same id, same answer, on any machine.

Every test returns one record: the question, what was done, what was seen, the numbers, and a verdict that CAN be
REFUTED. Nothing here draws anything. These are the sums and the rules; the Kuiper and the wafer show them.

FAMILIES (real names, not numbers):
  ARRANGEMENTS  ten ways to place n cells; the black sky rule decides (a dot is never wider than a third of the gap)
  GATES         ten selections and compositions on a real population; lit + dark = the whole, exactly
  PULSES        ten pulse fronts over a real population; no cell switches before the front reaches it
  LOGIC         ten circuits made of one kind of gate cell (lit unless both its two cells were lit a tick earlier)
  FEEDER PULSE  sixty load flows by the forward-backward sweep on estimated feeders joining REAL substation points

WHAT IS REAL AND WHAT IS ASSUMED in FEEDER PULSE, said once and carried in every record:
  REAL      the places of 15,126 secondary substations in the UK Power Networks area (estate layer grid_11kv_ukpn)
  ASSUMED   which substation feeds which: a minimum spanning tree from a chosen root (the estate holds no 11 kV lines)
  CANDIDATE every electrical figure (cable ohms per km, homes per substation, kW per home, charger kW, diversity):
            typical values quoted from memory, NOT yet keyed to a source. A client overwrites them with their own.
"""
import cmath
import glob
import hashlib
import json
import math
import os
import random

GOLDEN = math.pi * (3 - math.sqrt(5))
# the estate layer sits in the data-gridatlas repository, cloned beside this one; UKPN_POINTS overrides where to look
DATA_GLOB = os.environ.get('UKPN_POINTS', os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
                                                       'data-gridatlas', '**', 'grid_11kv_ukpn.parquet'))


# ------------------------------------------------------------------ the population of real places
_points = None
def points():
    """(lon, lat) of every substation point, in the file's own order. Read once per process."""
    global _points
    if _points is None:
        import pyarrow.parquet as pq
        hits = glob.glob(DATA_GLOB, recursive=True)
        if not hits:
            raise FileNotFoundError('the estate layer grid_11kv_ukpn.parquet was not found')
        t = pq.read_table(hits[0], columns=['min_x', 'min_y']).to_pydict()
        _points = [(float(x), float(y)) for x, y in zip(t['min_x'], t['min_y'])]
    return _points

def km(a, b):
    """Distance in km between two (lon, lat), flat earth at this latitude: good to a part in a thousand over 30 km."""
    kx = 111.32 * math.cos(math.radians((a[1] + b[1]) / 2))
    return math.hypot((a[0] - b[0]) * kx, (a[1] - b[1]) * 110.57)


# ------------------------------------------------------------------ ARRANGEMENTS
def shape(name, n):
    P = []
    if name == 'sunflower':
        P = [(math.sqrt((j + .5) / n) * math.cos(j * GOLDEN), math.sqrt((j + .5) / n) * math.sin(j * GOLDEN)) for j in range(n)]
    elif name == 'ring':
        P = [(math.cos(2 * math.pi * j / n), math.sin(2 * math.pi * j / n)) for j in range(n)]
    elif name == 'two rings':
        h = n // 2
        P = [(math.cos(2 * math.pi * j / h), math.sin(2 * math.pi * j / h)) for j in range(h)] + \
            [(.6 * math.cos(2 * math.pi * j / (n - h)), .6 * math.sin(2 * math.pi * j / (n - h))) for j in range(n - h)]
    elif name == 'orbit':
        e = 0.3
        for j in range(n):
            a = 2 * math.pi * j / n; r = (1 - e * e) / (1 + e * math.cos(a)) / (1 + e)
            P.append((r * math.cos(a), r * math.sin(a)))
    elif name == 'square lattice':
        s = math.ceil(math.sqrt(n)); P = [(-1 + 2 * (j % s) / (s - 1), -1 + 2 * (j // s) / (s - 1)) for j in range(n)]
    elif name == 'hexagonal lattice':
        s = math.ceil(math.sqrt(n))
        P = [(-1 + 2 * ((j % s) + .5 * ((j // s) % 2)) / s, -1 + 2 * (j // s) * math.sqrt(3) / 2 / s) for j in range(n)]
    elif name == 'spiral arms':
        for j in range(n):
            arm = j % 4; t = (j // 4 + 1) / (n / 4); a = arm * math.pi / 2 + 3 * t
            P.append((t * math.cos(a), t * math.sin(a)))
    elif name == 'busbar and feeders':
        bus = n // 5; P = [(-1 + 2 * j / (bus - 1), .8) for j in range(bus)]
        rest = n - bus; f = 8
        for j in range(rest):
            P.append((-1 + 2 * (j % f + .5) / f, .7 - 1.6 * (j // f) / max(1, (rest // f))))
    elif name == 'random scatter':
        rng = random.Random(7); P = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
    elif name == 'clock':
        ticks = 12; per = n // 15
        for k in range(ticks):
            a = 2 * math.pi * k / ticks
            P += [((.85 + .15 * i / per) * math.sin(a), (.85 + .15 * i / per) * math.cos(a)) for i in range(per)]
        for length, a in ((.5, 1.0), (.75, 3.4), (.8, 5.2)):
            m = (n - len(P)) // 3 if length < .8 else n - len(P)
            P += [(length * i / m * math.sin(a), length * i / m * math.cos(a)) for i in range(m)]
    return P[:n]

def nearest_gap(P):
    """Smallest distance between any two points, by a grid of buckets."""
    n = len(P); cell = 2.2 / math.sqrt(n); B = {}
    for i, (x, y) in enumerate(P):
        B.setdefault((int(x / cell), int(y / cell)), []).append(i)
    best = 9.0
    for (cx, cy), ids in B.items():
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                for j in B.get((cx + dx, cy + dy), ()):
                    for i in ids:
                        if i < j:
                            d = math.hypot(P[i][0] - P[j][0], P[i][1] - P[j][1])
                            if d < best: best = d
    return best

def t_arrangement(name, n=2000, body_px=150):
    P = shape(name, n); gap = nearest_gap(P)
    dot_px = gap / 3 * body_px                       # the black sky rule: radius at most a third of the gap
    ok = len(P) == n and dot_px >= 0.5               # a dot under half a pixel cannot be seen: the shape fails at this n
    return dict(question='Can %d cells be placed as "%s" in a body %d px in radius and still obey the black sky rule with a dot that can be seen?' % (n, name, body_px),
                did='placed the cells; found the smallest gap between any two; took a third of it as the largest honest dot',
                numbers=dict(cells=len(P), smallest_gap=round(gap, 6), largest_honest_dot_px=round(dot_px, 3)),
                observed='largest honest dot %.2f px' % dot_px, result='CONFIRMED' if ok else 'REFUTED')


# ------------------------------------------------------------------ GATES
def t_gate(kind):
    P = points(); N = len(P)
    north = {i for i, p in enumerate(P) if p[1] > 51.6}; east = {i for i, p in enumerate(P) if p[0] > 0.2}
    inner = {i for i, p in enumerate(P) if km(p, (-0.1276, 51.5072)) < 25}
    U = set(range(N)); comp = lambda s: U - s
    cases = {
        'north': (north, None), 'east': (east, None), 'within 25 km of Charing Cross': (inner, None),
        'north AND east': (north & east, None), 'north OR east': (north | east, None), 'NOT north': (comp(north), None),
        'De Morgan: NOT (north AND east) = NOT north OR NOT east': (comp(north & east), comp(north) | comp(east)),
        'De Morgan: NOT (north OR east) = NOT north AND NOT east': (comp(north | east), comp(north) & comp(east)),
        'north AND NOT north is empty': (north & comp(north), set()),
        'inner OR NOT inner is everything': (inner | comp(inner), U),
    }
    lit, same_as = cases[kind]; dark = U - lit
    ok = len(lit) + len(dark) == N and (same_as is None or lit == same_as)
    return dict(question='Gate "%s" on %d real substation places: do lit and dark make the whole, and does the identity hold?' % (kind, N),
                did='selected by the rule; counted lit, dark and whole; compared the two sides where the gate is an identity',
                numbers=dict(lit=len(lit), dark=len(dark), whole=N), observed='%d lit + %d dark = %d' % (len(lit), len(dark), len(lit) + len(dark)),
                result='CONFIRMED' if ok else 'REFUTED')


# ------------------------------------------------------------------ PULSES
def t_pulse(origin_name, speed_km_per_tick, second=None):
    P = points(); O = dict(charing=(-0.1276, 51.5072), norwich=(1.2974, 52.6309), brighton=(-0.1372, 50.8225))
    o = O[origin_name]; early = 0; last = 0; met = None
    for p in P[::3]:                                   # every third place: 5,042 cells, the same every run
        d = km(p, o); t_arrive = math.ceil(d / speed_km_per_tick)
        if t_arrive * speed_km_per_tick < d - 1e-9: early += 1     # lit before the front could have reached it
        last = max(last, t_arrive)
        if second:
            d2 = km(p, O[second]); t2 = math.ceil(d2 / speed_km_per_tick)
            if t_arrive == t2 and (met is None or t2 < met): met = t2
    ok = early == 0 and (second is None or met is not None)
    return dict(question='A front leaves %s at %g km a tick%s: is any cell lit before the front could reach it?' % (origin_name, speed_km_per_tick, (' and another leaves ' + second) if second else ''),
                did='gave every cell the first tick at which the front has covered its distance; counted cells lit early',
                numbers=dict(cells=len(P[::3]), lit_early=early, last_cell_tick=last, fronts_first_meet_tick=met),
                observed='%d lit early; the last cell switches at tick %d' % (early, last), result='CONFIRMED' if ok else 'REFUTED')


# ------------------------------------------------------------------ LOGIC (one kind of gate cell)
class Cells:
    def __init__(self): self.rules = {}; self.k = 0
    def inp(self, name): self.k += 1; self.rules[self.k] = ('in', name); return self.k
    def nand(self, a, b): self.k += 1; self.rules[self.k] = ('g', a, b); return self.k
    def NOT(self, a): return self.nand(a, a)
    def AND(self, a, b): return self.NOT(self.nand(a, b))
    def OR(self, a, b): return self.nand(self.NOT(a), self.NOT(b))
    def XOR(self, a, b): n = self.nand(a, b); return self.nand(self.nand(a, n), self.nand(b, n))
    def run(self, inputs, outs, ticks=400):
        """State of every cell tick by tick from all dark; stops when nothing has changed for 8 ticks."""
        s = {k: (inputs[r[1]] if r[0] == 'in' else 0) for k, r in self.rules.items()}; quiet = 0
        for t in range(1, ticks):
            n = {k: (inputs[r[1]] if r[0] == 'in' else (0 if (s[r[1]] and s[r[2]]) else 1)) for k, r in self.rules.items()}
            quiet = quiet + 1 if n == s else 0; s = n
            if quiet >= 8: return [s[o] for o in outs], t - 8
        return None, -1

def adder(bits):
    c = Cells(); a = [c.inp('a%d' % i) for i in range(bits)]; b = [c.inp('b%d' % i) for i in range(bits)]; z = c.inp('z')
    carry = z; out = []
    for i in range(bits):
        x = c.XOR(a[i], b[i]); out.append(c.XOR(x, carry)); carry = c.OR(c.AND(a[i], b[i]), c.AND(x, carry))
    return c, out + [carry]

def t_logic(kind):
    wrong = 0; cases = 0; slow = 0; cells = 0
    if kind.startswith('adder'):
        bits = int(kind.split()[1]); c, outs = adder(bits); cells = len(c.rules)
        rng = random.Random(bits); pairs = [(x, y) for x in range(2 ** bits) for y in range(2 ** bits)] if bits <= 4 else [(rng.randrange(2 ** bits), rng.randrange(2 ** bits)) for _ in range(200)]
        for x, y in pairs:
            i = {'z': 0}; i.update({'a%d' % k: (x >> k) & 1 for k in range(bits)}); i.update({'b%d' % k: (y >> k) & 1 for k in range(bits)})
            o, t = c.run(i, outs); cases += 1; slow = max(slow, t)
            if o is None or sum(v << k for k, v in enumerate(o)) != x + y: wrong += 1
    else:
        c = Cells(); n = dict(parity=8, majority=3, mux=3, decoder=2, comparator=4, planted=2, half=2)[kind.split()[0]]
        ins = [c.inp('i%d' % k) for k in range(n)]
        if kind == 'half adder': outs = [c.XOR(ins[0], ins[1]), c.AND(ins[0], ins[1])]; want = lambda v: [v[0] ^ v[1], v[0] & v[1]]
        elif kind == 'parity of 8':
            p = ins[0]
            for k in ins[1:]: p = c.XOR(p, k)
            outs = [p]; want = lambda v: [sum(v) % 2]
        elif kind == 'majority of 3': outs = [c.OR(c.OR(c.AND(ins[0], ins[1]), c.AND(ins[1], ins[2])), c.AND(ins[0], ins[2]))]; want = lambda v: [1 if sum(v) >= 2 else 0]
        elif kind == 'mux 2 to 1': outs = [c.OR(c.AND(ins[0], c.NOT(ins[2])), c.AND(ins[1], ins[2]))]; want = lambda v: [v[1] if v[2] else v[0]]
        elif kind == 'decoder 2 to 4':
            n0, n1 = c.NOT(ins[0]), c.NOT(ins[1]); outs = [c.AND(n0, n1), c.AND(ins[0], n1), c.AND(n0, ins[1]), c.AND(ins[0], ins[1])]
            want = lambda v: [1 if k == v[0] + 2 * v[1] else 0 for k in range(4)]
        elif kind == 'comparator 2 bit equal': outs = [c.AND(c.NOT(c.XOR(ins[0], ins[2])), c.NOT(c.XOR(ins[1], ins[3])))]; want = lambda v: [1 if (v[0], v[1]) == (v[2], v[3]) else 0]
        elif kind == 'planted fault must be caught': outs = [c.XOR(ins[0], ins[1]), c.NOT(ins[0])]; want = lambda v: [v[0] ^ v[1], v[0] & v[1]]
        cells = len(c.rules)
        for m in range(2 ** n):
            v = [(m >> k) & 1 for k in range(n)]; o, t = c.run({'i%d' % k: v[k] for k in range(n)}, outs); cases += 1; slow = max(slow, t)
            if o != want(v): wrong += 1
    planted = kind.startswith('planted'); ok = (wrong > 0) if planted else (wrong == 0)
    return dict(question='Do cells run by one rule (lit unless both the cells it answers to were lit a tick earlier) make a correct "%s"?' % kind,
                did='built it from that one gate cell; set every input row (or 200 seeded rows); waited for the outputs to settle; read the output cells',
                numbers=dict(cells=cells, rows=cases, wrong=wrong, slowest_settle_tick=slow),
                observed=('%d of %d rows wrong' % (wrong, cases)) + (' (a fault was planted: the check must see it)' if planted else ''),
                result='CONFIRMED' if ok else 'REFUTED')


# ------------------------------------------------------------------ FEEDER PULSE
CANDIDATE = dict(r_ohm_per_km=0.164, x_ohm_per_km=0.080, kv=11.0, kw_per_home_after_diversity=1.5, power_factor=0.95,
                 charger_kw=7.0, charger_diversity=0.4, volts_band_low_pu=0.94, cable_rating_a=355)

def feeder(seed, size=40):
    """A root chosen by seed among the real places, its nearest `size` neighbours, joined by a minimum spanning tree."""
    P = points(); rng = random.Random(seed); root = rng.randrange(len(P))
    near = sorted(range(len(P)), key=lambda i: km(P[i], P[root]))[:size + 1]
    intree = {near[0]}; parent = {near[0]: None}; length = {}
    while len(intree) < len(near):
        best = None
        for i in near:
            if i in intree: continue
            for j in intree:
                d = km(P[i], P[j])
                if best is None or d < best[0]: best = (d, i, j)
        d, i, j = best; intree.add(i); parent[i] = j; length[i] = max(d, 0.05)      # never shorter than 50 m of cable
    homes = {i: rng.randint(50, 300) for i in near if parent[i] is not None}
    return near[0], parent, length, homes

def sweep(root, parent, length, homes, ev_share, c=CANDIDATE, tol=1e-9):
    """Forward-backward sweep, per phase, constant power loads. Returns volts (pu), section amps, losses, rounds."""
    vbase = c['kv'] * 1000 / math.sqrt(3); z = complex(c['r_ohm_per_km'], c['x_ohm_per_km'])
    kids = {}
    for i, p in parent.items():
        if p is not None: kids.setdefault(p, []).append(i)
    order = [root]
    for n in order: order += kids.get(n, [])
    tanphi = math.tan(math.acos(c['power_factor']))
    S = {}
    for i, h in homes.items():
        kw = h * c['kw_per_home_after_diversity'] + h * ev_share * c['charger_kw'] * c['charger_diversity']
        S[i] = complex(kw, kw * tanphi) * 1000 / 3            # volt amperes per phase
    V = {n: complex(vbase, 0) for n in order}; rounds = 0
    while True:
        rounds += 1
        I = {n: (S[n] / V[n]).conjugate() if n in S else 0j for n in order}          # what each place draws
        J = dict(I)
        for n in reversed(order):                                                   # PULSE ONE: currents sum back toward the root
            if parent[n] is not None: J[parent[n]] += J[n]
        newV = {root: complex(vbase, 0)}
        for n in order[1:]:                                                         # PULSE TWO: volts fall out from the root
            newV[n] = newV[parent[n]] - J[n] * z * length[n]
        step = max(abs(newV[n] - V[n]) for n in order); V = newV
        if step < tol or rounds > 200: break
    loss = sum(abs(J[n]) ** 2 * z.real * length[n] for n in order[1:]) * 3
    load = sum(S.values()).real * 3
    source = (V[root] * J[root].conjugate()).real * 3
    return V, J, loss, load, source, rounds, vbase

def t_feeder(seed, ev_share):
    root, parent, length, homes = feeder(seed)
    V, J, loss, load, source, rounds, vbase = sweep(root, parent, length, homes, ev_share)
    c = CANDIDATE
    vmin = min(abs(v) for v in V.values()) / vbase; imax = max(abs(J[n]) for n in parent if parent[n] is not None)
    # THE CHECKS THAT CAN FAIL: (1) it converged; (2) what leaves the source = what the homes take + what the cable burns;
    # (3) at every place, current in = current drawn + currents out (redone from the final volts, not reused)
    balance = abs(source - load - loss) / max(load, 1)
    worst_kcl = 0.0
    kids = {}
    for i, p in parent.items():
        if p is not None: kids.setdefault(p, []).append(i)
    z = complex(c['r_ohm_per_km'], c['x_ohm_per_km'])
    for n, p in parent.items():
        if p is None: continue
        flow_in = (V[p] - V[n]) / (z * length[n])
        worst_kcl = max(worst_kcl, abs(flow_in - J[n]) / max(abs(J[n]), 1e-9))
    ok = rounds <= 200 and balance < 1e-6 and worst_kcl < 1e-6
    trouble = []
    if vmin < c['volts_band_low_pu']: trouble.append('lowest voltage %.3f of nominal is under the %.2f band' % (vmin, c['volts_band_low_pu']))
    if imax > c['cable_rating_a']: trouble.append('heaviest section %.0f A is over the %d A cable rating' % (imax, c['cable_rating_a']))
    return dict(question='Feeder pulse, estimated feeder number %d (41 real substation places, tree assumed), %d%% of homes with a charger: does the sweep settle, and do the books balance?' % (seed, round(ev_share * 100)),
                did='two pulses per round: currents summed back to the root, volts dropped out from the root; then power in = load + loss, and current in = current out at every place, checked from the final volts',
                numbers=dict(places=len(parent), homes=sum(homes.values()), cable_km=round(sum(length.values()), 2), rounds=rounds,
                             load_kw=round(load / 1000, 1), loss_kw=round(loss / 1000, 2), lowest_volts_pu=round(vmin, 4), heaviest_section_a=round(imax, 1),
                             power_balance_error=float('%.2e' % balance), worst_current_law_error=float('%.2e' % worst_kcl)),
                observed=('settled in %d rounds; lowest voltage %.3f of nominal; heaviest section %.0f A; ' % (rounds, vmin, imax)) + ('; '.join(trouble) if trouble else 'inside band and rating'),
                assumed='tree, homes per substation, and every electrical figure are CANDIDATE estimates: ' + json.dumps(c, sort_keys=True),
                result='CONFIRMED' if ok else 'REFUTED')


# ------------------------------------------------------------------ the hundred, in order
def registry():
    R = []
    for s in ['sunflower', 'ring', 'two rings', 'orbit', 'square lattice', 'hexagonal lattice', 'spiral arms', 'busbar and feeders', 'random scatter', 'clock']:
        R.append(('ARRANGEMENTS', s, (t_arrangement, (s,))))
    for g in ['north', 'east', 'within 25 km of Charing Cross', 'north AND east', 'north OR east', 'NOT north',
              'De Morgan: NOT (north AND east) = NOT north OR NOT east', 'De Morgan: NOT (north OR east) = NOT north AND NOT east',
              'north AND NOT north is empty', 'inner OR NOT inner is everything']:
        R.append(('GATES', g, (t_gate, (g,))))
    for o, v, s2 in [('charing', 1, None), ('charing', 5, None), ('charing', 25, None), ('norwich', 1, None), ('norwich', 5, None), ('brighton', 5, None),
                     ('charing', 5, 'norwich'), ('charing', 5, 'brighton'), ('norwich', 5, 'brighton'), ('brighton', 1, 'norwich')]:
        R.append(('PULSES', '%s at %g km a tick%s' % (o, v, ' meeting ' + s2 if s2 else ''), (t_pulse, (o, v, s2))))
    for l in ['half adder', 'adder 2 bit', 'adder 4 bit', 'adder 8 bit', 'parity of 8', 'majority of 3', 'mux 2 to 1', 'decoder 2 to 4', 'comparator 2 bit equal', 'planted fault must be caught']:
        R.append(('LOGIC', l, (t_logic, (l,))))
    for seed in range(1, 21):
        for ev in (0.0, 0.3, 0.6):
            R.append(('FEEDER PULSE', 'feeder %d, %d%% chargers' % (seed, round(ev * 100)), (t_feeder, (seed, ev))))
    assert len(R) == 100, len(R)                       # the first hundred keep their numbers for ever
    import site_cases                                   # families added later are appended, never inserted: a number, once given, is permanent
    import cable_cases
    import energy_cases
    import traction_cases
    import national_cases
    return R + site_cases.registry() + cable_cases.registry() + energy_cases.registry() + traction_cases.registry() + national_cases.registry()

def run(n):
    family, name, (fn, args) = registry()[n - 1]
    rec = fn(*args); rec.update(n=n, family=family, name=name)
    rec['fingerprint'] = hashlib.sha256(json.dumps({k: rec[k] for k in ('n', 'family', 'name', 'numbers', 'result')}, sort_keys=True).encode()).hexdigest()
    return rec

Topo

A Python command-line tool in the bench folder of Faraday that reads cables, solar, transformers and substations.

storagefaraday / bench/topo.py · lines 1–200 of 200 · Entry point · pattern shard (shared by 5 files)

What it does
It loads cables, solar, transformers and substations. Defines 9 functions or classes, including mulberry32, nxt, network, solve, telling. Uses libraries argparse, heapq, json, math, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'grid-network'): 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: cables, solar, transformers, substations.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: Commands Build (faraday); Nightshift Workflow (faraday).
What it achieves
It is built from the mulberry32 step (`mulberry32`), the nxt step (`nxt`) and the network step (`network`). NETWORKS BY THE BILLION: different TOPOLOGIES, not one site with different numbers. It accepts `--seeds`, `--workers` and `--selftest`.
Why it matters
Imported by Commands Build. Run by Nightshift Workflow.
Application
faraday · bench · Python CLI
Uses
argparse, heapq, json, math, os, subprocess, sys, time
Used by
imported by Commands Build (import), run by Nightshift Workflow (workflow run)
Produces
mulberry32, network, solve, telling, shard, status, add, main
Defines here
mulberry32, nxt, network, solve, telling, shard, status, add, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/topo.py:1-200 · blob 906cf2f2a05210ecb73945f666b3face237249cb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""bench/topo.py - NETWORKS BY THE BILLION: different TOPOLOGIES, not one site with different numbers.

One seed = one generic private network behind one connection point (no real one): a star, a chain, a tree or sub-boards, 2 to 12
substations, solar on some, a generator somewhere, an export limit. x 18 operating cases (solar 0, half, full; generator off, on;
load 100, 60, 30 per cent). Solved by the two pulse sweep over ANY radial tree. EVERY CASE IS SOLVED TWICE: here, and by
bench/fire_topo.js (the code the Kuiper runs: `fire network {"seed":N,...}`), rebuilt from the seed alone.

A billion rows are not kept. Each shard keeps its counts and its MOST TELLING cases; topo_top.py merges those into the top 1,000
that become commands with sentences. Shards of 2,000 seeds (36,000 cases); resumable; plain Python and node.

  python bench/topo.py --seeds 56000000 --workers 16        # about a billion cases
  python bench/topo.py --selftest
"""
import argparse, heapq, json, math, os, subprocess, sys, time
from multiprocessing import Pool

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.environ.get('TOPO_OUT', r'E:\faraday-bench\topo')
PER_SHARD = 2000
C = dict(kv=11.0, grid_x_over_r=10.0, hv_cable_r=0.20, hv_cable_x=0.09, tx_z_pct=5.5, tx_x_over_r=5.0, load_pf=0.90, gen_pf=0.95, volts_high_pu=1.06, volts_low_pu=0.94)
KVA = (500, 800, 1000, 1600, 2000); LIMITS = (0, 50, 200, 500, 1000); GENS = (0, 250, 500, 1000); FAULT = (100, 150, 250, 350, 500)
SHAPES = ('star', 'chain', 'tree', 'sub-boards')
CASES = [(ps, g, ls) for ps in (0.0, 0.5, 1.0) for g in (0, 1) for ls in (1.0, 0.6, 0.3)]

def mulberry32(a):
    a &= 0xFFFFFFFF
    def nxt():
        nonlocal a
        a = (a + 0x6D2B79F5) & 0xFFFFFFFF
        t = a
        t = ((t ^ (t >> 15)) * (t | 1)) & 0xFFFFFFFF
        t ^= (t + (((t ^ (t >> 7)) * (t | 61)) & 0xFFFFFFFF)) & 0xFFFFFFFF
        return (t ^ (t >> 14)) & 0xFFFFFFFF
    return nxt

VARIANT = int(os.environ.get('TOPO_VARIANT', '0'))
START = int(os.environ.get('TOPO_START_SHARD', '0'))

def network(seed, variant=None):
    if variant is None: variant = VARIANT
    """Whole numbers until the last division, in a fixed order of draws: fire_topo.js makes the identical network."""
    g = mulberry32(seed * 2654435761 + 777); pick = lambda n: g() % n
    shape = pick(4); n = 2 + pick(11); fault = FAULT[pick(5)]; intake = (10 + pick(191)) / 100; limit = LIMITS[pick(5)]
    subs = []
    for k in range(1, n + 1):
        kva = KVA[pick(5)]; load = kva * (25 + pick(56)) // 100; km = (5 + pick(76)) / 100
        if k == 1 or shape == 0: parent = 0
        elif shape == 1: parent = k - 1 if pick(10) < 8 else 0
        elif shape == 2: parent = pick(k)
        else: parent = 0 if k <= 3 else 1 + pick(3)
        pv = kva * (30 + pick(121)) // 100 if pick(10) < 3 else 0
        subs.append(dict(n=k, kva=kva, load_kw=load, km=km, parent=parent, pv_kw=pv))
    gen = GENS[pick(4)]; gen_at = pick(n + 1)
    # THE SAME NETWORKS, ASKED IN A DIFFERENT WAY. 1: half as much solar again on every roof that has any. 2: a connection of half
    # the fault level (a weak grid). 3: every cable three times as long (a spread out site). 4: every transformer one size down the list.
    if variant == 1:
        for s in subs: s['pv_kw'] = s['pv_kw'] * 3 // 2
    elif variant == 2: fault = fault // 2
    elif variant == 3:
        intake = intake * 3
        for s in subs: s['km'] = s['km'] * 3
    elif variant == 4:
        for s in subs: s['kva'] = KVA[max(0, KVA.index(s['kva']) - 1)]
    return dict(seed=seed, shape=SHAPES[shape], fault_mva=fault, intake_km=intake, export_limit_kw=limit, generator_kw=gen, generator_at=gen_at, subs=subs)

def solve(net, pv_share, gen_on, load_share, tol=1e-9):
    c = C; vb = c['kv'] * 1000 / math.sqrt(3)
    zs = (c['kv'] ** 2) / net['fault_mva']; xr = c['grid_x_over_r']; rs = zs / math.sqrt(1 + xr * xr)
    cable = complex(c['hv_cable_r'], c['hv_cable_x'])
    Z = {'poc': complex(rs, rs * xr), 'board': cable * net['intake_km']}; parent = {'grid': None, 'poc': 'grid', 'board': 'poc'}; S = {}; kva = {}
    tanl = math.tan(math.acos(c['load_pf'])); tang = math.tan(math.acos(c['gen_pf']))
    gen = complex(net['generator_kw'], net['generator_kw'] * tang) if gen_on else 0j
    if gen_on and net['generator_at'] == 0: S['board'] = -gen * 1000 / 3
    for s in net['subs']:
        hv, lv = 'hv%d' % s['n'], 'lv%d' % s['n']
        parent[hv] = 'board' if s['parent'] == 0 else 'hv%d' % s['parent']; parent[lv] = hv
        Z[hv] = cable * s['km']
        zt = c['tx_z_pct'] / 100 * (c['kv'] ** 2) / (s['kva'] / 1000); txr = c['tx_x_over_r']; rt = zt / math.sqrt(1 + txr * txr)
        Z[lv] = complex(rt, rt * txr); kva[lv] = s['kva']
        kw = s['load_kw'] * load_share; p = complex(kw, kw * tanl) - complex(s['pv_kw'] * pv_share, 0)
        if gen_on and net['generator_at'] == s['n']: p -= gen
        S[lv] = p * 1000 / 3
    kids = {}
    for n, p in parent.items():
        if p is not None: kids.setdefault(p, []).append(n)
    order = ['grid']
    for n in order: order += kids.get(n, [])
    V = {n: complex(vb, 0) for n in order}; rounds = 0
    while True:
        rounds += 1
        J = {n: ((S[n] / V[n]).conjugate() if n in S else 0j) for n in order}
        for n in reversed(order):
            if parent[n] is not None: J[parent[n]] += J[n]
        nv = {'grid': complex(vb, 0)}
        for n in order[1:]: nv[n] = nv[parent[n]] - J[n] * Z[n]
        step = max(abs(nv[n] - V[n]) for n in order); V = nv
        if step < tol or rounds > 300: break
    s_poc = V['poc'] * J['poc'].conjugate() * 3
    loss = sum(abs(J[n]) ** 2 * Z[n].real for n in order[1:]) * 3
    net_p = sum(S.values()).real * 3; source = (V['grid'] * J['poc'].conjugate()).real * 3
    tx = max(abs(V[n] * J[n].conjugate() * 3) / 1000 / kva[n] * 100 for n in kva)
    # the busiest cable section, in amps: what a chain or a tree adds that a star never shows
    amps = max(abs(J[n]) for n in order[1:] if n not in kva)
    vm = [abs(V[n]) / vb for n in order]
    return dict(p=s_poc.real / 1000, q=s_poc.imag / 1000, loss=loss / 1000, vmax=max(vm), vmin=min(vm), tx=tx, amps=amps, rounds=rounds,
                balance=abs(source - net_p - loss) / max(abs(net_p), 1.0))

def telling(net, case, r):
    """How telling is this case, by kind. Bigger is more telling. Only converged cases."""
    ps, g, ls = case; out = []; lim = net['export_limit_kw']; export = max(0.0, -r['p'])
    if ps > 0 and lim > 0 and export > 0: out.append(('export on the line', -abs(export - lim) / lim))
    if r['vmax'] > 1.03: out.append(('volts high on the line', -abs(r['vmax'] - C['volts_high_pu'])))
    if r['vmin'] < 0.97: out.append(('volts low on the line', -abs(r['vmin'] - C['volts_low_pu'])))
    out.append(('transformer on the line', -abs(r['tx'] - 100.0) / 100))
    inside = export <= lim and r['vmax'] <= C['volts_high_pu'] and r['vmin'] >= C['volts_low_pu'] and r['tx'] <= 100
    if inside and ps == 1.0:
        pv = sum(s['pv_kw'] for s in net['subs']); load = sum(s['load_kw'] for s in net['subs']) * ls
        if pv > 0: out.append(('most solar inside every limit', pv / max(load, 1.0)))
    return out

def shard(i):
    base = os.path.join(OUT, 'shards', 't%07d' % i); done = base + '.json'
    if os.path.exists(done): return json.load(open(done))
    t0 = time.time(); rows = []; n_ok = 0; flags = [0, 0, 0, 0]; by_shape = {}; tops = {}
    for seed in range(i * PER_SHARD, (i + 1) * PER_SHARD):
        net = network(seed); lim = net['export_limit_kw']
        for ci, case in enumerate(CASES):
            r = solve(net, *case); ok = r['rounds'] <= 300 and r['balance'] < 1e-6; n_ok += ok
            f = (1 if max(0.0, -r['p']) > lim else 0) | (2 if r['vmax'] > C['volts_high_pu'] else 0) | (4 if r['vmin'] < C['volts_low_pu'] else 0) | (8 if r['tx'] > 100 else 0)
            for b in range(4): flags[b] += (f >> b) & 1
            sh = by_shape.setdefault(net['shape'], [0, 0]); sh[0] += 1; sh[1] += 1 if (ok and f == 0) else 0
            rows.append('%d,%d,%.12g,%.12g,%.12g,%.12g,%.12g,%.12g,%.12g,%d' % (seed, ci, r['p'], r['q'], r['loss'], r['vmax'], r['vmin'], r['tx'], r['amps'], r['rounds']))
            if ok:
                for kind, score in telling(net, case, r):
                    h = tops.setdefault(kind, [])
                    item = (score, seed, ci, round(r['p'], 1), round(r['vmax'], 4), round(r['vmin'], 4), round(r['tx'], 1), f)
                    if len(h) < 40: heapq.heappush(h, item)
                    elif item > h[0]: heapq.heapreplace(h, item)
    csv = base + '.csv'
    with open(csv, 'w', newline='\n') as fh: fh.write('seed,case,p_kw,q_kvar,loss_kw,vmax_pu,vmin_pu,worst_tx_pct,busiest_amps,rounds\n' + '\n'.join(rows) + '\n')
    try:
        cp = subprocess.run(['node', os.path.join(HERE, 'topo_check.mjs'), csv, str(VARIANT)], capture_output=True, text=True, timeout=900)
        check = json.loads(cp.stdout.strip().splitlines()[-1]) if cp.stdout.strip() else dict(error=(cp.stderr or 'no output')[:300])
    except Exception as e:
        check = dict(error=str(e)[:300])
    if not check.get('differed') and 'error' not in check: os.remove(csv)       # a shard that was matched in full is not kept row by row; one that differs IS kept
    out = dict(shard=i, cases=len(rows), confirmed=n_ok, export_over=flags[0], volts_high=flags[1], volts_low=flags[2], tx_over=flags[3], by_shape=by_shape,
               tops={k: sorted(v, reverse=True) for k, v in tops.items()}, seconds=round(time.time() - t0, 2), check=check)
    with open(done + '.tmp', 'w') as fh: json.dump(out, fh)
    os.replace(done + '.tmp', done)
    return out

def status(tot, n_done, n_all, t0, note):
    el = time.time() - t0
    lines = ['# TOPO STATUS  ' + time.strftime('%Y-%m-%d %H:%M:%S'), '',
             '%d of %d shards; %s cases solved in Python; %s a second this run' % (n_done, n_all, format(tot['cases'], ','), format(int(tot['run_cases'] / el) if el > 0 else 0, ',')),
             'CONFIRMED %s, REFUTED %s (the sweep did not converge or power did not balance)' % (format(tot['confirmed'], ','), format(tot['cases'] - tot['confirmed'], ',')),
             'SECOND OPINION (JavaScript, the code the Kuiper runs): matched %s, DIFFERED %s, stopped a round apart %s, neither converged %s, shards the check could not run %d' % (
                 format(tot['matched'], ','), format(tot['differed'], ','), format(tot['rounds_differ'], ','), format(tot['both_refuse'], ','), tot['errors']),
             'Over a limit: export %s; volts high %s; volts low %s; a transformer %s' % tuple(format(tot[k], ',') for k in ('export_over', 'volts_high', 'volts_low', 'tx_over')),
             'Inside every limit, by shape: ' + '; '.join('%s %s of %s' % (k, format(v[1], ','), format(v[0], ',')) for k, v in sorted(tot['by_shape'].items())), note]
    if tot['differed'] or tot['errors']: lines.append('ACT: DIFFERS or ERROR in shards ' + ', '.join(map(str, tot['bad'][:12])))
    with open(os.path.join(OUT, 'STATUS.md'), 'w') as fh: fh.write('\n'.join(lines) + '\n')
    return lines

def add(tot, d, this_run):
    tot['cases'] += d['cases']; tot['confirmed'] += d['confirmed']
    if this_run: tot['run_cases'] += d['cases']
    for k in ('export_over', 'volts_high', 'volts_low', 'tx_over'): tot[k] += d[k]
    ch = d['check']
    for k in ('matched', 'differed', 'rounds_differ', 'both_refuse'): tot[k] += ch.get(k, 0)
    if 'error' in ch: tot['errors'] += 1
    if 'error' in ch or ch.get('differed'): tot['bad'].append(d['shard'])
    for k, v in d['by_shape'].items():
        s = tot['by_shape'].setdefault(k, [0, 0]); s[0] += v[0]; s[1] += v[1]

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('--seeds', type=int, default=200000); ap.add_argument('--workers', type=int, default=16); ap.add_argument('--selftest', action='store_true')
    a = ap.parse_args(); os.makedirs(os.path.join(OUT, 'shards'), exist_ok=True)
    if a.selftest:
        n1 = network(11); assert n1 == network(11) and network(12) != n1
        r = solve(n1, 1.0, 1, 0.3); assert r['rounds'] <= 300 and r['balance'] < 1e-6, r
        print('selftest ok:', n1['shape'], len(n1['subs']), 'substations; p = %.3f kW' % r['p']); return
    n = (a.seeds + PER_SHARD - 1) // PER_SHARD; t0 = time.time()
    tot = dict(cases=0, run_cases=0, confirmed=0, export_over=0, volts_high=0, volts_low=0, tx_over=0, matched=0, differed=0, rounds_differ=0, both_refuse=0, errors=0, bad=[], by_shape={})
    todo = []
    for i in range(START, START + n):
        p = os.path.join(OUT, 'shards', 't%07d.json' % i)
        if os.path.exists(p): add(tot, json.load(open(p)), False)
        else: todo.append(i)
    k = n - len(todo); last = 0
    with Pool(a.workers) as pool:
        for d in pool.imap_unordered(shard, todo, chunksize=1):
            add(tot, d, True); k += 1
            if time.time() - last > 20: status(tot, k, n, t0, 'RUNNING'); last = time.time()
    print('\n'.join(status(tot, k, n, t0, 'FINISHED')))

if __name__ == '__main__':
    main()

Topo Check

A JavaScript module in the bench folder of Faraday.

ingestfaraday / bench/topo_check.mjs · lines 1–22 of 22 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries node:module, node:fs. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'grid-network'): 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.
Inputs & outputs
In: command-line arguments.
What it achieves
One shard in; every network rebuilt from its seed by `fire_topo.js` (the code the Kuiper runs), every case solved again, every number compared.
Why it matters
No other file in the estate was found to import it.
Application
faraday · bench · JavaScript module
Uses
Fire (require), Fire Topo (require), node:module, node:fs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/topo_check.mjs:1-22 · blob 7721a73c205786986513860b1d4cbead95dbf2dd · 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: unreached_review
// bench/topo_check.mjs - THE SECOND OPINION for bench/topo.py. One shard in; every network rebuilt from its seed by fire_topo.js
// (the code the Kuiper runs), every case solved again, every number compared. Same rounds: 1e-9 relative. A round apart: 1e-6,
// counted. Neither converged: counted as both_refuse, no numbers compared. Last line printed is one JSON object.
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const require = createRequire(import.meta.url);
const FIRE = require('./fire.js'); require('./fire_topo.js');
const { network, solve, CASES } = FIRE.topo;
const lines = readFileSync(process.argv[2], 'utf8').split('\n').filter(Boolean).slice(1);
let matched = 0, differed = 0, roundsDiffer = 0, bothRefuse = 0, last = -1, net = null; const first = [];
for (const l of lines) {
  const [seed, ci, p, q, loss, vmax, vmin, tx, amps, rounds] = l.split(',').map(Number);
  if (seed !== last) { net = network(seed, +(process.argv[3] || 0)); last = seed; }
  const c = CASES[ci], r = solve(net, c[0], !!c[1], c[2]);
  if (r.rounds > 300 && rounds > 300) { bothRefuse++; matched++; continue; }
  const tol = r.rounds === rounds ? 1e-9 : 1e-6, got = [r.p, r.q, r.loss, r.vmax, r.vmin, r.tx, r.amps], want = [p, q, loss, vmax, vmin, tx, amps];
  const bad = got.findIndex((g, i) => !(+g.toPrecision(12) === want[i] || Math.abs(g - want[i]) <= tol * Math.max(1, Math.abs(g), Math.abs(want[i]))));
  if (bad >= 0) { differed++; if (first.length < 3) first.push({ seed, case: ci, which: bad, js: got[bad], py: want[bad], js_rounds: r.rounds, py_rounds: rounds }); }
  else { matched++; if (r.rounds !== rounds) roundsDiffer++; }
}
console.log(JSON.stringify({ rows: lines.length, matched, differed, rounds_differ: roundsDiffer, both_refuse: bothRefuse, first }));
process.exit(differed ? 1 : 0);

Traction Cases

A Python module in the bench folder of Faraday that works with solar, transformers and substations.

transformfaraday / bench/traction_cases.py · lines 1–45 of 45 · Entry point · pattern t_known (shared by 3 files)

What it does
It calculates solar, transformers and substations. Defines t_chain, t_scale, t_known, registry. Uses libraries json.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 22kV (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: solar, transformers, substations, 22kV.
Inputs & outputs
Voltage levels named: 22kV.
Downstream impact
Used directly by 1 file: Tests (faraday). Reached from 1 other entry point, including One (faraday).
What it achieves
It is built from the t chain helper (`t_chain`), the t scale helper (`t_scale`) and the t known helper (`t_known`). DC TRACTION: solar fed straight into a metro's direct current traction system, as sums that can fail. Its code works with 80 GWh, 64 MW and 100 GWh.
Why it matters
Checked by Tests.
Application
faraday · bench · Python module
Uses
json
Used by
imported by Tests (import)
Produces
t_chain, t_scale, t_known, registry
Defines here
t_chain, t_scale, t_known, registry
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/traction_cases.py:1-45 · blob 9c0205f684882e558f20553b8679c89b7e6244b9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/traction_cases.py - DC TRACTION: solar fed straight into a metro's direct current traction system, as sums that can fail.

GENERIC: the round figures of a published article on a large metro system, which cites a public freedom of information response:
about 1,216 GWh a year, 80 to 85 per cent of it traction, about 300 traction substations turning 11 to 22 kV alternating current into a
nominal 630 V direct current rail; a plan for 64 MW of solar giving about 80 GWh a year. Converter efficiencies are CANDIDATES.
The point: solar makes direct current and the trains use direct current; going through alternating current on the way loses energy twice.
"""
import json

def t_chain(inverter, transformer, rectifier, dcdc):
    ac = inverter * transformer * rectifier; saving = dcdc - ac
    inputs = dict(inverter=inverter, transformer=transformer, rectifier=rectifier, dc_converter=dcdc)
    return dict(question='Of each unit of solar, how much reaches the rail by the usual route (inverter, transformer, rectifier) and how much by one direct current converter?',
                sentence='DC traction: the two routes compared', command='fire dc-traction-chain ' + json.dumps(inputs, sort_keys=True), did='multiplied the efficiencies along each route',
                numbers=dict(reaches_rail_by_ac_route_pct=round(ac * 100, 2), reaches_rail_by_dc_route_pct=round(dcdc * 100, 2), saved_pct_of_the_solar=round(saving * 100, 2)),
                observed='%.1f%% arrives by the usual route, %.1f%% by the direct route: %.1f%% of the SOLAR is saved' % (ac * 100, dcdc * 100, saving * 100),
                assumed='converter efficiencies are CANDIDATE round figures', result='CONFIRMED' if 0 < saving < 0.2 else 'REFUTED')

def t_scale(solar_gwh, saving_share):
    total, traction_share, subs = 1216.0, 0.825, 300
    traction = total * traction_share; saved = solar_gwh * saving_share
    return dict(question='With %g GWh a year of solar fed on the direct current side and %g%% of it saved, how much energy is that, and against what?' % (solar_gwh, saving_share * 100),
                sentence='DC traction: %g GWh of solar, %g%% saved' % (solar_gwh, saving_share * 100), command='fire dc-traction-scale ' + json.dumps(dict(solar_gwh=solar_gwh, saving_share=saving_share), sort_keys=True),
                did='traction energy = total x share; saving = solar x share saved; average load per substation = traction / substations / hours',
                numbers=dict(traction_gwh=round(traction, 1), saved_gwh=round(saved, 2), solar_share_of_traction_pct=round(solar_gwh / traction * 100, 1), average_kw_per_substation=round(traction * 1e6 / subs / 8760)),
                observed='saves %.1f GWh a year; the solar is %.1f%% of traction energy; an average traction substation carries about %.0f kW' % (saved, solar_gwh / traction * 100, traction * 1e6 / subs / 8760),
                assumed='traction share 82.5%, the middle of the published 80 to 85%', result='CONFIRMED')

def t_known():
    cf = 80.0 / (64 * 8.76); full = 1216 * 0.825
    return dict(question='Do the published sums hold, and what do they apply to?', sentence='DC traction: the known answers', command='fire dc-traction-known {}', did='divided and multiplied',
                numbers=dict(capacity_factor_pct_implied_by_64_mw_and_80_gwh=round(cf * 100, 1), saving_gwh_if_all_traction_were_dc_fed_low=round(full * 0.05), saving_gwh_if_all_traction_were_dc_fed_high=round(full * 0.10),
                             saving_gwh_on_80_gwh_of_solar_low=round(80 * 0.05, 1), saving_gwh_on_80_gwh_of_solar_high=round(80 * 0.10, 1)),
                observed='50 to 100 GWh a year is 5 to 10%% of ALL traction energy (%.0f GWh): it is the prize if every unit came in on the direct current side. On 80 GWh of solar the same 5 to 10%% is 4 to 8 GWh. And 80 GWh from 64 MW implies a capacity factor of %.1f%%, above the 10 to 11%% usual for the city: check the yield.' % (full, cf * 100),
                assumed='none', result='CONFIRMED')

def registry():
    R = [('DC TRACTION', 'the known answers', (t_known, ()))]
    for inv in (0.97, 0.98):
        for rec in (0.95, 0.97):
            for dc in (0.97, 0.985): R.append(('DC TRACTION', 'routes inv %g rect %g dc %g' % (inv, rec, dc), (t_chain, (inv, 0.99, rec, dc))))
    for g in (80.0, 160.0, 400.0):
        for s in (0.05, 0.075, 0.10): R.append(('DC TRACTION', '%g GWh at %g%%' % (g, s * 100), (t_scale, (g, s))))
    return R

E036

A JavaScript module in the experiments folder of Faraday.

otherfaraday / experiments/e036.mjs · lines 1–29 of 29 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
36: a ring of 3, 5, 7 NOT cells.
Why it matters
No other file in the estate was found to import it.
Application
faraday · experiments · JavaScript module
Uses
Faraday — Experiments (import)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 experiments/e036.mjs:1-29 · blob fc2421276fd92ca2cab44f0eadf90a8d28849901 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// 36: a ring of 3, 5, 7 NOT cells. Is the period 2 x cells ticks?
import { builder, compile, read } from './lib.mjs';

export default async function () {
  const lines = []; let allExpected = true;
  for (const n of [3, 5, 7]) {
    const b = builder(36000 + n * 100);
    const keys = Array.from({ length: n }, () => b.fresh());
    keys.forEach((k, i) => b.program.push({ key: k, gate: [keys[(i + n - 1) % n], keys[(i + n - 1) % n]] }));
    const rules = compile(b.program);
    const seq = [];
    for (let t = 0; t < 8 * n; t++) seq.push(read(rules, {}, keys, t).join(''));
    let period = -1;
    for (let p = 1; p <= 4 * n && period < 0; p++) {
      let ok = true;
      for (let t = 2 * n; t + p < seq.length; t++) if (seq[t] !== seq[t + p]) { ok = false; break; }
      if (ok) period = p;
    }
    if (period !== 2 * n) allExpected = false;
    lines.push(`${n} cells: period ${period} (expected ${2 * n}); first ticks ${seq.slice(0, 5).join(' ')}`);
  }
  return {
    did: 'Built rings of 3, 5 and 7 cells, each lit unless the one before it was lit a tick earlier. No inputs. Read every cell for 8 x cells ticks and found the shortest repeat.',
    observed: lines.join('; '),
    shows: allExpected ? 'The ring oscillates with period twice its length.'
      : 'It does not. Every cell starts HOME at tick 0, so they all see the same thing and all flip together: the ring beats as one, period 2, whatever its length. A travelling wave needs the symmetry broken by an input.',
    result: allExpected ? 'CONFIRMED' : 'REFUTED'
  };
}

E037

A JavaScript module in the experiments folder of Faraday.

otherfaraday / experiments/e037.mjs · lines 1–22 of 22 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
37: a two to one selector.
Why it matters
No other file in the estate was found to import it.
Application
faraday · experiments · JavaScript module
Uses
Faraday — Experiments (import)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 experiments/e037.mjs:1-22 · blob 2308995c9a661f11787cba749805c7f3c0454e0e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// 37: a two to one selector. Does the output follow the chosen input for all 8 rows?
import { builder, compile, read, settles } from './lib.mjs';

export default async function () {
  const b = builder(37000);
  const A = b.input('a'), B = b.input('b'), S = b.input('s');
  const out = b.nand(b.nand(A, b.not(S)), b.nand(B, S));      // s = 0 gives a, s = 1 gives b
  const rules = compile(b.program);
  let right = 0; const wrong = []; let worst = 0;
  for (let row = 0; row < 8; row++) {
    const sch = { a: row & 1, b: (row >> 1) & 1, s: (row >> 2) & 1 };
    const at = settles(rules, sch, [out]); worst = Math.max(worst, at);
    const got = read(rules, sch, [out], at + 8)[0], want = sch.s ? sch.b : sch.a;
    if (at >= 0 && got === want) right++; else wrong.push(JSON.stringify(sch) + ' gave ' + got);
  }
  return {
    did: 'Built the selector from four gate cells. Set each of the 8 input rows, waited for the output cell to settle, read it.',
    observed: `${right} of 8 rows right; ${b.program.length} cells; settles by tick ${worst}` + (wrong.length ? '; wrong: ' + wrong.join(', ') : ''),
    shows: right === 8 ? 'One cell can choose which of two others is passed on: a selection made by the dots themselves.' : 'The selector as built is wrong.',
    result: right === 8 ? 'CONFIRMED' : 'REFUTED'
  };
}

E038

A JavaScript module in the experiments folder of Faraday.

otherfaraday / experiments/e038.mjs · lines 1–31 of 31 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
38: a four bit comparator. Is "A greater than B" right for all 256 pairs?
Why it matters
No other file in the estate was found to import it.
Application
faraday · experiments · JavaScript module
Uses
Faraday — Experiments (import)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 experiments/e038.mjs:1-31 · blob c57c4db5cc5088183162501b9780131337c6cb1f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// 38: a four bit comparator. Is "A greater than B" right for all 256 pairs?
import { builder, compile, read, settles } from './lib.mjs';

export default async function () {
  const b = builder(38000);
  const a = [], bb = [];
  for (let i = 0; i < 4; i++) a.push(b.input('a' + i));
  for (let i = 0; i < 4; i++) bb.push(b.input('b' + i));
  const zero = b.input('zero');
  // from the lowest bit up: greater = (a and not b) or (same and greater so far)
  let g = zero;
  for (let i = 0; i < 4; i++) {
    const gt = b.and(a[i], b.not(bb[i])), same = b.not(b.xor(a[i], bb[i]));
    g = b.or(gt, b.and(same, g));
  }
  const rules = compile(b.program);
  let right = 0, worst = 0; const wrong = [];
  for (let x = 0; x < 16; x++) for (let y = 0; y < 16; y++) {
    const sch = { zero: 0 };
    for (let i = 0; i < 4; i++) { sch['a' + i] = (x >> i) & 1; sch['b' + i] = (y >> i) & 1; }
    const at = settles(rules, sch, [g]); worst = Math.max(worst, at);
    const got = read(rules, sch, [g], at + 8)[0];
    if (at >= 0 && got === (x > y ? 1 : 0)) right++; else if (wrong.length < 5) wrong.push(x + '>' + y + ' gave ' + got);
  }
  return {
    did: 'Built the comparator from gate cells only. Set every pair of numbers from 0 to 15, waited for the output cell to settle, read it.',
    observed: `${right} of 256 pairs right; ${b.program.length} cells; slowest settles at tick ${worst}` + (wrong.length ? '; wrong: ' + wrong.join(', ') : ''),
    shows: right === 256 ? 'The dots can decide which of two numbers is larger.' : 'The comparator as built is wrong.',
    result: right === 256 ? 'CONFIRMED' : 'REFUTED'
  };
}