GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / particle-physics-drawing-engine / tools

Rare Cosmic and 4 more files

A JavaScript module in the economical seeds folder of Seed Data that works with exact target (`exactTarget`) and calculates planar distances, covering wafer, using SHA-256.

612 lines of Python and JavaScript from particle-physics-drawing-engine, seed-data, in 5 files. Topic: Kuiper, cosmos and drawing engines. Section 1557 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. Publish Iteration storage · particle-physics-drawing-engine / tools/publish_iteration.py lines 1–140
  2. Scope Check storage · particle-physics-drawing-engine / tools/scope_check.py lines 1–58
  3. Spiral vs Stack storage · particle-physics-drawing-engine / tools/spiral_vs_stack.py lines 1–74
  4. Underground storage · particle-physics-drawing-engine / tools/underground.py lines 1–134
  5. Rare Cosmic ingest · seed-data / experiments/economical-seeds/rare_cosmic.mjs lines 1–206

Publish Iteration

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that reads spiral vs stack and underground from the GridAtlas and ventus-grid-engine repositories.

storageparticle-physics-drawing-engine / tools/publish_iteration.py · lines 1–140 of 140 · Entry point · pattern key_for (shared by 2 files)

What it does
It loads spiral vs stack and underground. Defines 7 functions or classes, including system_for, key_for, put, put_many, api. Uses libraries base64, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: data source: gridatlas data; data source: ventus-grid-engine data; JSON file spiral-vs-stack.json; JSON file underground.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the system for helper (`system_for`), the key for helper (`key_for`) and the put step (`put`). Number, label and publish one iteration under `globalgrid2050.com/testcode/particles/`. Its code works with 100 kW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
base64, json, os, subprocess, sys, time
Used by
none found
Produces
system_for, key_for, put, put_many, load, main
Defines here
system_for, key_for, put, put_many, api, load, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/publish_iteration.py:1-140 · blob bbeb8f784dd9111cc98d777cec7367bce2f7dc0c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""publish_iteration.py: number, label and publish one iteration under globalgrid2050.com/testcode/particles/.

Called by the swarm after each run. Iteration N (1..30) gets its own folder NN-<slug>/ with a plain,
business-like page: the pictures the run drew, the facts it measured, the scope status. The index page
lists every iteration with its label so the owner can decide which to keep. Publishes through the
GitHub contents API (no local clone state), only small files. Stops at 30. No model text is published.
"""
import base64, json, os, subprocess, sys, time

REPO = "Ventusltd/globalgrid2050"
BASE = "testcode/particles"
COUNTER = r"E:\particles-runs\iteration.txt"
MAX_ITER = 30
MAX_KEY = 342795          # the estate's highest issued key on 2026-09-14
PHI = (1 + 5 ** 0.5) / 2


SYSTEMS = ["grid", "grid400", "grid132", "substations", "shotwick", "underground", "uk", "world", "logo"]   # real systems the wafer draws
HOME = "../../wafer-development-environment/202609180245-real-systems/"


def system_for(n):
    """Iteration n opens the real-systems wafer on system SYSTEMS[n mod 9]: a tour, deterministic, no choice."""
    return SYSTEMS[n % len(SYSTEMS)]


def key_for(n):
    """The formula: iteration n opens on line 1 + floor(frac(n/phi) * MAX_KEY). Golden-ratio spacing:
    every iteration lands far from every previous one, the sequence never repeats a key before all are
    visited (to rounding), and anyone can recompute which line iteration n shows. No Man's Sky rule:
    nothing chosen, everything derived from n."""
    return 1 + int(((n / PHI) % 1.0) * MAX_KEY)
STYLE = ("body{margin:0;background:#000;color:#ccc;font:15px/1.5 ui-monospace,Consolas,monospace}"
         "main{max-width:1400px;margin:0 auto;padding:0 0 24px}h1,p,table,pre,small{margin-left:16px;margin-right:16px}h1{font-size:18px;color:#f2f2f2;margin:0 0 4px}"
         "img{width:100%;height:auto;display:block;background:#000;margin:16px 0 6px}small{color:#8a8a8a}"
         "a{color:#61d6d6}code{color:#f9f1a5}table{border-collapse:collapse}td,th{padding:2px 10px;text-align:left}")


def put(path, data: bytes, msg):
    body = json.dumps({"message": msg, "content": base64.b64encode(data).decode(), "branch": "main"})
    r = subprocess.run(["gh", "api", "-X", "GET", f"repos/{REPO}/contents/{path}", "--jq", ".sha"], capture_output=True, text=True)
    if r.returncode == 0 and r.stdout.strip():
        body = json.dumps({"message": msg, "content": base64.b64encode(data).decode(), "branch": "main", "sha": r.stdout.strip()})
    r = subprocess.run(["gh", "api", "-X", "PUT", f"repos/{REPO}/contents/{path}", "--input", "-"], input=body, capture_output=True, text=True)
    if r.returncode != 0:
        print(f"publish failed for {path}: {r.stderr[:200]}"); return False
    return True


def put_many(files, msg):
    """One commit for all files of an iteration, through the git data API: one deploy, not three."""
    def api(method, path, body=None):
        args = ["gh", "api", "-X", method, path]
        r = subprocess.run(args + (["--input", "-"] if body is not None else []), input=json.dumps(body) if body is not None else None, capture_output=True, text=True)
        if r.returncode != 0:
            raise RuntimeError(f"{method} {path}: {r.stderr[:200]}")
        return json.loads(r.stdout)
    head = api("GET", f"repos/{REPO}/git/ref/heads/main")["object"]["sha"]
    base_tree = api("GET", f"repos/{REPO}/git/commits/{head}")["tree"]["sha"]
    tree = []
    for path, data in files.items():
        blob = api("POST", f"repos/{REPO}/git/blobs", {"content": base64.b64encode(data).decode(), "encoding": "base64"})["sha"]
        tree.append({"path": path, "mode": "100644", "type": "blob", "sha": blob})
    new_tree = api("POST", f"repos/{REPO}/git/trees", {"base_tree": base_tree, "tree": tree})["sha"]
    commit = api("POST", f"repos/{REPO}/git/commits", {"message": msg, "tree": new_tree, "parents": [head]})["sha"]
    api("PATCH", f"repos/{REPO}/git/refs/heads/main", {"sha": commit})
    return commit


def load(p):
    try:
        return json.load(open(p))
    except Exception:
        return None


def main(run_dir):
    n = int(open(COUNTER).read().strip()) + 1 if os.path.exists(COUNTER) else 1
    if n > MAX_ITER:
        print(f"iteration cap {MAX_ITER} reached; nothing published"); return 0
    b1 = load(os.path.join(run_dir, "b1-layers-256", "spiral-vs-stack.json")) or load(os.path.join(run_dir, "b1-layers-64", "spiral-vs-stack.json"))
    b2 = load(os.path.join(run_dir, "b2", "underground.json"))
    layers = [load(os.path.join(run_dir, f"layer-{L}", f"layer-{L}.json")) for L in (1, 16, 64, 256)]
    layers = [m for m in layers if m]
    status = open(os.path.join(run_dir, "SCOPE-STATUS.md"), encoding="utf-8").read() if os.path.exists(os.path.join(run_dir, "SCOPE-STATUS.md")) else ""
    passed = status.split("Ran ")[1].split(".")[0] if "Ran " in status else "not run"
    stamp = os.path.basename(run_dir)
    key = key_for(n); system = system_for(n)
    slug = f"{n:02d}-{system}-line-{key}"
    label = (f"Iteration {n}: {system} drawn on the wafer; line {key}; {b1['particles']:,} particles under two laws" if b1 else f"Iteration {n}") + \
            (f"; the Underground, {b2['stations']} stops" if b2 else "") + f"; scope tests {passed}"
    rows = "".join(f"<tr><td>layer {m['layer']}</td><td>{m['slots']:,} slots</td><td><code>{m['sha256_of_line_hashes'][:16]}…</code></td><td>{m['seconds']} s</td></tr>" for m in layers)
    page = f"""<!doctype html><html lang="en-GB"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Particles iteration {n:02d}</title><style>{STYLE}</style></head><body><main>
<iframe src="{HOME}?draw={system}" title="the wafer drawing a real system" style="width:100%;height:92vh;border:0;background:#000"></iframe>
<p><small>Above: the wafer drawing <code>{system}</code> with its own particles, live (iteration {n}: system {n} mod 9 of the tour, line {key} by the formula 1 + floor(frac(n/φ) × 342,795)); type <code>release</code>, then any button. Below: what the swarm measured in this run.</small></p>
<h1>{label}</h1>
<p>testcode/particles/{slug} · machine-made on the MSI at {stamp} by <a href="https://github.com/Ventusltd/particle-physics-drawing-engine">particle-physics-drawing-engine</a> · <a href="../">all iterations</a></p>
<p>Same-sized particles, positions computed from the address by a named law, nothing stored. Left: one spiral. Right: a stack of layers of 262,144 slots, angle by whole-number arithmetic.</p>
{'<img src="spiral-vs-stack.png" alt="spiral versus stack">' if b1 else ''}
{f'<small>{b1["particles"]:,} particles; spiral {b1["spiral"]["seconds"]} s, stack {b1["stack"]["seconds"]} s; cells lit {b1["spiral"]["cells_lit"]:,} / {b1["stack"]["cells_lit"]:,}</small>' if b1 else ''}
<p style="margin-top:24px">A network from the typed command <code>draw underground</code>: topology from Transport for London's open data, drawn as the same particles under an eight-direction schematic law. No map artwork.</p>
{'<img src="underground.png" alt="the Underground as particles">' if b2 else ''}
{f'<small>{b2["lines"]} lines, {b2["stations"]} stops, {b2["edges"]} edges, {b2["particles_drawn"]:,} particles. Powered by TfL Open Data. Contains OS data © Crown copyright and database rights 2016 and Geomni UK Map data © and database rights 2019.</small>' if b2 else ''}
<h2 style="font-size:16px;margin-top:28px">Generated layers, regenerated and hashed on this machine</h2>
<table><tr><th>layer</th><th>size</th><th>hash of every line</th><th>time</th></tr>{rows}</table>
<h2 style="font-size:16px;margin-top:28px">Scope status</h2>
<pre style="white-space:pre-wrap;color:#aaa">{status.replace('<','&lt;')}</pre>
<small>This page charts measured facts. It is not a design tool; above 100 kW a chartered electrical engineer signs.</small>
</main></body></html>"""
    files = {f"{BASE}/{slug}/index.html": page.encode()}
    for src, name in ((os.path.join(run_dir, "b1-layers-256", "spiral-vs-stack.png"), "spiral-vs-stack.png"), (os.path.join(run_dir, "b2", "underground.png"), "underground.png")):
        if os.path.exists(src):
            files[f"{BASE}/{slug}/{name}"] = open(src, "rb").read()
    # index: append this iteration to a machine-kept list, then render
    listing = r"E:\particles-runs\iterations.json"
    items = load(listing) or []
    items.append({"n": n, "slug": slug, "label": label, "stamp": stamp})
    lis = "".join(f'<tr><td>{i["n"]:02d}</td><td><a href="{i["slug"]}/">{i["label"]}</a></td><td>{i["stamp"]}</td><td>keep? ☐</td></tr>' for i in items)
    index = f"""<!doctype html><html lang="en-GB"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Particles: numbered iterations</title><style>{STYLE}</style></head><body><main>
<h1>Particle physics drawing engine: numbered iterations</h1>
<p>One iteration every hour, machine-made and measured, up to 30. Each is a page of what the swarm drew and hashed. The owner decides which to keep. Source and scope: <a href="https://github.com/Ventusltd/particle-physics-drawing-engine">particle-physics-drawing-engine</a>. Home view: <a href="../wafer-development-environment/202609170044-key-to-code/">the key-to-code wafer</a>.</p>
<table><tr><th>#</th><th>iteration</th><th>run (UTC)</th><th></th></tr>{lis}</table>
<small>Proof of the kind of work this leads to: <a href="https://ventusltd.github.io/gridatlas/">GridAtlas</a> and <a href="https://ventusltd.github.io/ventus-grid-engine/">Ventus Grid Engine</a>.</small>
</main></body></html>"""
    files[f"{BASE}/index.html"] = index.encode()
    try:
        commit = put_many(files, f"testcode/particles {n:02d}: {label}")
    except RuntimeError as e:
        print(f"publish failed: {e}"); return 1
    json.dump(items, open(listing, "w"), indent=1)
    open(COUNTER, "w").write(str(n))
    print(f"published iteration {n:02d} in one commit {commit[:7]}: {label}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1]))

Scope Check

A Python command-line tool in the tools folder of Particle Physics Drawing Engine.

storageparticle-physics-drawing-engine / tools/scope_check.py · lines 1–58 of 58 · Entry point

What it does
It loads data. Defines main. Uses libraries os, subprocess, sys, time. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file layer-2.json.
Downstream impact
Used directly by 1 file: Nightly Workflow (particle-physics-drawing-engine).
What it achieves
The scope drives the loop. It writes `results/SCOPE-STATUS.md`.
Why it matters
Run by Nightly Workflow.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
Particles (script call), Spiral vs Stack (script call), Underground (script call), os, subprocess, sys, time
Used by
run by Nightly Workflow (workflow run)
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/scope_check.py:1-58 · blob 0cf7b689cf1ed075f568e355c662fe0f7fb90c87 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""scope_check.py: the scope drives the loop.

Runs every test in SCOPE.md section 8 that has a script, and writes results/SCOPE-STATUS.md with
PASS, FAIL or NOT YET BUILT per test, dated, with the command and its exit code. Exit 1 if any built
test fails; exit 3 if no test could be run (examined nothing); else 0.
The table below mirrors SCOPE.md section 8 by hand; if the scope changes, change it here too.
"""
import os, subprocess, sys, time

TESTS = [
    ("T1", "a physical iPhone draws one layer", None),                       # a person, with the phone in hand
    ("T2", "exactness of the angle law", [sys.executable, "tools/particles.py", "exactness"]),
    ("T3", "cross-device positions within a pixel", None),
    ("T4", "generator determinism: a layer regenerates identically",
        [sys.executable, "-c",
         "import subprocess,sys;p=sys.executable;"
         "subprocess.check_call([p,'tools/particles.py','layer','--layer','2','--out','out/scope']);"
         "subprocess.check_call([p,'tools/particles.py','dna','out/scope/layer-2.json'])"]),
    ("T5", "address to source in one request", None),
    ("T6", "a law missing a fact refuses by name", None),
    ("T7", "sixteen layers served from the workstation's second drive", None),
    ("B1", "spiral and stack side by side", [sys.executable, "tools/spiral_vs_stack.py", "--layers", "4", "--per-layer", "65536", "--out", "out/scope/b1"]),
    ("B2", "a network from a typed command (the Underground)", [sys.executable, "tools/underground.py", "--out", "out/scope/b2"]),
]


def main():
    os.makedirs("results", exist_ok=True)
    rows, ran, failed = [], 0, 0
    for tid, name, cmd in TESTS:
        if cmd is None:
            rows.append((tid, name, "NOT YET BUILT", "", ""))
            continue
        t0 = time.time()
        r = subprocess.run(cmd, capture_output=True, text=True)
        secs = round(time.time() - t0, 1)
        ran += 1
        status = "PASS" if r.returncode == 0 else ("EXAMINED NOTHING" if r.returncode == 3 else "FAIL")
        if r.returncode != 0:
            failed += 1
        last = (r.stdout.strip().splitlines() or r.stderr.strip().splitlines() or [""])[-1][:120]
        rows.append((tid, name, status, f"exit {r.returncode}, {secs} s", last))
    stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    with open("results/SCOPE-STATUS.md", "w", encoding="utf-8") as f:
        f.write(f"# Scope status {stamp}\n\nRan {ran} of {len(TESTS)} tests; {failed} failed. "
                f"Tests marked NOT YET BUILT have no script yet (T1 needs a person with the phone).\n\n")
        f.write("| test | what | status | run | last line |\n|---|---|---|---|---|\n")
        for tid, name, status, run, last in rows:
            f.write(f"| {tid} | {name} | **{status}** | {run} | `{last}` |\n")
    for tid, name, status, run, last in rows:
        print(f"{tid} {status:16} {run}")
    print(f"ran {ran} of {len(TESTS)}; failed {failed}")
    sys.exit(3 if ran == 0 else (1 if failed else 0))


if __name__ == "__main__":
    main()

Spiral vs Stack

A Python command-line tool in the tools folder of Particle Physics Drawing Engine. It is built from the run step (`run`).

storageparticle-physics-drawing-engine / tools/spiral_vs_stack.py · lines 1–74 of 74 · Entry point

What it does
It loads data. Defines run. Uses libraries argparse, json, math, os, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments. Out: JSON file spiral-vs-stack.json.
Downstream impact
Used directly by 2 files: Scope Check (particle-physics-drawing-engine); Nightly Workflow (particle-physics-drawing-engine).
What it achieves
The same addresses under two laws, drawn side by side. It accepts `--layers`, `--per-layer` and `--out`.
Why it matters
Run by Scope Check and Nightly Workflow.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
Png (import), Particles (import), argparse, json, math, os, sys, time
Used by
run by Scope Check (script call), run by Nightly Workflow (workflow run)
Produces
run
Defines here
run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/spiral_vs_stack.py:1-74 · blob 4a1392c96b98a587ecfbec21367fa47f5d520523 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""spiral_vs_stack.py: build B1. The same addresses under two laws, drawn side by side.

  spiral  one endless disc: r = sqrt(address), theta = address * golden angle (64-bit)
  stack   one disc per layer of 2^18 slots, tiled; theta by the whole-number law (exact per layer)

Same particles, same size, same count. Only the law differs. Decision 1 is taken by looking.
Every number printed is measured; the script exits non-zero if a raster examined nothing.
"""
import argparse, json, math, os, sys, time
sys.path.insert(0, os.path.dirname(__file__))
from png import raster_to_png
from particles import SLOTS, GOLDEN, theta_int

SIZE = 1024


def run(layers, per_layer, out):
    os.makedirs(out, exist_ok=True)
    n = layers * per_layer
    t0 = time.time()
    # ---- spiral: one disc over every address
    spiral = [0] * (SIZE * SIZE)
    R = math.sqrt(n)
    for a in range(n):
        r = math.sqrt(a) / R
        th = a * GOLDEN
        x = int((r * math.cos(th) + 1) * 0.5 * (SIZE - 1))
        y = int((r * math.sin(th) + 1) * 0.5 * (SIZE - 1))
        spiral[y * SIZE + x] += 1
    t1 = time.time()
    # ---- stack: one disc per layer, tiled in a square grid
    cols = math.ceil(math.sqrt(layers))
    tile = SIZE // cols
    stack = [0] * (SIZE * SIZE)
    Rl = math.sqrt(per_layer)
    for L in range(layers):
        ox, oy = (L % cols) * tile, (L // cols) * tile
        for s in range(per_layer):
            r = math.sqrt(s) / Rl
            th = theta_int(s)
            x = ox + int((r * math.cos(th) + 1) * 0.5 * (tile - 1))
            y = oy + int((r * math.sin(th) + 1) * 0.5 * (tile - 1))
            stack[y * SIZE + x] += 1
    t2 = time.time()
    raster_to_png(os.path.join(out, "spiral.png"), SIZE, spiral)
    raster_to_png(os.path.join(out, "stack.png"), SIZE, stack)
    # side by side
    both = []
    for y in range(SIZE):
        both += spiral[y * SIZE:(y + 1) * SIZE] + [0] * 16 + stack[y * SIZE:(y + 1) * SIZE]
    from png import write_grey
    peak = max(max(spiral), max(stack)) or 1
    write_grey(os.path.join(out, "spiral-vs-stack.png"), SIZE * 2 + 16, SIZE,
               bytes(int(255 * (c / peak) ** 0.5) if c else 0 for c in both))
    stats = {
        "layers": layers, "particles_per_layer": per_layer, "particles": n,
        "spiral": {"cells_lit": sum(1 for c in spiral if c), "peak_per_cell": max(spiral), "seconds": round(t1 - t0, 2)},
        "stack": {"cells_lit": sum(1 for c in stack if c), "peak_per_cell": max(stack), "tile_px": tile, "seconds": round(t2 - t1, 2)},
        "raster_px": SIZE, "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    json.dump(stats, open(os.path.join(out, "spiral-vs-stack.json"), "w"), indent=1)
    print(json.dumps(stats))
    if not stats["spiral"]["cells_lit"] or not stats["stack"]["cells_lit"]:
        sys.exit(3)  # examined nothing


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--layers", type=int, default=4)
    p.add_argument("--per-layer", type=int, default=SLOTS)
    p.add_argument("--out", default="out/b1")
    a = p.parse_args()
    run(a.layers, a.per_layer, a.out)

Underground

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that fetches tfl raw.

storageparticle-physics-drawing-engine / tools/underground.py · lines 1–134 of 134 · Entry point

What it does
It fetches tfl raw. Defines 6 functions or classes, including fetch, topology, schematic, draw, dot. Uses libraries argparse, json, math, os, sys. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: command-line arguments. Out: JSON file tfl-raw.json; JSON file underground.json.
Downstream impact
Used directly by 2 files: Scope Check (particle-physics-drawing-engine); Nightly Workflow (particle-physics-drawing-engine).
What it achieves
It is built from the fetch step (`fetch`), the topology step (`topology`) and the schematic step (`schematic`). A network drawn from a typed command, with the same particles. It accepts `--out`, `--offline` and `--passes`.
Why it matters
Run by Scope Check and Nightly Workflow.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
Png (import), argparse, json, math, os, sys, time, urllib.request
Used by
run by Scope Check (script call), run by Nightly Workflow (workflow run)
Produces
fetch, topology, schematic, draw, main
Defines here
fetch, topology, schematic, draw, dot, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/underground.py:1-134 · blob 9c9fb53e0517e82fa4ef88da3083e08688a8ef53 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""underground.py: build B2. A network drawn from a typed command, with the same particles.

Topology is fact and comes from Transport for London's open Unified API (stations, lines, order
of stops). The artwork is ours: stations and edges become same-sized particles under a schematic
law that snaps edges towards the eight compass directions. No TfL map artwork is used.
Attribution required by the data terms: "Powered by TfL Open Data. Contains OS data (c) Crown
copyright and database rights 2016 and Geomni UK Map data (c) and database rights 2019."

Usage: python tools/underground.py --out out/b2 [--offline out/b2/tfl-raw.json]
Exit 3 if no topology could be fetched (examined nothing), 1 if the drawing failed.
"""
import argparse, json, math, os, sys, time, urllib.request
sys.path.insert(0, os.path.dirname(__file__))
from png import raster_to_png

API = "https://api.tfl.gov.uk"
SIZE = 1024
EDGE_SPACING = 0.004      # particles along an edge, in normalised units
STATION_DOTS = 9          # a station is a small dense cluster of the same particles


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": "particle-physics-drawing-engine/0.1"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.load(r)


def topology(raw):
    """raw: {lineId: routeSequence json}. Returns stations {id: (name, lat, lon)}, edges {(a,b)}, per line."""
    stations, edges, lines = {}, set(), {}
    for line_id, seq in raw.items():
        points = list(seq.get("stations", []))
        for q in seq.get("stopPointSequences", []):       # some stops appear only here
            points += q.get("stopPoint", [])
        for sp in points:
            sid = sp.get("id") or sp.get("stationId")
            if sid and "lat" in sp:
                stations[sid] = (sp.get("name", sid), sp["lat"], sp["lon"])
        line_edges = set()
        for branch in seq.get("orderedLineRoutes", []):
            ids = branch.get("naptanIds", [])
            for a, b in zip(ids, ids[1:]):
                if a in stations and b in stations:
                    line_edges.add((a, b) if a < b else (b, a))
        lines[line_id] = sorted(line_edges)
        edges |= line_edges
    return stations, edges, lines


def schematic(stations, edges, passes=200, step=0.05):
    """Start from geography (equirectangular), then pull each edge towards the nearest of 8 directions."""
    lat0 = sum(s[1] for s in stations.values()) / len(stations)
    pos = {k: [(s[2]) * math.cos(math.radians(lat0)), s[1]] for k, s in stations.items()}
    xs = [p[0] for p in pos.values()]; ys = [p[1] for p in pos.values()]
    sx, sy = max(xs) - min(xs), max(ys) - min(ys); sc = max(sx, sy)
    for p in pos.values():
        p[0] = (p[0] - min(xs)) / sc * 1.8 - 0.9 * sx / sc
        p[1] = (p[1] - min(ys)) / sc * 1.8 - 0.9 * sy / sc
    for _ in range(passes):
        for a, b in edges:
            pa, pb = pos[a], pos[b]
            dx, dy = pb[0] - pa[0], pb[1] - pa[1]
            L = math.hypot(dx, dy) or 1e-9
            ang = math.atan2(dy, dx)
            snap = round(ang / (math.pi / 4)) * (math.pi / 4)
            tx, ty = math.cos(snap) * L, math.sin(snap) * L
            cx, cy = (pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2
            for p, sgn in ((pa, -1), (pb, 1)):
                gx, gy = cx + sgn * tx / 2, cy + sgn * ty / 2
                p[0] += (gx - p[0]) * step; p[1] += (gy - p[1]) * step
    return pos


def draw(pos, edges, out):
    raster = [0] * (SIZE * SIZE)
    n = 0
    def dot(x, y):
        nonlocal n
        if -1 <= x <= 1 and -1 <= y <= 1:
            raster[int((1 - y) * 0.5 * (SIZE - 1)) * SIZE + int((x + 1) * 0.5 * (SIZE - 1))] += 1; n += 1
    for a, b in edges:
        (x0, y0), (x1, y1) = pos[a], pos[b]
        k = max(1, int(math.hypot(x1 - x0, y1 - y0) / EDGE_SPACING))
        for i in range(k + 1):
            dot(x0 + (x1 - x0) * i / k, y0 + (y1 - y0) * i / k)
    for x, y in pos.values():
        for i in range(STATION_DOTS):
            th = i * 2.399963229728653
            r = 0.004 * math.sqrt(i)
            dot(x + r * math.cos(th), y + r * math.sin(th))
    raster_to_png(os.path.join(out, "underground.png"), SIZE, raster, gamma=0.35)
    return n


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--out", default="out/b2")
    p.add_argument("--offline", help="use a previously saved tfl-raw.json instead of the API")
    p.add_argument("--passes", type=int, default=200, help="snapping passes of the schematic law")
    p.add_argument("--step", type=float, default=0.05, help="fraction of the way each pass moves an endpoint")
    p.add_argument("--spacing", type=float, default=0.004, help="particle spacing along an edge")
    a = p.parse_args()
    os.makedirs(a.out, exist_ok=True)
    t0 = time.time()
    if a.offline:
        raw = json.load(open(a.offline))
    else:
        try:
            line_ids = [l["id"] for l in fetch(f"{API}/Line/Mode/tube")]
            raw = {lid: fetch(f"{API}/Line/{lid}/Route/Sequence/all") for lid in line_ids}
        except Exception as e:
            print(f"examined nothing: TfL fetch failed: {e}"); sys.exit(3)
        json.dump(raw, open(os.path.join(a.out, "tfl-raw.json"), "w"))
    stations, edges, lines = topology(raw)
    if not stations or not edges:
        print(f"examined nothing: {len(stations)} stations, {len(edges)} edges parsed"); sys.exit(3)
    global EDGE_SPACING
    EDGE_SPACING = a.spacing
    pos = schematic(stations, edges, passes=a.passes, step=a.step)
    n = draw(pos, edges, a.out)
    facts = {
        "command": "draw underground", "source": f"{API}/Line/Mode/tube + /Line/<id>/Route/Sequence/all",
        "attribution": "Powered by TfL Open Data. Contains OS data (c) Crown copyright and database rights 2016 and Geomni UK Map data (c) and database rights 2019.",
        "lines": len(lines), "stations": len(stations), "edges": len(edges), "particles_drawn": n,
        "law": f"geography then {a.passes} passes of 8-direction edge snapping (step {a.step}); edge particles every {a.spacing}; 9 per station",
        "seconds": round(time.time() - t0, 1), "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    json.dump(facts, open(os.path.join(a.out, "underground.json"), "w"), indent=1)
    print(json.dumps(facts))


if __name__ == "__main__":
    main()

Rare Cosmic

A JavaScript module in the economical seeds folder of Seed Data that works with exact target (`exactTarget`) and calculates planar distances, covering wafer, using SHA-256.

ingestseed-data / experiments/economical-seeds/rare_cosmic.mjs · lines 1–206 of 206 · Not reached from any entry point (candidate for review) · pattern prove (shared by 3 files)

What it does
It lists and searches wafer. Defines 9 functions or classes, including git, read, sha256, blobId, start. Uses libraries node:assert/strict, node:child_process, node:crypto, node:url, node:perf_hooks. Side effects: 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.
Inputs & outputs
In: JSON file universe.json; JSON file wafer.json; command-line arguments.
What it achieves
It is built from the git step (`git`), the read step (`read`) and the sha256 step (`sha256`). Probe the exact COSMIC addressing code from a pinned Git object.
Why it matters
No other file in the estate was found to import it.
Application
seed-data · experiments/economical-seeds · JavaScript module
Uses
node:assert/strict, node:child_process, node:crypto, node:url, node:perf_hooks, node:vm
Used by
none found
Produces
git, read, sha256, blobId, start, probe, exactTarget, invoke, prove
Defines here
git, read, sha256, blobId, start, probe, exactTarget, invoke, prove
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/rare_cosmic.mjs:1-206 · blob 6ffbcaddeb9495df5da619f7c7730fa039872234 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unreached_review
/* Probe the exact COSMIC addressing code from a pinned Git object. */
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { performance } from 'node:perf_hooks';
import vm from 'node:vm';

const revision = 'dbe20b06c1ac107e902b93354f8e8a37b0462ad0';
const repository = process.env.COSMIC_REPO || fileURLToPath(new URL('./cosmic-source/', import.meta.url));
const git = (...args) => execFileSync('git', ['--no-lazy-fetch', '-C', repository, ...args]);
const read = (path) => git('show', `${revision}:${path}`);
const sha256 = (data) => createHash('sha256').update(data).digest('hex');
const blobId = (data) => createHash('sha1').update(`blob ${data.length}\0`).update(data).digest('hex');
const htmlBytes = read('index.html');
const htmlBlob = blobId(htmlBytes);
assert.equal(htmlBlob, '41a9007eb8480538552240829c5cf7a137e0445c');
const html = htmlBytes.toString('utf8');
const placementBegin = html.indexOf('const RHO_MAX');
const camera = html.indexOf('// --------------------------------------------------------------------------------- the camera');
assert(placementBegin > 0 && camera > placementBegin);
const constants = ['GOLDEN', 'GOLD32', 'PER_PIXEL', 'fmt'].map(name => {
  const match = html.match(new RegExp(`^const ${name} = [^\n]+$`, 'm'));
  assert(match, name);
  return match[0];
});
constants.push(html.match(/^const words = [^\n]+$/m)?.[0] || (() => {
  const name = 'function words(';
  const start = html.indexOf(name);
  const end = html.indexOf('\n}', start);
  assert(start !== -1 && end !== -1);
  return html.slice(start, end + 2);
})());

async function start(cartridge, fault) {
  const calls = [];
  const memory = {};
  const context = vm.createContext({
    URLSearchParams, location: { search: `?u=${cartridge}` },
    performance, hud: { textContent: 'starting' }, big: {}, sub: {},
    cv: { height: 847 }, memory,
    fetch: async (path) => {
      let bytes = read(path);
      const identity = { path, bytes: bytes.length, git_blob: blobId(bytes), sha256: sha256(bytes) };
      if (fault && /^commits\//.test(path)) bytes = Buffer.from(fault(bytes.toString('utf8')));
      calls.push({ ...identity, delivered_bytes: bytes.length });
      memory[path] = bytes.toString('utf8');
      return { ok: true, json: () => JSON.parse(memory[path]), text: () => memory[path] };
    }
  });
  vm.runInContext(`let scale = 0.92, pan = [0, 0], tween = null; function restart() {}
    ${constants.join('\n')}
    ${html.slice(placementBegin, camera)}
    Object.defineProperties(memory, {
      ready: { get: () => Boolean(root) },
      total: { get: () => TOTAL },
      rows: { get: () => root.children.map(n => [n.label, n.value]) },
    });
    memory.collapse = async (k) => {
      target = null;
      await collapseTo(k);
      if (!target) return null;
      return { k: target.k, path: target.path.map(n => n.label), offset: target.m, x: target.x,
        y: target.y, fetches: target.fetches, childError: target.node.badChildren, shape: target.node.shape,
        expectsChild: Boolean(LEVELS[target.node.depth]?.child),
        center: [target.node.x,target.node.y], rho: target.node.rho,
        hw: target.node.hw, hh: target.node.hh, zoom: tween.s1 };
    };`, context, { filename: 'cosmic/index.html@' + revision });
  for (let i = 0; !memory.ready && i < 50; i++) await new Promise(setImmediate);
  assert(memory.ready, context.hud.textContent);
  return { memory, calls };
}

async function probe(system, k, expectedPath, expectedOffset, reads) {
  const startCount = system.calls.length;
  const output = await system.memory.collapse(k);
  const extra_reads = system.calls.slice(startCount);
  if (expectedPath) {
    assert.deepEqual(Array.from(output.path), expectedPath);
    assert.equal(output.offset, expectedOffset);
    assert.equal(output.fetches, reads);
    assert(Number.isFinite(output.x) && Number.isFinite(output.y) && output.zoom > 0);
    const [cx, cy] = output.center;
    if (output.shape === 'rect') {
      assert(Math.abs(output.x - cx) <= output.hw && Math.abs(output.y - cy) <= output.hh);
    } else {
      assert(Math.hypot(output.x - cx, output.y - cy) <= output.rho);
    }
  } else {
    assert.equal(output, null);
  }
  assert.equal(extra_reads.length, reads);
  return { ordinal: k, target: output, new_reads: extra_reads };
}

function exactTarget(target) {
  if (!target) throw new RangeError('Ordinal is outside the cartridge total');
  if (target.expectsChild) throw new Error(target.childError || 'Selected sector did not resolve');
  return target;
}

async function invoke([ordinal, cartridge = 'universe.json', ...extra]) {
  const k = Number(ordinal);
  if (!/^\d+$/.test(ordinal) || !Number.isSafeInteger(k) || extra.length ||
    !['universe.json', 'wafer.json'].includes(cartridge)) {
    throw new Error('Usage: node rare_cosmic.mjs [ordinal [universe.json|wafer.json]]');
  }
  const system = await start(cartridge);
  const bootstrap = system.calls.slice();
  const target = exactTarget(await system.memory.collapse(k));
  console.log(JSON.stringify({ cartridge, revision, tablet: 6187, total: system.memory.total,
    bootstrap, target, addressed_sector: system.calls.slice(bootstrap.length) }, null, 2));
}

async function prove() {
  const estate = await start('universe.json');
  assert.deepEqual(estate.calls.map(x => x.path), ['universe.json', 'belt.tsv']);
  assert.equal(estate.memory.total, 37_929_011_953);
  assert.equal(estate.memory.rows.length, 67);
  const estateBootstrap = estate.calls.slice();
  const first = await probe(estate, 17_901, ['cosmic', 'a1e5abcf3f62'], 0, 1);
  assert.equal(first.new_reads[0].path, 'commits/00.tsv');
  const cached = await probe(estate, 35_790, ['cosmic', 'a1e5abcf3f62'], 17_889, 0);
  const outside = [await probe(estate, -1, null, null, 0),
                   await probe(estate, estate.memory.total, null, null, 0)];

  // Independently linear-check the last line of the largest sector using only its
  // already-loaded rows and sibling counts. The addressing call never sees this oracle.
  const sectorIndex = estate.memory.rows.findIndex(([name]) => name === 'globalgrid2050');
  const precedingCounts = estate.memory.rows.slice(0, sectorIndex).map(([, count]) => count);
  const largestOrdinal = precedingCounts.reduce((sum, count) => sum + count, 0)
                         + estate.memory.rows[sectorIndex][1] - 1;
  assert(largestOrdinal > 2 ** 32);
  const expectedSector = `commits/${sectorIndex.toString().padStart(2, '0')}.tsv`;
  const endReadCount = estate.calls.length;
  const endTarget = await estate.memory.collapse(largestOrdinal);
  const lastReads = estate.calls.slice(endReadCount);
  assert.equal(lastReads.length, 1);
  assert.equal(lastReads[0].path, expectedSector);
  const rows = estate.memory[expectedSector].split('\n').filter(line => line && line[0] !== '#');
  const [, count, , label] = rows.at(-1).split('\t');
  const length = Number(count);
  assert.equal(rows.length, 5_054);
  assert.deepEqual(Array.from(endTarget.path), ['globalgrid2050', label]);
  assert.equal(endTarget.offset, length - 1);
  assert.equal(endTarget.fetches, 1);

  const wafer = await start('wafer.json');
  assert.equal(wafer.memory.total, 67_518_045_832);
  assert.equal(wafer.memory.rows.length, 97);
  const waferProbe = await probe(wafer, 858_000_000, ['die +1+0'], 0, 0);
  assert.equal(waferProbe.target.shape, 'rect');
  assert.equal(waferProbe.target.center[0], 26.08 / 150);
  assert.equal(waferProbe.target.center[1], 0);

  const mismatched = await start('universe.json', text => text.replace('\t17901\t', '\t17900\t'));
  const fallback = await mismatched.memory.collapse(17_901);
  assert.deepEqual(Array.from(fallback.path), ['cosmic']);
  assert.match(fallback.childError, /children sum to 35,790, parent holds 35,791/);
  assert.equal(fallback.offset, 17_901);
  assert.throws(() => exactTarget(fallback), /children sum/);

  console.log(JSON.stringify({
    status: 'bounded pass with witnessed failure fallback',
    contract: 'Select a member by an ordinal over additive ranges, opening only its relevant sector, with layout supplied by the cartridge.',
    applicability: 'Pinned two-level code estate and one-level computed wafer fixtures. No browser rendering, inverse pixel test, or complete data scan.',
    command: 'node rare_cosmic.mjs',
    example_invocation: 'node rare_cosmic.mjs 17901 universe.json',
    source: {
      repository: 'Ventusltd/cosmic', revision, path: 'index.html', git_blob: htmlBlob,
      sha256: sha256(htmlBytes), stars_tablet: 6187,
      stars_elements: { ensureChildren: 134863, findByOrdinal: 134865, leafPosition: 134905, collapseTo: 134906 },
      source_link: `https://github.com/Ventusltd/cosmic/blob/${revision}/index.html#L435-L530`
    },
    estate: { total: estate.memory.total, sectors: estate.memory.rows.length,
      bootstrap: estateBootstrap, cold_boundary: first, already_resident: cached,
      high_ordinal: { ordinal: largestOrdinal, target: endTarget, new_reads: lastReads }, outside },
    wafer: { total: wafer.memory.total, bootstrap: wafer.calls, boundary: waferProbe },
    malformed_child: {
      injected_change: 'Subtract one counted unit in the selected sector.',
      detected: fallback.childError,
      returned: fallback,
      violates_exact_leaf_contract: true,
      instrument_wrapper_refused: true,
      interpretation: 'The UI still receives a parent-level target. Exact callers need to reject this incomplete refinement explicitly.'
    },
    limitations: [
      'Fetch was substituted with local reads of pinned Git blobs. Read counts and bytes describe those artifacts, without a network latency claim.',
      'Rendering and inverse pixel addressing were outside this probe.',
      'Resolved estate leaf is an ordinal within a commit range. The cartridge does not map it to original file path and line bytes.',
      'Estates and wafer counts are prior cartridge measures, without a new historical sweep or a physical wafer measurement.'
    ],
    runtime_ai_calls: 0, gpu_used: false, energy_measured: false
  }, null, 2));
}

if (process.argv.length > 2) {
  try {
    await invoke(process.argv.slice(2));
  } catch (error) {
    console.error(error.message);
    process.exitCode = 1;
  }
} else {
  await prove();
}