GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / lidar / src

Test Cable Sweep and 4 more files

A test in the tests folder of LiDAR that checks LiDAR Cable Sweep. It is built from the ground step (`ground`), the grid step (`grid`) and the routes step (`routes`).

590 lines of JavaScript and Python from lidar, seed-data, in 5 files. Topic: Cables and conductors. Section 35 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. LiDAR Cable Sweep electrical · lidar / src/cable_sweep.py lines 358–454
  2. Test Cable Sweep test · lidar / tests/test_cable_sweep.py lines 1–174
  3. Baseline transform · seed-data / experiments/economical-seeds/next-invention/cable-screen/baseline.mjs lines 1–124
  4. Baseline Test test · seed-data / experiments/economical-seeds/next-invention/cable-screen/baseline.test.mjs lines 1–97
  5. Benchmark storage · seed-data / experiments/economical-seeds/next-invention/cable-screen/benchmark.mjs lines 1–98

LiDAR Cable Sweep

A Python command-line tool that reads cable sweep receipt, cables and 132kV, using SHA-256. It loads cables (`load_cables`), routes meta (`route_meta`) and writes receipt (`write_receipt`).

electricallidar / src/cable_sweep.py · lines 358–454 of 454 (continued from section 34) · Entry point · pattern ground_from (shared by 2 files)

What it does
It loads cable sweep receipt, cables and 132kV. Defines 21 functions or classes, including to_host, Ground, __init__, h, ground_from. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): 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, 132kV, 33kV.
Inputs & outputs
In: JSON file cable_sweep_receipt.json; JSON file cables.json; JSON file source.json; command-line arguments. Voltage levels named: 132kV, 33kV.
Downstream impact
Used directly by 1 file: Test Cable Sweep (lidar).
What it achieves
How long is a buried cable over real ground, counted two ways? Its code works with 132 kV and 33 kV. It accepts `--tiles`, `--seed` and `--routes`.
Why it matters
Checked by Test Cable Sweep.
Application
lidar · src · Python CLI
Uses
argparse, hashlib, json, math, os, sys, time, numpy
Used by
imported by Test Cable Sweep (sys.path import)
Produces
to_host, Ground, ground_from, min_radius, plan, arc_point, ragged, electron, crossings, positron, draw, pair
Defines here
route_meta, write_receipt, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 src/cable_sweep.py:358-454 · blob 2924b82b1abbb83c7f033d20debe2afaaea53b9c · 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: unknown
    n = len(C["kv"])
    # CPU witness: the first routes, both channels, NumPy only
    Gc = ground_from(tiles_dir, np)
    Wr = pair(first, Gc)
    wd = np.concatenate([np.abs(Wr["e3"] - C["e3"][:witness]) / C["e3"][:witness],
                         np.abs(Wr["p3"] - C["p3"][:witness]) / C["p3"][:witness]])
    wit = dict(routes=int(len(Wr["e3"])), photons=int((wd > WIT_TOL).sum()), max_rel=float(wd.max()), tol=WIT_TOL)
    photons = int((C["rel"] > TOL).sum())
    plan_rel = np.abs(C["c2"] - C["L2d"]) / C["L2d"]
    q = lambda v: [round(float(x), 6) for x in np.percentile(v, [0, 5, 25, 50, 75, 95, 100])] if len(v) else []
    extra = {}
    for kv in (33, 132):
        m = C["kv"] == kv
        L2, L3 = C["L2d"][m], C["p3"][m]
        extra[f"{kv}kV"] = dict(
            routes=int(m.sum()), plan_km=round(float(L2.sum()) / 1000, 4), cable_3d_km=round(float(L3.sum()) / 1000, 4),
            extra_m_per_km=round(float((L3 - L2).sum() / L2.sum() * 1000), 4),
            extra_pct_percentiles_0_5_25_50_75_95_100=q(100 * (L3 - L2) / L2),
            extra_m_percentiles_0_5_25_50_75_95_100=q(L3 - L2),
            radius_violation_routes=int((C["nviol"][m] > 0).sum()), bent_routes=int((C["nb"][m] > 0).sum()))
    vr = C["nviol"] > 0
    worst = sorted(meta, key=lambda d: -d["rel"])[:KEEP]
    return {
        "kind": "cable length sweep pair", "seed": seed, "device": device,
        "script_sha256": hashlib.sha256(open(__file__, "rb").read()).hexdigest(),
        "source": {"shape": [G.ny, G.nx], "origin_e_m": G.oe, "origin_n_m": G.on, "spacing_m": G.sp},
        "bend_rules": {f"{kv}kV": rule[kv] for kv in (33, 132)},
        "cables_json_sha256": hashlib.sha256(json.dumps(cables, sort_keys=True).encode()).hexdigest(),
        "method": {"electron": f"3D chords of samples every <= {DS_E} m of chainage on the bilinear ground",
                   "positron": "analytic plan length + vertical correction, pieces cut at grid lines, "
                               "closed form on straights, 6-point Gauss-Legendre on arcs",
                   "tolerance_rel": TOL,
                   "routes_drawn": "0-4 bends uniform; legs log-uniform 3-300 m; turns 5-150 deg either way; "
                                   "33/132 kV half each; each corner asks for the rule radius"},
        "counts": {"routes": n, "by_bends": {str(b): int((C["nb"] == b).sum()) for b in range(NB + 1)},
                   "electron_samples": samples, "positron_intervals": intervals, "stopped_by": stopped},
        "disagreement": {"photons": photons, "max_rel": float(C["rel"].max()), "median_rel": float(np.median(C["rel"])),
                         "worst": worst},
        "plan_check": {"max_rel_chords_vs_analytic": float(plan_rel.max()), "median_rel": float(np.median(plan_rel))},
        "bend_radius": {"routes_with_violation": int(vr.sum()), "bent_routes": int((C["nb"] > 0).sum()),
                        "bends_below_min": int(C["nviol"].sum()), "bends_total": int(C["nb"].sum()),
                        "smallest_fitted_radius_m": float(C["rmin"][np.isfinite(C["rmin"])].min()) if np.isfinite(C["rmin"]).any() else None},
        "extra_3d_over_plan": extra,
        "witness": wit, "photons_total": photons + wit["photons"],
        "bounds": {"routes": routes, "seconds": seconds, "batch": batch},
        "wall_s": round(time.perf_counter() - t0, 3),
    }


def route_meta(D, R, i, G):
    nb = int((D["turns"][i] != 0).sum())
    return dict(start_e=round(float(D["x0"][i] + G.oe), 3), start_n=round(float(D["y0"][i] + G.on), 3),
                heading_deg=round(math.degrees(D["h0"][i]) % 360, 3), kv=int(D["kv"][i]),
                legs_m=[round(float(v), 3) for v in D["legs"][i][:nb + 1]],
                turns_deg=[round(math.degrees(v), 3) for v in D["turns"][i][:nb]],
                fitted_radius_m=[round(float(v), 4) for v in R["r"][i][:nb]],
                plan_m=round(float(R["P"]["L2d"][i]), 4), electron_m=round(float(R["e3"][i]), 6),
                positron_m=round(float(R["p3"][i]), 6))


def write_receipt(tiles_dir, r):
    body = (json.dumps(r, indent=1, sort_keys=True) + "\n").encode()
    path = os.path.join(tiles_dir, RECEIPT)
    with open(path, "wb") as f:       # bytes: LF on every platform
        f.write(body)
    return path, hashlib.sha256(body).hexdigest()


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--tiles", required=True)
    ap.add_argument("--seed", type=int, default=SEED)
    ap.add_argument("--routes", type=int, default=40000)
    ap.add_argument("--seconds", type=float, default=60.0)
    ap.add_argument("--batch", type=int, default=2000)
    ap.add_argument("--cables", default=CABLES)
    ap.add_argument("--cpu", action="store_true")
    a = ap.parse_args(argv)
    r = sweep(a.tiles, a.seed, a.routes, a.seconds, a.batch, use_gpu=not a.cpu, cables_path=a.cables)
    path, sha = write_receipt(a.tiles, r)
    c, d, b = r["counts"], r["disagreement"], r["bend_radius"]
    print(f"{c['routes']} routes {c['by_bends']} on {r['device']} in {r['wall_s']} s, stopped by {c['stopped_by']}")
    for kv, rr in r["bend_rules"].items():
        print(f"  {kv}: R = {rr['multiple_of_od']} x {rr['od_mm']} mm = {rr['radius_m']:.3f} m, depth {rr['depth_m']} m")
    print(f"photons {d['photons']} (> {TOL:.1%}), max rel {d['max_rel']:.2e}, median {d['median_rel']:.2e}; "
          f"plan chords vs analytic max {r['plan_check']['max_rel_chords_vs_analytic']:.2e}")
    print(f"bends below min radius: {b['bends_below_min']} of {b['bends_total']} in {b['routes_with_violation']} routes")
    for kv, e in r["extra_3d_over_plan"].items():
        print(f"  {kv}: {e['plan_km']} km plan -> {e['cable_3d_km']} km 3D, +{e['extra_m_per_km']} m/km, "
              f"% p50/p95/max {e['extra_pct_percentiles_0_5_25_50_75_95_100'][3:4] + e['extra_pct_percentiles_0_5_25_50_75_95_100'][5:]}")
    print(f"witness {r['witness']['routes']} routes, photons {r['witness']['photons']} (max {r['witness']['max_rel']:.1e})")
    print(f"receipt {path} sha256 {sha}")
    return 0 if r["photons_total"] == 0 else 1


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

Test Cable Sweep

A test in the tests folder of LiDAR that checks LiDAR Cable Sweep. It is built from the ground step (`ground`), the grid step (`grid`) and the routes step (`routes`).

testlidar / tests/test_cable_sweep.py · lines 1–174 of 174 · Entry point · pattern test_bounded_by_seconds (shared by 3 files)

What it does
It tests cables. Defines 12 functions or classes, including ground, grid, routes, close, test_min_radius_rule. Uses libraries inspect, json, math, os, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): 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, 132kV, 33kV.
Inputs & outputs
Out: JSON file source.json. Voltage levels named: 132kV, 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `src/cable_sweep.py` on synthetic ground with known lengths. Its code works with 132 kV and 33 kV. It writes `source.json`.
Why it matters
Guards the behaviour of LiDAR Cable Sweep.
Application
lidar · tests · test
Uses
LiDAR Cable Sweep (sys.path import), inspect, json, math, os, pathlib, sys, tempfile, traceback
Used by
none found
Produces
ground, grid, routes, close, test_min_radius_rule, test_flat_plan_lengths, test_plane_straight_and_arc, test_ridge_kink_on_grid_line, test_short_legs_shrink_fillet, hilly, test_sweep_hilly, test_bounded_by_seconds
Defines here
ground, grid, routes, close, test_min_radius_rule, test_flat_plan_lengths, test_plane_straight_and_arc, test_ridge_kink_on_grid_line, test_short_legs_shrink_fillet, hilly, test_sweep_hilly, test_bounded_by_seconds
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 tests/test_cable_sweep.py:1-174 · blob dce4b5f8fccd6208f0a8093ec0a764a7538cf6c3 · 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: unknown
# SPDX-License-Identifier: Apache-2.0
"""Tests for src/cable_sweep.py on synthetic ground with known lengths.

Flat ground: 3D = plan = legs - 2 R tan(theta/2) + R theta a bend. A plane of gradient g along a
straight: L sqrt(1 + g^2). A ridge |x - c| kinked on a grid line: each flank exact. Both channels
must hit the known length and each other; short legs must shrink the fillet and be counted.

    E:/swarm/gpu-bench/venv/Scripts/python.exe lidar/tests/test_cable_sweep.py
"""
import inspect, json, math, os, pathlib, sys, tempfile, traceback
import numpy as np

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
import cable_sweep as cs  # noqa: E402
Ground = cs.Ground

XPS = [np] + ([cs.cp] if cs.cp is not None else [])
OE, ON = 400000.0, 200000.0
CABLES = {"rules": [
    {"voltage_kv": 33, "construction": "a", "when": "installation", "multiple_of_od": 20, "source": "t"},
    {"voltage_kv": 33, "construction": "a", "when": "final", "multiple_of_od": 40, "source": "t"},
    {"voltage_kv": 132, "construction": "b", "when": "installation", "multiple_of_od": 35, "source": "t"},
    {"voltage_kv": 132, "construction": "b", "when": "installation", "multiple_of_od": 30, "source": "t"},
    {"voltage_kv": 132, "construction": "c", "when": "installation", "multiple_of_od": None, "source": "t"}],
    "cables": [
    {"id": "33-1000", "voltage_kv": 33, "csa_mm2": 1000, "od_mm": 70.0, "od_status": "estimated"},
    {"id": "132-1000-spec", "voltage_kv": 132, "csa_mm2": 1000, "od_mm": 115.0, "od_status": "estimated"},
    {"id": "132-1000", "voltage_kv": 132, "csa_mm2": 1000, "od_mm": 91.0, "od_status": "verified"}]}


def ground(xp, z):
    return Ground(np.asarray(z, float), OE, ON, 1.0, xp)


def grid(n=401):
    return np.meshgrid(np.arange(n, dtype=float), np.arange(n, dtype=float))


def routes(rows, R=3.0, depth=1.0):
    """rows of (x0, y0, heading, legs, turns) in local metres."""
    n = len(rows)
    D = dict(x0=np.array([r[0] for r in rows], float), y0=np.array([r[1] for r in rows], float),
             h0=np.array([r[2] for r in rows], float), legs=np.zeros((n, cs.NB + 1)), turns=np.zeros((n, cs.NB)))
    for k, r in enumerate(rows):
        D["legs"][k, :len(r[3])] = r[3]; D["turns"][k, :len(r[4])] = r[4]
    D["R"], D["depth"], D["kv"] = np.full(n, R), np.full(n, depth), np.full(n, 33)
    return D


def close(v, want, rel=1e-6):
    assert abs(v - want) <= rel * abs(want), (v, want, abs(v - want) / abs(want))


def test_min_radius_rule():
    r33, r132 = cs.min_radius(CABLES, 33), cs.min_radius(CABLES, 132)
    assert r33["multiple_of_od"] == 20 and abs(r33["radius_m"] - 1.4) < 1e-12          # final rule not used
    assert r132["cable_id"] == "132-1000" and r132["multiple_of_od"] == 35             # verified OD, largest rule
    assert abs(r132["radius_m"] - 3.185) < 1e-12 and r132["depth_m"] == 1.05
    if os.path.exists(cs.CABLES):                                                        # the real file, if present
        real = cs.load_cables(cs.CABLES)
        assert abs(cs.min_radius(real, 33)["radius_m"] - 1.4) < 1e-9
        assert abs(cs.min_radius(real, 132)["radius_m"] - 3.185) < 1e-9


def test_flat_plan_lengths():
    R = 3.185
    th = [math.radians(90), math.radians(-40), math.radians(135), math.radians(-150)]
    rows = [(50.3, 60.7, 0.3, [120.0], []),
            (50.3, 60.7, 0.3, [80.0, 70.0], th[:1]),
            (150.0, 150.0, 2.0, [40.0, 30.0, 25.0, 60.0, 35.0], th)]
    want = [120.0, 150.0 - 2 * R + R * math.pi / 2,
            190.0 + sum(R * abs(t) - 2 * R * math.tan(abs(t) / 2) for t in th)]
    for xp in XPS:
        r = cs.pair(routes(rows, R), ground(xp, np.full((401, 401), 80.0)))
        assert not r["viol"].any()
        for k in range(3):
            close(r["P"]["L2d"][k], want[k], 1e-12)
            close(r["p3"][k], want[k], 1e-12)
            close(r["e3"][k], want[k], 1e-5)       # chords of arcs, 0.05 m apart
        assert r["rel"].max() < cs.TOL


def test_plane_straight_and_arc():
    x, y = grid()
    gx, gy = 0.12, -0.05
    z = 100 + gx * x + gy * y
    h = 0.7
    g = gx * math.cos(h) + gy * math.sin(h)
    for xp in XPS:
        r = cs.pair(routes([(40.2, 200.1, h, [150.0], []), (100.5, 100.5, h, [60.0, 60.0], [math.radians(120)])], R=20.0),
                    ground(xp, z))
        close(r["p3"][0], 150.0 * math.sqrt(1 + g * g), 1e-12)
        close(r["e3"][0], 150.0 * math.sqrt(1 + g * g), 1e-10)
        # the bend: straights exact, arc by a fine midpoint sum of sqrt(1 + (grad . t)^2)
        t = 20.0 * math.tan(math.radians(60))
        phi = h + (np.arange(200000) + 0.5) / 200000 * math.radians(120)
        arc = 20.0 * math.radians(120) * np.mean(np.sqrt(1 + (gx * np.cos(phi) + gy * np.sin(phi)) ** 2))
        g2 = gx * math.cos(h + math.radians(120)) + gy * math.sin(h + math.radians(120))
        want = (60 - t) * math.sqrt(1 + g * g) + arc + (60 - t) * math.sqrt(1 + g2 * g2)
        close(r["p3"][1], want, 1e-9)
        close(r["e3"][1], want, 1e-5)


def test_ridge_kink_on_grid_line():
    x, y = grid()
    z = 50 + 0.3 * np.abs(x - 200) + 0.02 * y                 # kink on x = 200, a grid line
    for xp in XPS:
        h = 0.2
        r = cs.pair(routes([(120.37, 100.2, h, [170.0], [])]), ground(xp, z))
        ux, uy = math.cos(h), math.sin(h)
        a = (200 - 120.37) / ux                                # chainage at the kink
        want = a * math.hypot(1, -0.3 * ux + 0.02 * uy) + (170 - a) * math.hypot(1, 0.3 * ux + 0.02 * uy)
        close(r["p3"][0], want, 1e-12)
        close(r["e3"][0], want, 1e-6)


def test_short_legs_shrink_fillet():
    R = 3.185
    for xp in XPS:
        r = cs.pair(routes([(100, 100, 0, [2.0, 50.0], [math.radians(90)]),          # leg 2 m: r = 2
                            (100, 100, 0, [40.0, 3.0, 40.0], [math.radians(90), math.radians(90)]),  # shared 1.5 m
                            (100, 100, 0, [40.0, 40.0], [math.radians(90)])], R), ground(xp, np.full((301, 301), 7.0)))
        close(r["r"][0, 0], 2.0, 1e-12)
        close(r["r"][1, 0], 1.5, 1e-12); close(r["r"][1, 1], 1.5, 1e-12)
        assert r["viol"][0, 0] and r["viol"][1, :2].all() and not r["viol"][2].any()
        close(r["p3"][0], 52.0 - 4.0 + math.pi, 1e-12)
        assert r["rel"].max() < cs.TOL


def hilly(tmp_path, n=601, seed=5):
    rng = np.random.default_rng(seed)
    x, y = grid(n)
    z = 120 + 0.03 * x + 4 * np.sin(x / 37) * np.cos(y / 23) + rng.normal(0, 0.05, x.shape)
    np.save(tmp_path / "source.npy", z)
    json.dump({"origin_e_m": OE, "origin_n_m": ON, "spacing_m": 1}, open(tmp_path / "source.json", "w"))


def test_sweep_hilly(tmp_path):
    hilly(tmp_path)
    for gpu in [False] + ([True] if cs.cp is not None else []):
        r = cs.sweep(str(tmp_path), routes=300, seconds=60, batch=120, use_gpu=gpu, witness=16, cables=CABLES)
        c = r["counts"]
        assert c["routes"] == 300 and all(c["by_bends"][str(b)] > 0 for b in range(5))
        assert r["photons_total"] == 0 and r["witness"]["photons"] == 0, r["disagreement"]["worst"][:2]
        assert r["plan_check"]["max_rel_chords_vs_analytic"] < 1e-4
        for kv in ("33kV", "132kV"):
            e = r["extra_3d_over_plan"][kv]
            assert e["routes"] > 0 and e["cable_3d_km"] >= e["plan_km"] and e["extra_pct_percentiles_0_5_25_50_75_95_100"][0] >= 0
        assert r["bend_radius"]["bends_below_min"] > 0 and len(r["script_sha256"]) == 64
        path, _ = cs.write_receipt(str(tmp_path), r)
        raw = open(path, "rb").read()
        assert b"\r\n" not in raw and raw.endswith(b"\n") and json.loads(raw)["seed"] == cs.SEED


def test_bounded_by_seconds(tmp_path):
    np.save(tmp_path / "source.npy", np.full((401, 401), 50.0))
    json.dump({"origin_e_m": OE, "origin_n_m": ON, "spacing_m": 1}, open(tmp_path / "source.json", "w"))
    r = cs.sweep(str(tmp_path), routes=10 ** 6, seconds=0.0, batch=7, use_gpu=False, witness=4, cables=CABLES)
    assert r["counts"]["stopped_by"] == "seconds" and r["counts"]["routes"] == 7
    assert r["disagreement"]["max_rel"] < 1e-5          # flat: 3D is the plan


if __name__ == "__main__":
    fails = 0
    for name, fn in sorted((n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)):
        with tempfile.TemporaryDirectory() as d:
            try:
                fn(*([pathlib.Path(d)] if inspect.signature(fn).parameters else []))
                print("ok  ", name)
            except Exception:
                fails += 1
                print("FAIL", name); traceback.print_exc()
    print(f"{fails} failed")
    sys.exit(1 if fails else 0)

Baseline

A JavaScript module in the cable screen folder of Seed Data that adds count (`addCount`) and calculates planar distances (units: Ω).

transformseed-data / experiments/economical-seeds/next-invention/cable-screen/baseline.mjs · lines 1–124 of 124 · pattern nonnegative (shared by 2 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including requireRecord, positive, nonnegative, finiteOutput, addCount.
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.
Downstream impact
Used directly by 4 files: Baseline Test (seed-data); Benchmark (seed-data); Route Screen Test (seed-data); Parity (seed-data). Reached from 1 other entry point, including Seed Regressions Workflow (seed-data).
What it achieves
It adds count (`addCount`) and is built from the require record helper (`requireRecord`) and the finite output helper (`finiteOutput`). Defines `requireRecord`, `positive`, `nonnegative` and 5 more.
Why it matters
Imported by Parity. Run by Benchmark. Checked by 2 tests, including Baseline Test.
Application
seed-data · experiments/economical-seeds/next-invention/cable-screen · JavaScript module
Uses
none found
Used by
imported by Baseline Test (import), run by Benchmark (script call), imported by Route Screen Test (import), imported by Parity (import)
Produces
screen
Defines here
requireRecord, positive, nonnegative, finiteOutput, addCount, crossingsReport, electricalModel, screen
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/cable-screen/baseline.mjs:1-124 · blob 4457a68a91102d736e90d0431f7767293f605b25 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: supporting_data
const trenchlessClasses = new Set(["motorway", "trunk_road", "railway", "navigable_river", "canal",
    "protected_habitat", "open_water"]);
const openCutClasses = new Set(["minor_road", "watercourse"]);

function requireRecord(value, name) {
    if (value === null || typeof value !== "object" || Array.isArray(value)) {
        throw new TypeError(name + " must be an object");
    }
}

function positive(value, name) {
    if (!Number.isFinite(value) || value <= 0) throw new RangeError(name + " must be finite and positive");
}

function nonnegative(value, name) {
    if (!Number.isFinite(value) || value < 0) throw new RangeError(name + " must be finite and nonnegative");
}

function finiteOutput(value, name) {
    if (!Number.isFinite(value)) throw new RangeError("Nonfinite " + name);
    return value;
}

function addCount(value, count) {
    const total = value + count;
    if (!Number.isSafeInteger(total)) throw new RangeError("crossing count exceeds the exact integer range");
    return total;
}

function crossingsReport(crossings) {
    if (!Array.isArray(crossings)) throw new TypeError("crossings must be an array");
    let blocked = false;
    const result = {count: 0, trenchless: 0, openCut: 0, declaredLengthM: 0, undeclaredCount: 0};
    for (const section of crossings) {
        requireRecord(section, "crossing");
        const {type, widthM, setbackM, depthM} = section;
        const count = Object.hasOwn(section, "count") ? section.count : 1;
        if (!Number.isSafeInteger(count) || count <= 0) throw new RangeError("crossing count must be a positive integer");
        const trenchless = trenchlessClasses.has(type);
        if (!trenchless && !openCutClasses.has(type)) throw new RangeError("unknown crossing type");
        result.count = addCount(result.count, count);
        if (trenchless) result.trenchless = addCount(result.trenchless, count);
        else result.openCut = addCount(result.openCut, count);
        blocked ||= type === "open_water";

        const hasWidth = Object.hasOwn(section, "widthM");
        const hasSetback = Object.hasOwn(section, "setbackM");
        const hasDepth = Object.hasOwn(section, "depthM");
        if (hasWidth !== hasSetback || (hasDepth && !hasWidth)) {
            throw new RangeError("width and setback must be supplied as a pair before using depth");
        }
        if (!hasWidth) {
            result.undeclaredCount = addCount(result.undeclaredCount, count);
            continue;
        }
        positive(widthM, "width");
        positive(setbackM, "setback");
        if (hasDepth) nonnegative(depthM, "depth");
        const span = widthM + 2 * setbackM;
        const length = depthM > 0 ? 2 * Math.hypot(span / 2, depthM) : span;
        result.declaredLengthM = finiteOutput(result.declaredLengthM + count * length, "crossing length");
    }
    return {result, blocked};
}

function electricalModel(electrical) {
    requireRecord(electrical, "electrical");
    const {currentA, nominalVolts, resistanceOhmPerKm, reactanceOhmPerKm, powerFactor, phases} = electrical;
    positive(currentA, "current");
    positive(nominalVolts, "nominal voltage");
    positive(resistanceOhmPerKm, "resistance");
    nonnegative(reactanceOhmPerKm, "reactance");
    positive(powerFactor, "power factor");
    if (powerFactor > 1) throw new RangeError("power factor exceeds one");
    if (phases !== "three" && phases !== "single") throw new RangeError("unknown phase configuration");
    const dropScale = phases === "three" ? Math.sqrt(3) : 2;
    const lossScale = phases === "three" ? 3 : 2;
    const effectiveImpedance = resistanceOhmPerKm * powerFactor
        + reactanceOhmPerKm * Math.sqrt(1 - powerFactor ** 2);
    return lengthM => {
        const km = lengthM / 1000;
        const dropV = finiteOutput(dropScale * currentA * km * effectiveImpedance, "voltage drop");
        const dropPct = finiteOutput(100 * dropV / nominalVolts, "percentage drop");
        const lossW = finiteOutput(lossScale * currentA ** 2 * resistanceOhmPerKm * km, "loss");
        return {status: "computed", lengthM, dropV, dropPct, lossW};
    };
}

export function screen(input) {
    requireRecord(input, "input");
    const calculate = electricalModel(input.electrical);
    if (!Array.isArray(input.options) || !input.options.length) throw new RangeError("at least one route required");
    const ids = new Set();
    let minimum = Infinity;
    let lowestLossIds = [];
    const options = input.options.map(option => {
        requireRecord(option, "option");
        const {id, straightLineKm} = option;
        if (typeof id !== "string" || !id.trim() || ids.has(id)) throw new RangeError("route ID invalid or duplicated");
        ids.add(id);
        positive(straightLineKm, "straight-line length");
        const {result: crossings, blocked} = crossingsReport(option.crossings);
        const corridor = blocked ? {status: "blocked", km: null}
            : straightLineKm < 1 ? {status: "below_minimum", km: null}
                : {status: "indicative", km: finiteOutput(straightLineKm * 1.245, "corridor length")};
        const straightMetres = finiteOutput(straightLineKm * 1000, "straight-line metres");
        let electrical = {status: "needs_installed_length"};
        if (Object.hasOwn(option, "installedLengthM")) {
            positive(option.installedLengthM, "installed length");
            if (option.installedLengthM < straightMetres) {
                throw new RangeError("installed length is shorter than the straight-line distance");
            }
            electrical = calculate(option.installedLengthM);
        }
        if (electrical.status === "computed") {
            if (electrical.lossW < minimum) {
                minimum = electrical.lossW;
                lowestLossIds = [id];
            } else if (electrical.lossW === minimum) lowestLossIds.push(id);
        }
        return {id, corridor, crossings, electrical};
    });
    return {options, lowestLossIds: lowestLossIds.sort()};
}

Baseline Test

A test in the cable screen folder of Seed Data that checks Baseline.

testseed-data / experiments/economical-seeds/next-invention/cable-screen/baseline.test.mjs · lines 1–97 of 97 · Entry point · pattern option (shared by 6 files)

What it does
It tests its inputs. Defines input, option. Uses libraries node:assert/strict, node:test.
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.
Downstream impact
Used directly by 1 file: Seed Regressions Workflow (seed-data).
What it achieves
Defines `input` and `option`.
Why it matters
Run by Seed Regressions Workflow.
Application
seed-data · experiments/economical-seeds/next-invention/cable-screen · test
Uses
Baseline (import), node:assert/strict, node:test
Used by
run by Seed Regressions Workflow (workflow run)
Produces
input, option
Defines here
input, option
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/cable-screen/baseline.test.mjs:1-97 · blob aace53d4439885109490337e45a35b691c5608b0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: supporting_data
import assert from "node:assert/strict";
import test from "node:test";
import { screen } from "./baseline.mjs";

function input(options, electrical = {}) {
    return {
        electrical: {currentA: 10, nominalVolts: 400, resistanceOhmPerKm: 0.5,
            reactanceOhmPerKm: 0.25, powerFactor: 0.6, phases: "single", ...electrical},
        options
    };
}

function option(id = "A", extra = {}) {
    return {id, straightLineKm: 2, crossings: [], ...extra};
}

test("uses the installed length for independent AC calculations", () => {
    const result = screen(input([option("A", {installedLengthM: 2000})]));
    assert.deepEqual(result.options[0].electrical, {
        status: "computed", lengthM: 2000, dropV: 20, dropPct: 5, lossW: 200
    });
    assert.deepEqual(result.lowestLossIds, ["A"]);
});

test("three-phase uses its own drop and loss factors", () => {
    const result = screen(input([option("B", {straightLineKm: 1, installedLengthM: 1000})], {
        phases: "three", currentA: 100, powerFactor: 1
    })).options[0].electrical;
    assert.ok(Math.abs(result.dropV - 86.60254037844386) < 1e-12);
    assert.equal(result.lossW, 15000);
});

test("corridor blocking, threshold and missing length stay distinct", () => {
    const result = screen(input([
        option("sea", {straightLineKm: 0.9, crossings: [{type: "open_water"}]}),
        option("short", {straightLineKm: 0.99}),
        option("boundary", {straightLineKm: 1})
    ]));
    assert.deepEqual(result.options.map(x => x.corridor), [
        {status: "blocked", km: null}, {status: "below_minimum", km: null},
        {status: "indicative", km: 1.245}
    ]);
    assert.ok(result.options.every(x => x.electrical.status === "needs_installed_length"));
    assert.deepEqual(result.lowestLossIds, []);
});

test("counts occurrences and measured crossing lengths using the requested profile", () => {
    const result = screen(input([option("A", {crossings: [
        {type: "railway", widthM: 6, setbackM: 1, depthM: 3, count: 2},
        {type: "minor_road", widthM: 5, setbackM: 1},
        {type: "watercourse", count: 3}
    ]})])).options[0];
    assert.deepEqual(result.crossings, {
        count: 6, trenchless: 2, openCut: 4, declaredLengthM: 27, undeclaredCount: 3
    });
    assert.deepEqual(result.corridor, {status: "indicative", km: 2.49});
});

test("calculates with an explicit installed length if water blocks the corridor method", () => {
    const result = screen(input([option("sea", {
        crossings: [{type: "open_water"}], installedLengthM: 2000
    })])).options[0];
    assert.equal(result.corridor.status, "blocked");
    assert.equal(result.electrical.lossW, 200);
});

test("retains all tied minimal losses, independently of route order", () => {
    const result = screen(input([
        option("z", {straightLineKm: 0.049, installedLengthM: 51}), option("b", {straightLineKm: 0.049, installedLengthM: 50}),
        option("A", {straightLineKm: 0.049, installedLengthM: 50}), option("undefined")
    ]));
    assert.deepEqual(result.lowestLossIds, ["A", "b"]);
});

test("rejects invalid configuration, missing widths or overflow", () => {
    for (const malformed of [
        input([]), input([option(), option()]), input([option(" ")]),
        input([option("bad", {straightLineKm: Infinity})]),
        input([option("bad", {installedLengthM: null})]),
        input([option("bad", {crossings: [{type: "x"}]})]),
        input([option("bad", {crossings: [{type: "canal", count: 1.5}]})]),
        input([option("bad", {crossings: [{type: "canal", count: 0}]})]),
        input([option("bad", {crossings: [{type: "canal", widthM: 2}]})]),
        input([option("bad", {crossings: [{type: "canal", depthM: 0}]})]),
        input([option("bad", {crossings: [{type: "canal", widthM: 2, setbackM: 0}]})]),
        input([option("bad", {crossings: [{type: "canal", widthM: 2, setbackM: 3, depthM: -1}]})]),
        input([option()], {powerFactor: 1.1}),
        input([option()], {reactanceOhmPerKm: -0.1}),
        input([option()], {phases: "five"}),
        input([option("bad", {installedLengthM: 1999})]),
        input([option("bad", {straightLineKm: 1e308})]),
        input([option("bad", {crossings: [
            {type: "minor_road", count: Number.MAX_SAFE_INTEGER}, {type: "railway", count: 1}
        ]})]),
        input([option("bad", {installedLengthM: 2000})], {currentA: 1e200})
    ]) assert.throws(() => screen(malformed));
});

Benchmark

A JavaScript module in the cable screen folder of Seed Data that reads fixture and cables, using SHA-256.

storageseed-data / experiments/economical-seeds/next-invention/cable-screen/benchmark.mjs · lines 1–98 of 98 · Not reached from any entry point (candidate for review) · pattern normalized (shared by 4 files)

What it does
It loads fixture and cables. Defines normalized, sample. Uses libraries node:assert/strict, node:child_process, node:crypto, node:fs, node:url. Side effects: reads or writes files; starts processes.
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. Domain terms in the code: cables.
Inputs & outputs
In: JSON file fixture.json; command-line arguments.
What it achieves
Defines `normalized` and `sample`.
Why it matters
No other file in the estate was found to import it.
Application
seed-data · experiments/economical-seeds/next-invention/cable-screen · JavaScript module
Uses
Route Screen (script call), Baseline (script call), node:assert/strict, node:child_process, node:crypto, node:fs, node:url, node:perf_hooks
Used by
none found
Produces
normalized, sample
Defines here
normalized, sample
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/cable-screen/benchmark.mjs:1-98 · blob 46b2930c2e758f8db5cd56b21636ee0c18fd7b00 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
/** Measure equivalent cable-option decisions in interleaved fresh workers. */
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { performance } from 'node:perf_hooks';

const HERE = fileURLToPath(import.meta.url);
const fixtureUrl = new URL('./fixture.json', import.meta.url);
const rounds = 7;
const iterations = 1024;

function normalized(value) {
  if (typeof value === 'number') return Number(value.toPrecision(11));
  if (Array.isArray(value)) return value.map(normalized);
  if (value && typeof value === 'object') {
    return Object.fromEntries(Object.keys(value).sort().map(key => [key, normalized(value[key])]));
  }
  return value;
}

async function sample(mode, repo) {
  const start = performance.now();
  const coldCpu = process.cpuUsage();
  const payload = readFileSync(fixtureUrl);
  const fixture = JSON.parse(payload);
  let invoke, logicalPinnedBytes = 0;
  if (mode === 'composed') {
    const { loadInstruments, screen } = await import('./route-screen.mjs');
    const modules = await loadInstruments(repo);
    logicalPinnedBytes = modules.logicalSourceBytes;
    invoke = data => screen(data, modules);
  } else {
    ({screen: invoke} = await import('./baseline.mjs'));
  }
  const first = invoke(fixture);
  const setupAndFirstResultMs = performance.now() - start;
  const setupAndFirstResultCpu = process.cpuUsage(coldCpu);
  const witness = createHash('sha256').update(JSON.stringify(normalized(first))).digest('hex');

  for (let i = 0; i < 128; i++) invoke(fixture);
  const t = performance.now();
  const cpu = process.cpuUsage();
  let warmWitness = 0;
  for (let i = 0; i < iterations; i++) warmWitness += invoke(fixture).options[0].electrical.lossW;
  const warmBatchMs = performance.now() - t;
  const warm = process.cpuUsage(cpu);
  assert.equal(warmWitness, first.options[0].electrical.lossW * iterations);
  return {
    mode, witness, setupAndFirstResultMs, warmBatchMs,
    setupAndFirstResultCpuUs: setupAndFirstResultCpu.user + setupAndFirstResultCpu.system,
    warmBatchCpuUs: warm.user + warm.system,
    peakWorkerRssBytes: process.resourceUsage().maxRSS * 1024,
    fixtureBytes: payload.length, pinnedDependencyPayloadBytes: logicalPinnedBytes,
    warmInvocations: iterations, inferenceCalls: 0, humanInterventions: 0
  };
}

const [, , first, second, third] = process.argv;
if (first === '--worker') {
  assert(['composed', 'independent'].includes(second));
  console.log(JSON.stringify(await sample(second, third)));
} else {
  if (!first || !second) throw new Error('Usage: node benchmark.mjs <engine-checkout> <new-receipt.json>');
  const samples = [];
  for (let i = 0; i < rounds; i++) {
    const order = i % 2 ? ['independent', 'composed'] : ['composed', 'independent'];
    for (const mode of order) {
      const start = performance.now();
      const raw = execFileSync(process.execPath, [HERE, '--worker', mode, first]);
      const workerWallMs = performance.now() - start;
      samples.push({ ...JSON.parse(raw), workerWallMs });
    }
  }
  assert.equal(new Set(samples.map(sample => sample.witness)).size, 1, 'Comparable answers disagree');
  const metrics = ['setupAndFirstResultMs', 'setupAndFirstResultCpuUs', 'warmBatchMs', 'warmBatchCpuUs',
    'peakWorkerRssBytes', 'fixtureBytes', 'pinnedDependencyPayloadBytes', 'workerWallMs'];
  const medians = Object.fromEntries(['composed', 'independent'].map(mode => {
    const matched = samples.filter(sample => sample.mode === mode);
    return [mode, Object.fromEntries(metrics.map(name =>
      [name, matched.map(sample => sample[name]).sort((a, b) => a - b)[Math.floor(rounds / 2)]]))];
  }));
  const receipt = {
    schema: 'seed.cable-screen.cost-comparison.v1',
    platform: process.platform, node: process.version, rounds, iterations, medians, samples,
    boundaries: {
      startup: 'Worker wall includes launch. In-process setup includes pinned Git extraction for composition.',
      cpu: 'Node process CPU only. Git child CPU and RSS are outside process counters.',
      bytes: 'Counts the shared input JSON and explicit verified Git payload bytes. Implicit module loads, Git on-disk reads and physical movement are outside the counters.',
      operating_conditions: 'Interleaved fresh processes. Cache state and competing system activity uncontrolled.',
      energy: 'No validated joule or watt-hour instrumentation.',
      inference: 'No timed invocations used model or GPU execution. Authoring cost is recorded separately.'
    }
  };
  writeFileSync(second, JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' });
  console.log(JSON.stringify(medians, null, 2));
}