In this section
- Ventus Engine ingest · gpu-drivers-for-global-grid / engine/ventus_engine.py lines 1–272
- Worlds render · gpu-drivers-for-global-grid / engine/worlds.py lines 1–215
- Grid Dictionary — Index Page render · grid-dictionary / index.html lines 1–62
Ventus Engine
A Python module in GPU Drivers for Global Grid that converts to host (`to_host`).
ingestgpu-drivers-for-global-grid / engine/ventus_engine.py · lines 1–272 of 272 · pattern free_batch (shared by 3 files)
- What it does
- Defines 29 functions or classes, including EngineError, Backend, __init__, is_gpu, mem. Uses libraries __future__, math, time, numpy, cupy.
- Downstream impact
- Used directly by 2 files: East West Block (gpu-drivers-for-global-grid); Selftest (gpu-drivers-for-global-grid).
- What it achieves
- It is built from the engine error class (`EngineError`), the backend class (`Backend`) and the is gpu helper (`is_gpu`). Our own GPU arithmetic engine. No model, no vendor, no LLM.
- Why it matters
- Imported by East West Block and Selftest.
- Application
- gpu-drivers-for-global-grid · engine · Python module
- Uses
- __future__, math, time, numpy, cupy
- Used by
- imported by East West Block (import), imported by Selftest (import)
- Produces
- EngineError, Backend, Space, Verification, Run, Engine
- Defines here
- EngineError, Backend, __init__, is_gpu, mem, free_batch, to_host, conditions, Space, __init__, decode, coprime_stride, __repr__, Verification, __init__, passed, __repr__, Run, __init__, rate, Engine, __init__, assert_closed_forms, _codes, _reduce, run, verify, _codes_with, report
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/ventus_engine.py:1-272 · blob e8e8743ffb2a1ed204d52f25925ca9ca39f7e7a5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Ventus engine - our own GPU arithmetic engine. No model, no vendor, no LLM.
The intelligence is ours: closed forms we wrote, enumerated over a case space
we define, on whichever backend is present. The card is a multiplier on our
arithmetic, never a source of answers.
Written 2026-09-20 from three pieces that were already proven on this machine:
- reduce ON the card so a batch returns ~20 kB, not gigabytes
- size the batch from FREE device memory at run time, never a constant
- a rate is not a result until the arithmetic has been verified equal to a
reference implementation
House rules enforced in code, not by discipline:
* a run over zero cases FAILS. A check that reached nothing is not a pass.
* a rate cannot be reported for arithmetic that has not been verified.
* every rate carries the conditions it was taken under.
* closed forms are asserted BEFORE the sweep, so the sweep can only confirm
or break them, never discover them.
from ventus_engine import Backend, Space, Engine
eng = Engine(Space([7, 11, 13]), kernel)
eng.assert_closed_forms(my_checks)
v = eng.verify(n=100_000) # cpu vs gpu on a coprime stride
r = eng.run() # the whole space
print(eng.report(r, v))
"""
from __future__ import annotations
import math
import time
__all__ = ["Backend", "Space", "Engine", "EngineError", "Verification", "Run"]
class EngineError(RuntimeError):
"""Raised when a house rule is broken, never a warning."""
# --------------------------------------------------------------- the backend
class Backend:
"""numpy, or cupy when a device is present and actually runs a kernel."""
def __init__(self, prefer="auto"):
import numpy
self.np = numpy
self.xp = numpy
self.name = "numpy"
self.device = None
if prefer in ("auto", "gpu"):
try:
import cupy
cupy.arange(8, dtype=cupy.float64).sum() # prove it runs
self.xp = cupy
self.name = "cupy"
self.device = cupy.cuda.Device(0)
except Exception as exc:
if prefer == "gpu":
raise EngineError("gpu asked for, not available: %r" % exc)
elif prefer != "cpu":
raise EngineError("prefer must be auto, gpu or cpu")
@property
def is_gpu(self):
return self.name == "cupy"
def mem(self):
"""(free, total) device bytes, or (None, None) on the CPU."""
if not self.is_gpu:
return None, None
return self.device.mem_info
def free_batch(self, bytes_per_case, share=0.25, cap=1 << 23, floor=1 << 12):
"""Batch sized from FREE memory now - never a hard-coded constant."""
if bytes_per_case <= 0:
raise EngineError("bytes_per_case must be positive")
if not self.is_gpu:
return min(cap, 1 << 20)
free, _ = self.mem()
n = int(free * share / bytes_per_case)
return max(floor, min(cap, n))
def to_host(self, a):
return self.xp.asnumpy(a) if self.is_gpu else self.np.asarray(a)
def conditions(self):
free, total = self.mem()
c = {"backend": self.name}
if self.is_gpu:
c["device_free_gb"] = round(free / 1e9, 2)
c["device_total_gb"] = round(total / 1e9, 2)
c["device_used_gb"] = round((total - free) / 1e9, 2)
c["card_shared"] = (total - free) > 1.5e9
c["cpu_watts_measured"] = False # stated plainly, always
return c
# ------------------------------------------------------------- the case space
class Space:
"""A mixed-radix case space. Case i decodes to one value per axis."""
def __init__(self, radices, names=None):
radices = [int(r) for r in radices]
if not radices or any(r < 1 for r in radices):
raise EngineError("every radix must be >= 1")
self.radices = radices
self.names = list(names) if names else [
"axis%d" % i for i in range(len(radices))]
if len(self.names) != len(radices):
raise EngineError("names and radices differ in length")
self.size = math.prod(radices)
def decode(self, xp, idx):
"""Vectorised: idx -> list of per-axis integer arrays."""
out, rest = [], idx
for r in self.radices:
out.append(rest % r)
rest = rest // r
return out
def coprime_stride(self):
"""A stride that walks the whole space without repeating."""
s = 1000003
while math.gcd(s, self.size) != 1:
s += 2
return s
def __repr__(self):
return "Space(%s, size=%d)" % (self.radices, self.size)
# ------------------------------------------------------------------- results
class Verification:
def __init__(self, n, differ, worst, seconds, ref, test):
self.n, self.differ, self.worst = n, differ, worst
self.seconds, self.ref, self.test = seconds, ref, test
@property
def passed(self):
return self.n > 0 and self.differ == 0
def __repr__(self):
return "Verification(%s vs %s, n=%d, differ=%d, worst=%.2e, %s)" % (
self.ref, self.test, self.n, self.differ, self.worst,
"PASS" if self.passed else "FAIL")
class Run:
def __init__(self, cases, seconds, totals, conditions, batch):
self.cases, self.seconds = cases, seconds
self.totals, self.conditions, self.batch = totals, conditions, batch
@property
def rate(self):
return self.cases / self.seconds if self.seconds > 0 else float("inf")
# -------------------------------------------------------------------- engine
class Engine:
"""Maps one kernel over one space, reducing on the device."""
def __init__(self, space, kernel, bytes_per_case=176, prefer="auto"):
if not callable(kernel):
raise EngineError("kernel must be callable(xp, axes) -> codes")
self.space, self.kernel = space, kernel
self.bytes_per_case = bytes_per_case
self.backend = Backend(prefer)
self._closed_forms_asserted = False
# ---- closed forms first, always
def assert_closed_forms(self, checks):
"""checks(xp, space, kernel) must raise or return True. Run BEFORE any
sweep, so the sweep can only confirm the arithmetic."""
if checks(self.backend.np, self.space, self.kernel) is not True:
raise EngineError("closed forms did not return True")
self._closed_forms_asserted = True
return True
def _codes(self, xp, idx):
axes = self.space.decode(xp, idx)
codes = self.kernel(xp, axes)
if codes.shape != idx.shape:
raise EngineError("kernel returned %s for %s inputs"
% (codes.shape, idx.shape))
return codes
def _reduce(self, xp, codes, nbins):
"""Reduce ON the device: only nbins numbers cross the bus."""
return xp.bincount(codes.astype(xp.int64), minlength=nbins)[:nbins]
def run(self, nbins=16, limit=None, batch=None):
if not self._closed_forms_asserted:
raise EngineError("assert_closed_forms() must pass before run()")
xp = self.backend.xp
total = self.space.size if limit is None else min(limit, self.space.size)
if total <= 0:
raise EngineError("a run over zero cases fails: nothing was reached")
batch = batch or self.backend.free_batch(self.bytes_per_case)
totals = xp.zeros(nbins, dtype=xp.int64)
done, t0 = 0, time.perf_counter()
while done < total:
n = min(batch, total - done)
idx = xp.arange(done, done + n, dtype=xp.int64)
totals += self._reduce(xp, self._codes(xp, idx), nbins)
done += n
if self.backend.is_gpu:
self.backend.xp.cuda.Stream.null.synchronize()
secs = time.perf_counter() - t0
host = [int(v) for v in self.backend.to_host(totals)]
if sum(host) != total:
raise EngineError("reduction lost cases: %d of %d"
% (sum(host), total))
return Run(total, secs, host, self.backend.conditions(), batch)
def verify(self, n=100_000, against="cpu"):
"""Same cases, both backends, on a coprime stride through the space."""
if n <= 0:
raise EngineError("a verification of zero cases fails")
ref = Backend(against)
stride = self.space.coprime_stride()
t0 = time.perf_counter()
idx_r = ref.xp.arange(n, dtype=ref.xp.int64) * stride % self.space.size
a = ref.to_host(self._codes_with(ref, idx_r))
xp = self.backend.xp
idx_t = xp.arange(n, dtype=xp.int64) * stride % self.space.size
b = self.backend.to_host(self._codes_with(self.backend, idx_t))
differ = int((a != b).sum())
worst = float(abs(a.astype("float64") - b.astype("float64")).max()) \
if n else 0.0
return Verification(n, differ, worst, time.perf_counter() - t0,
ref.name, self.backend.name)
def _codes_with(self, backend, idx):
axes = self.space.decode(backend.xp, idx)
return self.kernel(backend.xp, axes)
# ---- a rate is not a result until it has been verified
def report(self, run, verification, label="run"):
if not isinstance(verification, Verification):
raise EngineError("report() requires a Verification")
if not verification.passed:
raise EngineError(
"refusing to report a rate: verification %s (n=%d, differ=%d)"
% ("failed" if verification.n else "reached nothing",
verification.n, verification.differ))
if run.cases <= 0:
raise EngineError("refusing to report a run over zero cases")
c = run.conditions
lines = [
"%s %s" % (label.upper(), self.space),
" verified %s vs %s, %d cases on stride %d: %d differ, worst "
"%.2e" % (verification.ref, verification.test, verification.n,
self.space.coprime_stride(), verification.differ,
verification.worst),
" cases %d (denominator: the whole space is %d)"
% (run.cases, self.space.size),
" seconds %.3f" % run.seconds,
" rate {:,.0f} cases/s{}".format(
run.rate,
" NOT A THROUGHPUT: the space is smaller than one batch, so "
"this is setup time" if run.cases < run.batch else ""),
" batch %d, sized from free memory at run time" % run.batch,
" backend %s" % c["backend"],
]
if c["backend"] == "cupy":
lines.append(" device %.2f GB free of %.2f GB%s"
% (c["device_free_gb"], c["device_total_gb"],
" CARD SHARED AT RUN TIME"
if c.get("card_shared") else ""))
lines.append(" cpu watts NOT MEASURED - no wall meter, no RAPL. "
"No efficiency ratio is stated.")
lines.append(" totals %s" % run.totals)
return "\n".join(lines)Worlds
A Python command-line tool in the engine folder of GPU Drivers for Global Grid covering cables. It is built from the reference step (`reference`) and the SVG step (`svg`).
rendergpu-drivers-for-global-grid / engine/worlds.py · lines 1–215 of 215 · Entry point · pattern reference (shared by 15 files)
- What it does
- It draws cables. Defines reference, svg, P, main. Uses libraries io, os, sys, time, numpy. Side effects: changes the web page (DOM); starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- Out: SVG drawing.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Kuiper worlds: the card draws, not just decides.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- io, os, sys, time, numpy, cupy
- Used by
- none found
- Produces
- reference, svg, main
- Defines here
- reference, svg, P, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/worlds.py:1-215 · blob a9d86a977e829bac9265c848d66036bd854cd9a4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: unknown · users: none · canonical: unknown
"""Kuiper worlds: the card draws, not just decides.
The same case index that yields a verdict also yields the PICTURE of that
design - module positions and the cable route through them - computed on the
card in one fused kernel. The card emits geometry; the page draws it. Same
index, same world, every time, with nothing stored: eighteen quintillion No
Man's Sky planets fit in a few hundred megabytes for exactly this reason.
This is the UI rule made literal. An operation that cannot be seen is not an
operation, so the geometry is generated by the same pass that generates the
answer, rather than being drawn afterwards by hand.
python worlds.py generate, verify, write worlds.svg
Verified before anything is drawn: the card's geometry must equal the
processor's, point for point.
"""
import io
import os
import sys
import time
import numpy as np
try:
import cupy as cp
except Exception as exc: # pragma: no cover
print("cupy unavailable: %r" % (exc,))
sys.exit(1)
# ---- the design space. Module is class T660: 1303 mm wide in portrait.
W_MM, GAP_MM = 1303.0, 20.0
PITCH = (W_MM + GAP_MM) / 1000.0 # metres between module centres
SERIES = list(range(20, 35)) # 15
ROUTINGS = ["sequential", "leapfrog"] # 2
ROWS = [1, 2] # modules high: 3 axes is a world
NS, NR, NH = len(SERIES), len(ROUTINGS), len(ROWS)
SIZE = NS * NR * NH
MAXPTS = 40 # 34 modules + entry + return + slack
ROW_M = 2.384 + 0.03 # module height in portrait, plus gap
_SRC = """
long long r = idx;
int si = (int)(r %% %(NS)d); r /= %(NS)d;
int ri = (int)(r %% %(NR)d); r /= %(NR)d;
int hi = (int)(r %% %(NH)d);
int n = %(S0)d + si; // modules in series
int leap = (ri == 1);
int rows = 1 + hi; // modules high
double p = %(PITCH).6f;
double ry = %(ROWM).6f;
int base = (int)(idx * %(MAXPTS)d * 2);
int k = 0;
// the string cable, module centre to module centre
for (int step = 0; step < n; ++step) {
int m;
if (!leap) {
m = step; // straight along the row
} else if (step < (n + 1) / 2) {
m = step * 2; // out along every other
} else {
m = (n - 1 - (step - (n + 1) / 2) * 2); // back through the skipped
if (n %% 2 == 0) m = n - 2 - (step - n / 2) * 2;
}
double x = (m + 0.5) * p;
double y = (rows == 2 && (m %% 2)) ? ry : 0.0;
out[base + k * 2] = (float)x;
out[base + k * 2 + 1] = (float)y;
k++;
}
// the home run: both ends brought back to the inverter side at x = 0
out[base + k * 2] = (float)((n - 0.5) * p);
out[base + k * 2 + 1] = (float)(-0.9);
k++;
out[base + k * 2] = 0.0f;
out[base + k * 2 + 1] = (float)(-0.9);
k++;
npts[idx] = k;
""" % {"NS": NS, "NR": NR, "NH": NH, "S0": SERIES[0], "PITCH": PITCH,
"ROWM": ROW_M, "MAXPTS": MAXPTS}
DRAW = cp.ElementwiseKernel(
"int64 idx", "raw float32 out, raw int32 npts", _SRC, "ventus_world_draw")
def reference(idx):
"""The same geometry on the processor. This is what the card must equal."""
out = np.zeros((len(idx), MAXPTS, 2), dtype=np.float32)
npts = np.zeros(len(idx), dtype=np.int32)
for j, i in enumerate(idx):
r = int(i)
si = r % NS; r //= NS
ri = r % NR; r //= NR
hi = r % NH
n = SERIES[0] + si
leap = (ri == 1)
rows = 1 + hi
k = 0
for step in range(n):
if not leap:
m = step
elif step < (n + 1) // 2:
m = step * 2
else:
m = n - 1 - (step - (n + 1) // 2) * 2
if n % 2 == 0:
m = n - 2 - (step - n // 2) * 2
out[j, k] = ((m + 0.5) * PITCH,
ROW_M if (rows == 2 and m % 2) else 0.0)
k += 1
out[j, k] = ((n - 0.5) * PITCH, -0.9); k += 1
out[j, k] = (0.0, -0.9); k += 1
npts[j] = k
return out, npts
def svg(cases, geo, npts, path):
"""The view, written from the card's own geometry. No hand-drawing."""
cols, cell_w, cell_h, pad = 3, 360.0, 150.0, 14.0
rows_n = (len(cases) + cols - 1) // cols
W = cols * cell_w + pad * 2
H = rows_n * cell_h + pad * 2 + 46
s = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %.0f %.0f" '
'width="100%%" style="background:#07090d;font-family:ui-monospace,'
'Menlo,Consolas,monospace">' % (W, H)]
s.append('<text x="%.0f" y="26" fill="#fff" font-size="15">Kuiper worlds '
'— %d designs, geometry generated on the card</text>'
% (pad, len(cases)))
s.append('<text x="%.0f" y="42" fill="#4ade80" font-size="10.5">every '
'point below came from the same index that yields the verdict; '
'nothing here was drawn by hand</text>' % pad)
for c, case in enumerate(cases):
gx = pad + (c % cols) * cell_w
gy = pad + 46 + (c // cols) * cell_h
r = case
si = r % NS; r //= NS
ri = r % NR; r //= NR
hi = r % NH
n, routing, rows = SERIES[0] + si, ROUTINGS[ri], 1 + ROWS.index(ROWS[hi]) + 0
rows = ROWS[hi]
pts = geo[c][:npts[c]]
xs, ys = pts[:, 0], pts[:, 1]
x0, x1 = float(xs.min()), float(xs.max())
y0, y1 = float(ys.min()), float(ys.max())
sx = (cell_w - 34) / max(x1 - x0, 1e-6)
sy = (cell_h - 58) / max(y1 - y0, 1e-6)
k = min(sx, sy)
def P(x, y):
return (gx + 17 + (x - x0) * k, gy + 34 + (y1 - y) * k)
# modules first, so the cable is drawn over them
for m in range(n):
mx = (m + 0.5) * PITCH
my = ROW_M if (rows == 2 and m % 2) else 0.0
px, py = P(mx, my)
s.append('<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" '
'fill="#11151f" stroke="#1b2030" stroke-width="0.7"/>'
% (px - (W_MM / 1000.0) * k / 2, py - 5,
max(1.2, (W_MM / 1000.0) * k), 10))
d = " ".join("%.1f,%.1f" % P(float(x), float(y)) for x, y in pts)
s.append('<polyline points="%s" fill="none" stroke="#5ec8f2" '
'stroke-width="1.5"/>' % d)
s.append('<text x="%.0f" y="%.0f" fill="#cfe3f2" font-size="10">'
'%d in series · %s · %d high</text>'
% (gx + 17, gy + 20, n, routing, rows))
s.append('<text x="%.0f" y="%.0f" fill="#8b93a7" font-size="9">'
'index %d · %.2f kW DC at 660 Wp</text>'
% (gx + 17, gy + cell_h - 16, case, n * 660.0 / 1000.0))
s.append("</svg>")
io.open(path, "w", encoding="utf-8", newline="\n").write("\n".join(s))
def main():
print("world space: %d designs over 3 axes %s" % (SIZE, [NS, NR, NH]))
idx = cp.arange(SIZE, dtype=cp.int64)
out = cp.zeros(SIZE * MAXPTS * 2, dtype=cp.float32)
npts = cp.zeros(SIZE, dtype=cp.int32)
cp.cuda.Stream.null.synchronize()
t0 = time.perf_counter()
DRAW(idx, out, npts)
cp.cuda.Stream.null.synchronize()
sec = time.perf_counter() - t0
geo = cp.asnumpy(out).reshape(SIZE, MAXPTS, 2)
npt = cp.asnumpy(npts)
ref_geo, ref_npt = reference(np.arange(SIZE))
same_n = bool((npt == ref_npt).all())
worst = float(np.abs(geo - ref_geo).max())
print("verified against the processor: point counts equal = %s, worst "
"coordinate difference = %.3e" % (same_n, worst))
if not same_n or worst > 0:
print("FAIL: the card and the processor drew different worlds")
return 1
print("the card drew %d complete worlds in %.4f s (%s designs/s)\n"
% (SIZE, sec, "{:,.0f}".format(SIZE / sec)))
show = [SERIES.index(n) + NS * (r + NR * h)
for n in (24, 30, 34) for r in (0, 1) for h in (0, 1)][:12]
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, "worlds.svg")
svg(show, geo[show], npt[show], path)
print("wrote %s - %d of them drawn, every coordinate from the card"
% (os.path.basename(path), len(show)))
print("\nNot claimed: this is the cable ROUTE, not a cable schedule; no")
print("length, loss or sizing figure is stated and none was computed.")
return 0
if __name__ == "__main__":
sys.exit(main())Grid Dictionary — Index Page
A web page using data from the ventus-grid-engine and stars repositories. It is built from the esc step (`esc`) and the render step (`render`).
rendergrid-dictionary / index.html · lines 1–62 of 62 · Entry point
- What it does
- It draws its content. Defines esc, render. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- README: "Live page: `index.html` (reads `data/dictionary.json`)."
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: stars data; JSON file dictionary.json; form fields (user input). Out: web page.
- Downstream impact
- Used directly by 6 files: Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Pilot (globalgrid2050); Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609170036-estate/); Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609180205-underground/); and 2 more. Reached from 190 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/).
- What it achieves
- The README says: Live page: `index.html` (reads `data/dictionary.json`). It reads `./data/dictionary.json`.
- Why it matters
- Imported by 6 files, including Pilot, from GlobalGrid2050.
- Application
- grid-dictionary · / · page
- Uses
- Table (link)
- Used by
- named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL)
- Produces
- esc, render
- Defines here
- esc, render
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- grid-dictionary@21b73d7cd5a6171245e0b3d1b69b0ce4d6322a63 index.html:1-62 · blob 26a6a22fefd920b9bc608eb9e45f7916190cbced · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Grid dictionary · Global Grid 2050</title>
<style>
:root{color-scheme:dark}
body{margin:0;padding:16px 18px 48px;background:#0b0d12;color:#eef2fb;font:15px/1.55 Inter,ui-sans-serif,system-ui,sans-serif}
a{color:#00e5ff;text-decoration:none}a:hover{text-decoration:underline}
.ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff}
h1{font-size:22px;margin:2px 0 6px}
.muted{color:#9aa3b5}
.nav{display:flex;flex-wrap:wrap;gap:6px 14px;margin:8px 0 10px;font-size:13px;font-family:ui-monospace,monospace}
.search{width:100%;box-sizing:border-box;background:#0f1218;border:1px solid #385464;color:#eef2fb;border-radius:999px;padding:11px 16px;font:inherit;font-size:16px;margin:8px 0}
.search:focus{outline:none;border-color:#00e5ff;box-shadow:0 0 0 2px rgba(0,229,255,.18)}
.cats{display:flex;flex-wrap:wrap;gap:6px;margin:4px 0 10px}
.cat{font-size:12px;padding:4px 11px;border:1px solid #262b36;border-radius:999px;cursor:pointer;color:#c7d0e0}
.cat.on{border-color:#00e5ff;color:#eef2fb}
.term{border:1px solid #1e2530;border-radius:12px;padding:12px 14px;margin:9px 0;background:linear-gradient(160deg,rgba(255,255,255,.03),rgba(255,255,255,.008))}
.term h3{margin:0 0 3px;font-size:17px}
.k{font-family:ui-monospace,monospace;font-size:11px;color:#ffc43c;margin-left:6px}
.tag{font-family:ui-monospace,monospace;font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:#9aa3b5}
.src{color:#9aa3b5;font-size:13px;margin-top:5px}
.rel a{margin-right:2px}
.code{color:#69f0ae;font-size:12.5px}
</style>
<div class="ey">Ventus · Global Grid 2050</div>
<h1>Grid dictionary</h1>
<nav class="nav"><a href="https://ventusltd.github.io/ventus-grid-engine/">← Spider map</a><a href="https://globalgrid2050.com/">Home</a><a href="https://ventusltd.github.io/stars/table.html">Periodic table</a></nav>
<div class="muted" id="status">Loading…</div>
<input class="search" id="search" type="search" placeholder="Search the grid — try DNO, NESO, headroom, voltage, constraint" autocomplete="off">
<div class="cats" id="cats"></div>
<div id="list"></div>
<p class="muted" style="margin-top:20px">Every term has a permanent key and is tied to the estate's unique code history (the wandering star) and to the Maya cards on the Spider, so a dead end on the map can teach the grid. Sources: NESO, the transmission owners, the DNOs, Ofgem, UK Government and Elexon. <a href="https://github.com/Ventusltd/grid-dictionary">How this is built</a></p>
<script>
const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
let D, cat=null, q='';
function render(){
const list=document.getElementById('list');
const terms=D.terms.filter(t=>(!cat||t.category===cat)&&(!q||(t.term+' '+t.definition+' '+(t.aliases||[]).join(' ')).toLowerCase().includes(q)));
list.innerHTML=terms.map(t=>`<div class="term"><h3>${esc(t.term)}<span class="k">${t.key}</span></h3>`
+`<div class="tag">${esc(D.categories[t.category]||t.category)}</div>`
+`<div>${esc(t.definition)}</div>`
+`<div class="src">Source: ${esc(t.source)}</div>`
+(t.related&&t.related.length?`<div class="src rel">Related: ${t.related.map(r=>`<a href="#" data-k="${esc(r.term)}">${esc(r.term)}</a>`).join(', ')}</div>`:'')
+(t.estate?`<div class="src">In our code: ${esc(t.estate)}</div>`:'')
+(t.code_families&&t.code_families.length?`<div class="src code">Tied to ${t.code_families.length} unique code families via the wandering star</div>`:'')
+`</div>`).join('')||'<p class="muted">Nothing matches.</p>';
list.querySelectorAll('a[data-k]').forEach(a=>a.onclick=e=>{e.preventDefault();document.getElementById('search').value=a.dataset.k;q=a.dataset.k.toLowerCase();render();window.scrollTo({top:0});});
}
(async()=>{
try{ D=await (await fetch('./data/dictionary.json',{cache:'no-cache'})).json(); }
catch(e){ document.getElementById('status').textContent='The dictionary is not built yet: '+e.message; return; }
document.getElementById('status').textContent=`${D.count} grid terms · updated ${D.generated_utc.slice(0,16).replace('T',' ')} UTC`;
const cats=document.getElementById('cats');
cats.innerHTML=`<span class="cat on" data-c="">All</span>`+Object.entries(D.categories).map(([id,t])=>`<span class="cat" data-c="${id}">${esc(t)}</span>`).join('');
cats.querySelectorAll('.cat').forEach(el=>el.onclick=()=>{cat=el.dataset.c||null;cats.querySelectorAll('.cat').forEach(x=>x.classList.toggle('on',x===el));render();});
document.getElementById('search').oninput=e=>{q=e.target.value.trim().toLowerCase();render();};
render();
})();
</script>
</html>