In this section
- Build Payload other · pipelinenews / tools/intelligence/cartridges/grid-distance-column/build_payload.py lines 1–329
- Make Cartridge render · pipelinenews / tools/intelligence/cartridges/grid-distance-column/make_cartridge.py lines 1–346
Build Payload
A Python command-line tool in the grid distance column folder of PipelineNews that works with tolerance km and latest grid proximity and calculates planar distances, covering substations.
otherpipelinenews / tools/intelligence/cartridges/grid-distance-column/build_payload.py · lines 1–329 of 329 · Entry point · pattern latest_grid_proximity (shared by 2 files)
- What it does
- Defines tolerance_km, band_for, latest_grid_proximity, round_km, main. Uses libraries argparse, glob, hashlib, io, json. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 11kV.
- Inputs & outputs
- In: command-line arguments. Voltage levels named: 11kV.
- Downstream impact
- Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- What it achieves
- It is built from the tolerance km helper (`tolerance_km`), the band for helper (`band_for`) and the latest grid proximity helper (`latest_grid_proximity`). Build the grid-distance payload: one number per project, for the table column. Its code works with 11 kV and 5 MW. It accepts `--gen` and `--source`.
- Why it matters
- Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-distance-column · Python CLI
- Uses
- argparse, glob, hashlib, io, json, math, os, sys
- Used by
- named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- tolerance_km, band_for, latest_grid_proximity, round_km, main
- Defines here
- tolerance_km, band_for, latest_grid_proximity, round_km, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-distance-column/build_payload.py:1-329 · blob c0a0525387315802dca8c196cde59e6469e8453d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Build the grid-distance payload: one number per project, for the table column.
WHY THIS IS NOT THE GRID PROXIMITY PAYLOAD
------------------------------------------
The GRID panel's payload is 5.5 MB. It carries, for every project, the nearest
circuit at each of seven voltages with the foot of each perpendicular, every
substation within reach, and the transmission/distribution split. That is the
right shape for a panel a user opens for one project at a time, and it is
fetched lazily when they open it.
A table column needs one number for every row before the first paint. Fetching
5.5 MB to render a column would be the wrong trade by a factor of thirty, so
this builds a slim index -- nearest circuit, its voltage, the transmission and
distribution answers, and the screening band -- keyed by REPD ref.
WHERE THE NUMBERS COME FROM
---------------------------
They are not recomputed from the network layers. They are carried across from
the published grid-proximity payload, so the column and the panel can never
disagree: the column IS the panel's number, to the metre.
What this script does do is CHECK them. The published payload stores the foot
of each perpendicular alongside its distance, so every row can be re-measured
from the site coordinate to that foot using the canonical geodesy in
Ventusltd/grid-distance-maths, and compared. The comparison is made against a
bound derived from the source's own rounding -- 3 dp on distances, 6 dp on
coordinates -- because that is the finest agreement the stored data can
support. If any row disagrees by more than that, this fails and writes
nothing.
That check is the point of the exercise. It is what turns "the panel and the
Atlas use the same formula" from an assertion into something a build proves.
python build_payload.py # writes data/{GEN}-grid-distance.json
python build_payload.py --gen 202609010812
python build_payload.py --source ../../../../releases/<id>/data/<gen>-grid-proximity.json
"""
import argparse
import glob
import hashlib
import io
import json
import math
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
# cartridges/grid-distance-column -> cartridges -> intelligence -> tools -> repo
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
WORKSPACE = os.path.dirname(REPO)
OUT = os.path.join(HERE, "data", "{GEN}-grid-distance.json")
# The geodesy is imported from the canonical repository, never copied into this
# one. A local copy is precisely the failure this cartridge is meant to close:
# the estate had four implementations on three Earth radii because every
# consumer carried its own. If the repo is not beside this one, that is a setup
# error and the build stops -- it does not quietly fall back.
GEODESY_SRC = os.path.join(WORKSPACE, "grid-distance-maths", "src")
if not os.path.isfile(os.path.join(GEODESY_SRC, "geodesy.py")):
raise SystemExit(
"canonical geodesy not found at %s\n"
"Clone Ventusltd/grid-distance-maths beside this repository.\n"
"This script will not fall back to a local copy of the formula; that is "
"the defect the repository exists to prevent." % GEODESY_SRC)
sys.path.insert(0, GEODESY_SRC)
import geodesy as G # noqa: E402
# The tolerance is DERIVED from how the source stores its numbers, not picked.
#
# The published payload rounds every distance to 3 decimal places of a kilometre
# and every coordinate -- the site AND the foot of the perpendicular -- to 6
# decimal places of a degree. Re-measuring between two rounded endpoints and
# comparing against a rounded distance cannot agree to better than the sum of
# those roundings, however identical the arithmetic is.
#
# Two earlier attempts at this constant were wrong in instructive ways. A
# millimetre tolerance failed 3,042 of 3,047 rows at a worst disagreement of
# 0.58 m -- rounding, not divergence. Counting the foot's rounding but not the
# site's still failed two rows, because both endpoints are stored rounded and
# both contribute. The bound below counts every source of rounding actually
# present in the file, and is computed from the file rather than asserted:
# `tolerance_km()` takes the widest per-coordinate error over the latitudes the
# data really spans, so it cannot silently go stale if the register moves.
#
# What the check proves is therefore the strongest claim the source supports:
# the canonical geodesy reproduces every published distance to within the
# published payload's own precision. A real divergence -- a different radius,
# the asin form, a vertex instead of a foot -- is orders of magnitude larger
# than this bound and would still fail loudly.
KM_DECIMALS = 3
COORD_DECIMALS = 6
KM_PER_DEG_LAT = 111.32
def tolerance_km(latitudes):
"""The largest disagreement rounding alone can produce, for these latitudes.
Half a unit in the last place of the distance, plus the displacement a half
ULP of latitude and longitude can move each of the two endpoints. Longitude
degrees shrink with latitude, so the worst case is the lowest latitude in
the data, not the mean.
"""
km_rounding = 0.5 * 10 ** -KM_DECIMALS
half = 0.5 * 10 ** -COORD_DECIMALS
lowest = min((abs(v) for v in latitudes), default=0.0)
kx = KM_PER_DEG_LAT * math.cos(math.radians(lowest))
per_endpoint = math.hypot(half * kx, half * KM_PER_DEG_LAT)
return km_rounding + 2 * per_endpoint
BANDS = (
("STRONG", 2.0),
("MODERATE", 5.0),
("DISTANT", 15.0),
)
def band_for(km):
"""The screening band, recomputed here from the circuit distance alone.
The panel's band also considers substation distance; this column shows only
a circuit distance, so it states the circuit band and nothing more. A band
is a statement about how close the mapped network is. It is not a statement
that a connection is obtainable, and nothing downstream may read it as one.
"""
if km is None:
return None
for name, limit in BANDS:
if km <= limit:
return name
return "REMOTE"
def latest_grid_proximity():
"""The newest published grid-proximity payload in releases/."""
hits = sorted(glob.glob(os.path.join(
RELEASES, "*-pipelinenews", "data", "*-grid-proximity.json")))
if not hits:
raise SystemExit("no grid-proximity payload found under %s" % RELEASES)
return hits[-1]
def round_km(v):
"""Three decimals: a metre. The panel quotes 10 m and says why that is the
limit -- the site coordinate is a register centroid. A metre in the payload
keeps the column's sort stable without implying more than the panel does."""
return None if v is None else round(v, 3)
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--gen", default="{GEN}", help="12-digit generation")
ap.add_argument("--source", help="grid-proximity payload to carry across")
a = ap.parse_args()
source = a.source or latest_grid_proximity()
src = json.loads(io.open(source, encoding="utf-8").read())
print("source %s" % os.path.relpath(source, REPO).replace("\\", "/"))
print("schema %s" % src.get("schema"))
print("rows %d" % len(src.get("rows", [])))
radius = src["earth_model"]["radius_km"]
if radius != G.R_ATLAS:
raise SystemExit(
"source payload was built on radius %r, canonical is %r; refusing to "
"carry numbers across a radius change" % (radius, G.R_ATLAS))
out = {}
stats = {"rows": 0, "with_circuit": 0, "no_circuit": 0,
"transmission": 0, "distribution": 0, "checked": 0}
bands = {}
worst = {"delta": 0.0, "ref": None, "published": None, "measured": None}
failures = []
# Derive the tolerance from the coordinates actually in this file, before
# checking anything against it.
tol = tolerance_km([(r.get("at") or [None, None])[1]
for r in src.get("rows", [])
if (r.get("at") or [None, None])[1] is not None])
for row in src.get("rows", []):
ref = str(row.get("ref") or "").strip()
if not ref:
continue
stats["rows"] += 1
at = row.get("at") or []
circuit = row.get("circuit") or {}
km = circuit.get("km")
# Re-measure against the canonical implementation. The published payload
# stores the foot of the perpendicular, so this is an exact check of the
# same question, not an approximation of it.
if km is not None and len(at) == 2 and len(circuit.get("foot") or []) == 2:
foot = circuit["foot"]
measured = G.distance_km(at[0], at[1], foot[0], foot[1])
delta = abs(measured - km)
stats["checked"] += 1
if delta > worst["delta"]:
worst = {"delta": delta, "ref": ref,
"published": km, "measured": measured}
if delta > tol:
failures.append((ref, km, measured, delta))
if km is None:
stats["no_circuit"] += 1
continue
stats["with_circuit"] += 1
entry = {"k": round_km(km)}
if circuit.get("kv"):
entry["v"] = circuit["kv"]
transmission = (row.get("circuit_transmission") or {}).get("km")
distribution = (row.get("circuit_distribution") or {}).get("km")
if transmission is not None:
entry["t"] = round_km(transmission)
entry["tv"] = (row.get("circuit_transmission") or {}).get("kv")
stats["transmission"] += 1
if distribution is not None:
entry["d"] = round_km(distribution)
entry["dv"] = (row.get("circuit_distribution") or {}).get("kv")
stats["distribution"] += 1
entry["b"] = band_for(km)
bands[entry["b"]] = bands.get(entry["b"], 0) + 1
out[ref] = entry
print("\nverification against Ventusltd/grid-distance-maths")
print(" rows re-measured %d" % stats["checked"])
print(" worst disagreement %.3e km (ref %s)"
% (worst["delta"], worst["ref"]))
print(" rounding bound %.3e km" % tol)
print(" derived from the source's own 3 dp "
"distances and 6 dp coordinates")
if failures:
print("\n%d rows disagree beyond tolerance. Writing nothing." % len(failures))
for ref, pub, meas, delta in failures[:10]:
print(" ref %-8s published %.6f canonical %.6f delta %.3e"
% (ref, pub, meas, delta))
return 1
print(" RESULT the canonical geodesy reproduces every "
"published distance")
payload = {
"schema": "pipelinenews.grid-distance.v1",
"generation": a.gen,
"projects": len(out),
"network_at_runtime": False,
"carried_from": {
"schema": src.get("schema"),
"generation": src.get("generation"),
"note": "The column shows the panel's own number. It is carried "
"across, not recomputed, so the two can never disagree.",
},
"earth_model": {
"formula": "haversine",
"radius_km": G.R_ATLAS,
"implementation": "Ventusltd/grid-distance-maths src/geodesy.py",
"verified": {
"method": "every published distance re-measured from the site "
"coordinate to the stored foot of the perpendicular",
"rows": stats["checked"],
"worst_delta_km": worst["delta"],
"tolerance_km": tol,
"tolerance_basis": "the source payload rounds distances to 3 dp "
"of a km and feet to 6 dp of a degree; the "
"tolerance is the sum of those two roundings, "
"so this asserts agreement to the published "
"precision and no further",
},
},
"bands": {
"purpose": "A screening band from measured geometry. It says how "
"close the mapped network is, not whether a connection "
"is obtainable.",
"STRONG": "circuit within 2 km",
"MODERATE": "circuit within 5 km",
"DISTANT": "circuit within 15 km",
"REMOTE": "nearest mapped circuit beyond 15 km",
"counts": bands,
},
"beta": {
"status": "BETA",
"meaning": "The measurement is published and checked. What it does "
"not yet cover is stated below, so the number can be "
"used for screening with its limits known.",
"not_covered": [
"11 kV, except an estimated UKPN layer; most sub-5 MW "
"distribution connections are made at a voltage this column "
"cannot see",
"the point of connection, which is not the site centroid the "
"register supplies",
"connection queue position, curtailment and contracted capacity",
],
},
"caveat": dict(G.STRAIGHT_LINE_CAVEAT),
"provenance": src.get("provenance", {}),
"coverage": {
"with_circuit": stats["with_circuit"],
"no_circuit": stats["no_circuit"],
"note": "A project with no entry has no mapped circuit found, or no "
"coordinate in the register. It is shown as a dash, never "
"as a large number.",
},
"grid": out,
}
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
path = OUT.replace("{GEN}", a.gen) if a.gen != "{GEN}" else OUT
os.makedirs(os.path.dirname(path), exist_ok=True)
io.open(path, "w", encoding="utf-8", newline="").write(body)
digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
io.open(path + ".sha256", "w", encoding="utf-8", newline="").write(
digest + " " + os.path.basename(path) + "\n")
print("\nwrote %s (%s bytes)"
% (os.path.basename(path), format(len(body.encode("utf-8")), ",")))
for k in ("rows", "with_circuit", "no_circuit", "transmission", "distribution"):
print(" %-14s %6d" % (k, stats[k]))
for k in ("STRONG", "MODERATE", "DISTANT", "REMOTE"):
print(" %-14s %6d" % (k.lower(), bands.get(k, 0)))
return 0
if __name__ == "__main__":
raise SystemExit(main())Make Cartridge
A Python command-line tool in the grid distance column folder of PipelineNews covering postcodes and cables, using SHA-256 and haversine.
renderpipelinenews / tools/intelligence/cartridges/grid-distance-column/make_cartridge.py · lines 1–346 of 346 · Entry point · pattern anchor (shared by 16 files)
- What it does
- It lists and searches postcodes and cables. Defines read, anchor, main. Uses libraries argparse, io, json, os, sys. Side effects: changes the web page (DOM); starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, cables, 11kV.
- Inputs & outputs
- In: JSON file cartridge.json; command-line arguments. Voltage levels named: 11kV.
- 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 read step (`read`) and the anchor step (`anchor`). Generate `cartridge.json` for the grid-distance column. Its code works with 11 kV and 5 MW. It accepts `--parent`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-distance-column · Python CLI
- Uses
- argparse, io, json, os, sys
- Used by
- none found
- Produces
- read, anchor, main
- Defines here
- read, anchor, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-distance-column/make_cartridge.py:1-346 · blob 66e023abd61e22697f604a7d4761678e79ad9491 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Generate cartridge.json for the grid-distance column.
The manifest is a list of exact from -> to string repairs against the parent
release. Typing those anchors by hand is how you ship a build that fails on an
invisible character: the sort options contain both an em dash and an en dash,
and the table markup is indentation-sensitive.
So the anchors are not typed. They are READ out of the parent release and
asserted unique before the manifest is written. If an anchor is missing or
appears twice, this stops rather than producing a manifest that will fail
half-way through a build.
python make_cartridge.py --parent 202608311731-pipelinenews
"""
import argparse
import io
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
APP = "assets/202608291447-app.mjs"
def read(path):
return io.open(path, encoding="utf-8", newline="").read()
def anchor(text, needle, label):
"""Assert a repair anchor exists exactly once, and hand it back."""
n = text.count(needle)
if n != 1:
raise SystemExit("anchor %r occurs %d times, expected 1:\n%s"
% (label, n, needle[:200]))
return needle
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--parent", default="202608311731-pipelinenews")
a = ap.parse_args()
parent = os.path.join(RELEASES, a.parent)
if not os.path.isdir(parent):
raise SystemExit("no such parent release: %s" % parent)
idx = read(os.path.join(parent, "index.html"))
app = read(os.path.join(parent, APP))
repairs_index = []
repairs_app = []
# ---- 1. styles -------------------------------------------------------
css_from = anchor(idx, " .locality-note { color: #8d98a5; font-size: 9px; }",
"locality-note css")
css_to = css_from + """
/* GRID column. The BETA chip is a scope marker, not a disclaimer: the
measurement is published and checked, and the chip says which questions
it does not answer. Amber rather than red for that reason. */
.beta-chip {
font-size: 8px; letter-spacing: .06em; padding: 1px 3px; border-radius: 2px;
background: #3a2f12; color: #e0b050; border: 1px solid #6a5320;
vertical-align: 1px;
}
.grid-cell { white-space: nowrap; font-variant-numeric: tabular-nums; }
.grid-cell .km { color: #d8dee6; }
.grid-cell .kv { color: #8d98a5; font-size: 9px; margin-left: 3px; }
/* Band tints the distance only. Bands describe how close the mapped
network is; they never imply a connection is obtainable. */
.grid-cell[data-band="STRONG"] .km { color: #6fd18a; }
.grid-cell[data-band="MODERATE"] .km { color: #d8c96a; }
.grid-cell[data-band="DISTANT"] .km { color: #d89a6a; }
.grid-cell[data-band="REMOTE"] .km { color: #b06a6a; }
.grid-note { color: #8d98a5; font-size: 9px; }"""
repairs_index.append({"label": "GRID column styles and BETA chip",
"from": css_from, "to": css_to})
# ---- 2. table heading ------------------------------------------------
th_from = anchor(idx,
' <th class="hide-mobile">OPERATOR</th>\n'
' <th>TECHNOLOGY</th>',
"operator/technology headings")
th_to = (' <th class="hide-mobile sortable-heading" id="gridHeader" aria-sort="none">\n'
' <button id="sortGrid" type="button" aria-label="Sort by straight-line distance to the nearest mapped grid circuit">\n'
' GRID <span class="beta-chip">BETA</span> <span id="gridSortIndicator" aria-hidden="true">↕</span>\n'
' </button>\n'
' </th>\n') + th_from
repairs_index.append({"label": "GRID heading, sortable, after POSTCODE",
"from": th_from, "to": th_to})
# ---- 3. the note beside the filters ----------------------------------
note_from = anchor(idx,
' <span class="locality-note" id="localityNote">TOWN + POSTCODE · loading…</span>',
"locality note span")
note_to = (note_from + '\n'
' <span class="grid-note" id="gridDistanceNote">GRID · loading…</span>')
repairs_index.append({"label": "GRID note beside the locality note",
"from": note_from, "to": note_to})
# ---- 4. sort options -------------------------------------------------
# Read the postcode option line out of the file so the dashes match.
line = [ln for ln in idx.split("\n") if 'value="postcode_desc"' in ln]
if len(line) != 1:
raise SystemExit("expected exactly one postcode_desc option")
opt_from = anchor(idx, line[0], "postcode_desc option")
opt_to = (opt_from + '\n'
' <option value="grid_asc">SORT: GRID DISTANCE — NEAREST</option>\n'
' <option value="grid_desc">SORT: GRID DISTANCE — FURTHEST</option>')
repairs_index.append({"label": "GRID sort options in the sort select",
"from": opt_from, "to": opt_to})
# ---- 5. app: sort modes ---------------------------------------------
sorts_from = anchor(app,
'const SORTS = new Set(["capacity_desc", "capacity_asc", "updated_desc", "updated_asc",\n'
' "county_asc", "county_desc", "town_asc", "town_desc", "postcode_asc", "postcode_desc"]);',
"SORTS set")
sorts_to = ('const SORTS = new Set(["capacity_desc", "capacity_asc", "updated_desc", "updated_asc",\n'
' "county_asc", "county_desc", "town_asc", "town_desc", "postcode_asc", "postcode_desc",\n'
' "grid_asc", "grid_desc"]);')
repairs_app.append({"label": "grid sort modes", "from": sorts_from, "to": sorts_to})
head_from = anchor(app,
' postcode: { header: "postcodeHeader", indicator: "postcodeSortIndicator", asc: "postcode_asc", desc: "postcode_desc", first: "postcode_asc" },',
"postcode SORT_HEADINGS entry")
head_to = (head_from + '\n'
' // Nearest first: the screening question is "what is close", so the\n'
' // first click answers it rather than showing the most remote sites.\n'
' grid: { header: "gridHeader", indicator: "gridSortIndicator", asc: "grid_asc", desc: "grid_desc", first: "grid_asc" },')
repairs_app.append({"label": "grid heading wiring", "from": head_from, "to": head_to})
# ---- 6. app: the payload and its accessor ---------------------------
state_from = anchor(app,
'function localityFor(item) {\n'
' return (locality && locality[String(item.repd_ref)]) || null;\n'
'}',
"localityFor")
state_to = state_from + '''
// The grid-distance payload: the nearest mapped circuit per REPD ref, carried
// across from the GRID panel's own payload and verified at build time against
// Ventusltd/grid-distance-maths. Slim on purpose -- the panel's payload is
// 5.5 MB and is fetched only when a user opens it; this is 240 KB and is
// fetched once at boot because a column needs every row.
//
// Null until it lands, and null forever if the fetch fails. The column then
// reads "-" and every other column is untouched.
let gridDistance = null;
function gridFor(item) {
return (gridDistance && gridDistance[String(item.repd_ref)]) || null;
}
// A distance the register cannot support is a dash, never a zero and never a
// large number standing in for "not found". Absence from a mapped layer is not
// absence on the ground.
function gridCellHtml(item) {
if (!gridDistance) return "\\u2026";
const hit = gridFor(item);
if (!hit || typeof hit.k !== "number") return "-";
const parts = [`Nearest mapped circuit ${hit.k.toFixed(2)} km${hit.v ? ` at ${hit.v} kV` : ""}`];
if (typeof hit.t === "number") parts.push(`transmission ${hit.t.toFixed(2)} km${hit.tv ? ` (${hit.tv} kV)` : ""}`);
if (typeof hit.d === "number") parts.push(`distribution ${hit.d.toFixed(2)} km${hit.dv ? ` (${hit.dv} kV)` : ""}`);
parts.push("Straight-line to mapped geometry, not a cable route or a connection length.");
parts.push("Fault level and thermal headroom are not shown and cannot be inferred from distance: they need DNO network data such as source impedance and are established by a connection study.");
const band = hit.b ? ` data-band="${escapeHtml(hit.b)}"` : "";
return `<span${band} title="${escapeHtml(parts.join(" \\u00b7 "))}"><span class="km">${hit.k.toFixed(2)}</span><span class="kv">km${hit.v ? ` \\u00b7 ${hit.v}kV` : ""}</span></span>`;
}'''
repairs_app.append({"label": "grid payload state and cell renderer",
"from": state_from, "to": state_to})
# ---- 7. app: the cell ------------------------------------------------
cell_from = anchor(app,
'<td class="hide-mobile reference-cell">${escapeHtml(place?.postcode || "-")}</td>',
"postcode cell")
cell_to = cell_from + '<td class="hide-mobile grid-cell">${gridCellHtml(item)}</td>'
repairs_app.append({"label": "GRID cell in the row", "from": cell_from, "to": cell_to})
# ---- 8. app: the sort ------------------------------------------------
sort_from = anchor(app,
' } else if (sortMode === "postcode_asc" || sortMode === "postcode_desc") {\n'
' const direction = sortMode === "postcode_asc" ? 1 : -1;\n'
' next.sort((left, right) =>\n'
' compareText(localityFor(project(left))?.postcode, localityFor(project(right))?.postcode, direction) || left - right);',
"postcode sort branch")
sort_to = sort_from + '''
} else if (sortMode === "grid_asc" || sortMode === "grid_desc") {
// Blanks sort last in BOTH directions, exactly as postcode does. A project
// with no mapped circuit has not got an infinite distance and has not got a
// zero one; pushing it to the bottom either way keeps the measured rows
// contiguous, which is the whole point of sorting by proximity.
const direction = sortMode === "grid_asc" ? 1 : -1;
next.sort((left, right) => {
const a = gridFor(project(left))?.k;
const b = gridFor(project(right))?.k;
const aMissing = typeof a !== "number";
const bMissing = typeof b !== "number";
if (aMissing && bMissing) return left - right;
if (aMissing) return 1;
if (bMissing) return -1;
return (a - b) * direction || left - right;
});'''
repairs_app.append({"label": "grid distance sort, blanks last both ways",
"from": sort_from, "to": sort_to})
# ---- 9. app: the loader ---------------------------------------------
loader_from = anchor(app, "async function loadLocality() {", "loadLocality")
loader_to = '''async function loadGridDistance() {
const entry = registry.supplemental_assets?.grid_distance_column;
const note = document.getElementById("gridDistanceNote");
if (!entry) {
if (note) note.textContent = "GRID \\u00b7 not in this release";
return;
}
try {
runtimeEvidence.gridDistanceRequests += 1;
const payload = await fetchImmutable(entry.payload.path);
invariant(payload.schema === entry.payload.schema, "grid-distance schema mismatch");
invariant(payload.generation === entry.generation, "grid-distance generation mismatch");
invariant(payload.grid && typeof payload.grid === "object", "grid-distance index missing");
gridDistance = payload.grid;
runtimeEvidence.gridDistanceReady = true;
if (note) {
const counts = payload.bands?.counts || {};
const strong = (counts.STRONG || 0).toLocaleString("en-GB");
note.textContent = `GRID \\u00b7 BETA \\u00b7 straight-line km to the nearest mapped circuit \\u00b7 `
+ `${(payload.projects || 0).toLocaleString("en-GB")} measured, ${strong} within 2 km \\u00b7 `
+ `not a cable route, and not headroom`;
// The full scope of the BETA sits on hover rather than in the strip, so
// the caveat is one gesture away without crowding the filter row.
note.title = [
payload.caveat?.distance,
payload.caveat?.headroom,
payload.caveat?.coverage,
payload.beta?.not_covered?.length
? "Not covered in this beta: " + payload.beta.not_covered.join("; ")
: "",
payload.earth_model
? `Measured on ${payload.earth_model.formula} at R = ${payload.earth_model.radius_km} km using ${payload.earth_model.implementation}; every published distance re-measured and reproduced at build time.`
: "",
].filter(Boolean).join("\\n\\n");
}
} catch (error) {
// A grid payload that will not load must not take the table with it.
gridDistance = null;
if (note) note.textContent = "GRID \\u00b7 unavailable in this session";
}
}
''' + loader_from
repairs_app.append({"label": "grid-distance loader", "from": loader_from, "to": loader_to})
boot_from = anchor(app, " await loadLocality();", "loadLocality call in boot")
boot_to = boot_from + "\n await loadGridDistance();"
repairs_app.append({"label": "load the grid payload during boot",
"from": boot_from, "to": boot_to})
ev_from = anchor(app, " localityRequests: 0,\n localityReady: false,",
"runtimeEvidence locality fields")
ev_to = ev_from + "\n gridDistanceRequests: 0,\n gridDistanceReady: false,"
repairs_app.append({"label": "runtime evidence counters", "from": ev_from, "to": ev_to})
span_from = anchor(app, '<tr><td colspan="13" class="fast-fail">', "fail-closed colspan")
span_to = '<tr><td colspan="14" class="fast-fail">'
repairs_app.append({"label": "fail-closed row spans the new column count",
"from": span_from, "to": span_to})
# ---- manifest --------------------------------------------------------
man = {
"key": "grid_distance_column",
"summary": ("A GRID column in the main table: straight-line distance to "
"the nearest mapped circuit, sortable nearest-first, marked "
"BETA. The number is the GRID panel's own, carried across "
"and verified at build time against the canonical geodesy in "
"Ventusltd/grid-distance-maths."),
"modifies_existing_dashboard": True,
"modification_note": ("This cartridge is NOT panel-only. It adds a column "
"to the project table, a sort mode, a note beside "
"the filters, and it widens the fail-closed row, so "
"it patches the table renderer, the sort modes and "
"the boot sequence."),
"repairs": {"index.html": repairs_index, "app": repairs_app},
"hash_fields": [{"at": ["payload", "sha256"],
"path": "data/{GEN}-grid-distance.json"}],
"registry_entry": {
"schema": "pipelinenews.grid-distance-supplemental-asset.v1",
"generation": "{GEN}",
"usage_context": "NON_COMMERCIAL_OPEN_SOURCE",
"usage_context_establishes_upstream_rights": False,
"activation": "fetched once during boot, before the first table paint; fails soft",
"additive_only": False,
"mutates_existing_dashboard": ("adds a GRID column and a grid-distance "
"sort mode to the project table"),
"network_at_runtime": False,
"payload": {"schema": "pipelinenews.grid-distance.v1",
"path": "data/{GEN}-grid-distance.json",
"sha256": "", "bytes": 0},
"maturity": {
"status": "BETA",
"means": ("The measurement is published and checked. BETA marks "
"what it does not yet cover, so it can be used for "
"screening with its limits known. It is not a warning "
"that the number is unreliable."),
"not_covered": [
"11 kV beyond an estimated UKPN layer, the voltage most "
"sub-5 MW distribution connections are actually made at",
"the point of connection, which is not the register centroid "
"the distance is measured from",
"connection queue position, curtailment and contracted capacity",
],
"cannot_be_inferred": (
"Fault level and thermal headroom. These are properties of "
"the network, not of the geometry: they depend on DNO data "
"such as source impedance, fault infeed and existing "
"committed connections, and are established by a connection "
"study. No distance, at any precision, implies them."),
},
"provenance": {
"geometry": ("OpenStreetMap-derived overhead line and substation "
"layers, ODbL-1.0, (c) OpenStreetMap contributors."),
"projects": ("DESNZ Renewable Energy Planning Database, Open "
"Government Licence v3.0."),
"mathematics": ("Ventusltd/grid-distance-maths src/geodesy.py, "
"haversine at R = 6378.137 km, point projected "
"onto the segment on a local tangent plane. Every "
"published distance was re-measured against it at "
"build time and reproduced within the source "
"payload's own rounding."),
},
},
}
out = os.path.join(HERE, "cartridge.json")
io.open(out, "w", encoding="utf-8", newline="").write(
json.dumps(man, ensure_ascii=False, indent=2) + "\n")
print("wrote cartridge.json")
print(" index.html repairs %d" % len(repairs_index))
print(" app.mjs repairs %d" % len(repairs_app))
print(" every anchor verified unique in %s" % a.parent)
return 0
if __name__ == "__main__":
sys.exit(main())