In this section
- Build Exact Renewable Energy Planning Database (REPD) Deep Link Successor energy-data · gridatlas / compiler/202608300453-build-exact-repd-deep-link-successor.py lines 1–258
- Compile Atlas V9 storage · gridatlas / compiler/202611132345-compile-atlas-v9.py lines 1–250
- GridAtlas — Index Page render · gridatlas / index.html lines 1–2
Build Exact Renewable Energy Planning Database (REPD) Deep Link Successor
A Python command-line tool in the compiler folder of GridAtlas that reads grid 400kV, map ready and deep link receiver, using SHA-256. It replaces once (`replace_once`) and writes JSON (`write_json`).
energy-datagridatlas / compiler/202608300453-build-exact-repd-deep-link-successor.py · lines 1–258 of 258 · version 2026-08-30 04:53 · Entry point · pattern replace_once (shared by 21 files)
- What it does
- It loads grid 400kV, map ready and deep link receiver. Defines replace_once, sha256, write_json, main. Uses libraries __future__, argparse, hashlib, json, shutil. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): 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: 400kV.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; JSON file build-manifest.json; JSON file map-ready-manifest.json; JSON file release-manifest.json; JSON file deep-link-receiver-manifest.json; command-line arguments. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (gridatlas).
- What it achieves
- Build an immutable GridAtlas successor that receives exact REPD deep links. Its code works with 400 kV. It writes `deep-link-receiver-manifest.json`. It accepts `--parent`, `--output` and `--release-id`.
- Why it matters
- Run by Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link.
- Application
- gridatlas · compiler · Python CLI
- Uses
- __future__, argparse, hashlib, json, shutil, pathlib
- Used by
- run by Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (workflow run)
- Produces
- replace_once, sha256, write_json, main
- Defines here
- replace_once, sha256, write_json, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 compiler/202608300453-build-exact-repd-deep-link-successor.py:1-258 · blob efb22f86719e94275b66825324b9152c0e4c41ca · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build an immutable GridAtlas successor that receives exact REPD deep links."""
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
from pathlib import Path
SEARCH_FILE = "202608291818-place-postcode-search.js"
GENERATION = "202608300453"
SHARED_CARTRIDGE = Path(
"cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson"
)
def replace_once(source: str, before: str, after: str, label: str) -> str:
count = source.count(before)
if count != 1:
raise RuntimeError(f"{label}: expected one anchor, found {count}")
return source.replace(before, after, 1)
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def write_json(path: Path, value: object) -> None:
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--parent", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--release-id", required=True)
parser.add_argument("--parent-release-id", required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
if args.output.exists():
raise RuntimeError(f"output already exists: {args.output}")
if args.parent.name != args.parent_release_id:
raise RuntimeError("parent folder and parent release id disagree")
if not args.parent.is_dir():
raise RuntimeError("immutable parent is missing")
if not SHARED_CARTRIDGE.is_file():
raise RuntimeError(f"shared 400 kV cartridge is missing: {SHARED_CARTRIDGE}")
shutil.copytree(args.parent, args.output)
local_cartridge = args.output.parent / SHARED_CARTRIDGE
local_cartridge.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(SHARED_CARTRIDGE, local_cartridge)
if sha256(local_cartridge) != sha256(SHARED_CARTRIDGE):
raise RuntimeError("local shared 400 kV cartridge digest mismatch")
search_path = args.output / SEARCH_FILE
source = search_path.read_text(encoding="utf-8")
source = replace_once(
source,
" generation: '202608291818',",
f" generation: '{GENERATION}',",
"search generation",
)
source = replace_once(
source,
" failures: []\n",
" failures: [],\n"
" deep_link: { status: 'IDLE', repd_ref: null, resolved: false, mapped: false }\n",
"deep-link state",
)
receiver = r'''
async function waitForCapturedMap(timeoutMs = 60000) {
const started = performance.now();
while (performance.now() - started < timeoutMs) {
const map = window.__GRIDATLAS_V9_MAP__;
if (map && typeof map.flyTo === 'function') return map;
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error('GridAtlas map was not captured for exact REPD deep link');
}
async function receiveExactRepdDeepLink(input, resultsEl) {
const repdRef = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
if (!repdRef) {
state.deep_link = { status: 'ABSENT', repd_ref: null, resolved: false, mapped: false };
return;
}
state.deep_link = { status: 'RECEIVING', repd_ref: repdRef, resolved: false, mapped: false };
try {
invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
input.value = repdRef;
const results = await queryOfficialRepd(repdRef);
const exact = results.find(result => String(result.repd_ref) === repdRef);
invariant(exact, `official REPD identity ${repdRef} was not found`);
renderResults(results, resultsEl);
await waitForCapturedMap();
selectResult(exact);
invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
document.body.dataset.gridatlasRepdRef = repdRef;
document.body.dataset.gridatlasRepdDeepLink = 'resolved';
state.deep_link = {
status: 'RESOLVED',
repd_ref: repdRef,
resolved: true,
mapped: true,
name: exact.name,
postcode: exact.postcode,
longitude: exact.longitude,
latitude: exact.latitude
};
} catch (error) {
const message = String(error?.message || error);
state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
state.deep_link = { status: 'FAILED', repd_ref: repdRef, resolved: false, mapped: false, message };
document.body.dataset.gridatlasRepdDeepLink = 'failed';
console.error('[V9 EXACT REPD DEEP LINK]', error);
}
}
'''
source = replace_once(source, " function bindSearch() {", receiver + "\n function bindSearch() {", "receiver insertion")
old_boot = """ window.addEventListener('DOMContentLoaded', () => {
try {
bindSearch();
} catch (error) {
state.failures.push({ phase: 'bind', message: String(error?.message || error) });
console.error('[V9 PLACE SEARCH INIT]', error);
}
}, { once: true });
"""
new_boot = """ window.addEventListener('DOMContentLoaded', () => {
try {
bindSearch();
const input = document.getElementById('search-input');
const resultsEl = document.getElementById('search-results');
void receiveExactRepdDeepLink(input, resultsEl);
} catch (error) {
state.failures.push({ phase: 'bind', message: String(error?.message || error) });
console.error('[V9 PLACE SEARCH INIT]', error);
}
}, { once: true });
"""
source = replace_once(source, old_boot, new_boot, "DOMContentLoaded receiver")
search_path.write_text(source, encoding="utf-8", newline="\n")
build_path = args.output / "build-manifest.json"
build = json.loads(build_path.read_text(encoding="utf-8"))
build.update(
generation=GENERATION,
release_id=args.release_id,
source_commit=args.source_commit,
parent_release_id=args.parent_release_id,
classification="DETERMINISTIC_BUILD_COMPLETE",
exact_repd_deep_link_receiver=True,
exact_repd_identity_parameter="repd_ref",
exact_repd_search_cartridge=SEARCH_FILE,
)
write_json(build_path, build)
map_path = args.output / "map-ready-manifest.json"
map_ready = json.loads(map_path.read_text(encoding="utf-8"))
map_ready.update(generation=GENERATION, release_id=args.release_id, source_commit=args.source_commit)
map_ready.setdefault("architecture", {})["exact_repd_deep_link_receiver"] = True
write_json(map_path, map_ready)
release_path = args.output / "release-manifest.json"
release = json.loads(release_path.read_text(encoding="utf-8"))
release.update(
generation=GENERATION,
release_id=args.release_id,
parent_release_id=args.parent_release_id,
source_commit=args.source_commit,
classification="V8_RENDER_READY_EXACT_REPD_DEEP_LINK_CANDIDATE",
product_surface="PINNED_V8_WITH_WORKER_SOURCE_400KV_AND_EXACT_REPD_RECEIVER",
)
release["deep_link_receiver"] = {
"schema": "gridatlas.exact-repd-deep-link-receiver.v1",
"identity_parameter": "repd_ref",
"identity_rule": "EXACT_REPD_REF_ONLY",
"official_source": "DESNZ_REPD_Q2_2026_PARQUET",
"automatic_search": True,
"automatic_fly_to": True,
"synthetic_receiver": False,
"route_interceptions": 0,
"privacy": "NO_PERSONAL_DATA",
}
release["machine_learning_record"] = {
"schema": "gridatlas.ml.render-ready-performance-record.v1",
"path": f"machine-learning/records/{GENERATION}-render-ready-performance.jsonl",
"task": "binary_release_promotion",
"positive_label": "PROMOTE",
"negative_label": "REJECT",
"privacy": "NO_PERSONAL_DATA",
}
write_json(release_path, release)
receiver_manifest = {
"schema": "gridatlas.exact-repd-deep-link-build.v1",
"classification": "DETERMINISTIC_EXACT_REPD_RECEIVER_BUILT",
"generation": GENERATION,
"release_id": args.release_id,
"parent_release_id": args.parent_release_id,
"source_commit": args.source_commit,
"identity_parameter": "repd_ref",
"identity_rule": "EXACT_REPD_REF_ONLY",
"search_cartridge": SEARCH_FILE,
"search_cartridge_sha256": sha256(search_path),
"local_test_shared_cartridge": SHARED_CARTRIDGE.as_posix(),
"local_test_shared_cartridge_sha256": sha256(local_cartridge),
"immutable_parent_files_changed": [
SEARCH_FILE,
"build-manifest.json",
"map-ready-manifest.json",
"release-manifest.json",
"sha256sums.txt",
],
"v8_html_changed": False,
"v8_css_changed": False,
"v8_engine_changed": False,
"map_ready_data_changed": False,
"privacy": "NO_PERSONAL_DATA",
}
write_json(args.output / "deep-link-receiver-manifest.json", receiver_manifest)
sums: list[str] = []
for path in sorted(item for item in args.output.rglob("*") if item.is_file()):
relative = path.relative_to(args.output).as_posix()
if relative == "sha256sums.txt":
continue
sums.append(f"{sha256(path)} {relative}")
(args.output / "sha256sums.txt").write_text("\n".join(sums) + "\n", encoding="utf-8", newline="\n")
result = {
"classification": "DETERMINISTIC_EXACT_REPD_RECEIVER_BUILT",
"generation": GENERATION,
"release_id": args.release_id,
"parent_release_id": args.parent_release_id,
"search_cartridge_sha256": sha256(search_path),
"local_test_shared_cartridge": local_cartridge.as_posix(),
"local_test_shared_cartridge_sha256": sha256(local_cartridge),
"v8_html_changed": False,
"v8_css_changed": False,
"v8_engine_changed": False,
"map_ready_data_changed": False,
}
print(json.dumps(result, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())Compile Atlas V9
A Python command-line tool in the compiler folder of GridAtlas that reads Renewable Energy Planning Database (REPD) publication q3, REPD q3 cleaned and solar, using EPSG:27700 and EPSG:4326.
storagegridatlas / compiler/202611132345-compile-atlas-v9.py · lines 1–250 of 250 · version 2026-11-13 23:45 · Entry point · pattern postcode (shared by 2 files)
- What it does
- It loads REPD publication q3, REPD q3 cleaned, solar and the REPD register. Defines 11 functions or classes, including digest, clean, norm, postcode, public_applicant. Uses libraries argparse, csv, hashlib, json, math. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): 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: solar, the REPD register.
- Inputs & outputs
- In: CSV file REPD_Publication_Q3_2026.csv; CSV file REPD_2026Q3_cleaned.csv; DuckDB queries; command-line arguments. Out: Parquet file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It classifies tech (`classify_tech`), compiles rows (`compile_rows`) and writes Parquet (`write_parquet`). Its name says it compiles atlas. Defines `digest`, `clean`, `norm` and 7 more. It accepts `--source`, `--v8` and `--output`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · compiler · Python CLI
- Uses
- argparse, csv, hashlib, json, math, re, unicodedata, collections
- Used by
- none found
- Produces
- digest, clean, norm, postcode, public_applicant, classify_tech, row_hash, compile_rows, write_parquet, v8_parity, main
- Defines here
- digest, clean, norm, postcode, public_applicant, classify_tech, row_hash, compile_rows, write_parquet, v8_parity, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 compiler/202611132345-compile-atlas-v9.py:1-250 · blob a4d19e14522ccede48dd8210cc0ada6955f91b73 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
import argparse
import csv
import hashlib
import json
import math
import re
import unicodedata
from collections import Counter
from pathlib import Path
import duckdb
from pyproj import Transformer
GENERATION = "202611132345"
# PREVIEW: the input is the cleaned, de-duplicated October file, not the raw official CSV,
# which repeats ref 7679 and would abort at the duplicate-ref check below.
SOURCE_URL = "https://assets.publishing.service.gov.uk/media/6af42ff0a4004bdbe54e54a5/REPD_Publication_Q3_2026.csv"
OFFICIAL_SHA256 = "48e76c49f33a1090e78108d1ea9bfe689b35963ea3be1bb4f6516d038a5ff862"
SOURCE_NAME = "REPD_2026Q3_cleaned.csv"
SOURCE_ENCODING = "utf-8-sig"
SOURCE_DATASET = "REPD Q3 2026 (October 2026 extract, cleaned)"
SOURCE_PUBLISHED = "UNVERIFIED"
SOURCE_SHA256 = "d937ae16ad07f43caaaa25b4cee56399e1e9b9bb2ae5ecb7bc88cf9bc092e4b9"
SOURCE_BYTES = 5201029
V8_SHA256 = "ca5da437ddb832f7e4e8d84bba1f2f6d40df6285089a43156452fdda7eebe0fe"
V8_BYTES = 4256963
V8_FEATURES = 10784
VIABLE = {"operational", "under construction", "awaiting construction", "consented", "planning permission granted", "planning approved", "application submitted", "pre-construction"}
REQUIRED = ["Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name", "Technology Type", "Installed Capacity (MWelec)", "Development Status (short)", "Address", "County", "Region", "Country", "Post Code", "X-coordinate", "Y-coordinate", "Planning Authority", "Planning Application Reference"]
POSTCODE = re.compile(r"^(?:GIR 0AA|[A-Z][A-HJ-Y]?[0-9][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2})$")
ORG_WORDS = re.compile(r"\b(?:ltd|limited|plc|llp|company|co|group|holdings|energy|power|solar|wind|renewable|development|developer|farm|estate|university|college|council|authority|government|trust|society|association|partnership|services|systems|airport|water|waste|environment|utility|utilities|generation|investments?|infrastructure|industries|international|uk)\b", re.I)
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def clean(value):
if value is None:
return None
value = re.sub(r"\s+", " ", str(value)).strip()
return None if not value or value.lower() in {"nan", "not set", "n/a"} else value
def norm(value):
value = unicodedata.normalize("NFKD", clean(value) or "")
return re.sub(r"[^a-z0-9]+", " ", value.encode("ascii", "ignore").decode().lower()).strip()
def postcode(raw):
raw_clean = (clean(raw) or "").upper()
compact = re.sub(r"\s+", "", raw_clean)
canonical = f"{compact[:-3]} {compact[-3:]}" if len(compact) >= 5 else raw_clean
return raw_clean or None, canonical or None, bool(POSTCODE.fullmatch(canonical))
def public_applicant(raw):
value = clean(raw)
if not value:
return None, "NOT_SUPPLIED"
if re.search(r"(?:@|\b\+?\d[\d ()-]{7,}\b)", value):
return None, "WITHHELD_CONTACT_DETAIL"
words = re.findall(r"[A-Za-z][A-Za-z'’-]*", value)
possible_person = 2 <= len(words) <= 4 and all(w[:1].isupper() for w in words) and not ORG_WORDS.search(value)
if possible_person:
return "WITHHELD — POSSIBLE INDIVIDUAL", "WITHHELD_POSSIBLE_INDIVIDUAL"
return value, "REPD_AS_PUBLISHED"
def classify_tech(raw, mounting):
text = (clean(raw) or "").lower()
mounting_text = (clean(mounting) or "").lower()
if "solar photovoltaic" in text or "solar pv" in text:
return "solar_roof" if mounting_text == "roof" else "solar"
if "wind onshore" in text: return "wind_onshore"
if "wind offshore" in text: return "wind_offshore"
if text == "hydrogen" or "fuel cell (hydrogen)" in text: return "hydrogen"
if any(x in text for x in ("large hydro", "small hydro", "pumped storage hydro")): return "hydro"
if any(x in text for x in ("compressed air energy storage", "liquid air energy storage")): return "caes"
if text in {"battery", "battery storage"} or "battery" in text: return "bess"
if any(x in text for x in ("biomass", "efw incineration", "anaerobic digestion", "landfill gas", "sewage sludge", "co-firing", "energy from waste", "incineration")): return "biomass"
if any(x in text for x in ("advanced conversion", "gasification", "pyrolysis")): return "act"
if "geothermal" in text or "hot dry rocks" in text: return "geothermal"
if "tidal" in text or "shoreline wave" in text: return "tidal"
if "flywheel" in text: return "flywheel"
if "storage" in text: return "bess"
if "wind" in text: return "wind"
return "other"
def row_hash(row):
payload = {key: clean(row.get(key)) for key in REQUIRED}
return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def compile_rows(source):
transformer = Transformer.from_crs("EPSG:27700", "EPSG:4326", always_xy=True)
output = []
seen = set()
with open(source, "r", encoding=SOURCE_ENCODING, newline="") as handle:
reader = csv.DictReader(handle)
missing = [name for name in REQUIRED if name not in (reader.fieldnames or [])]
if missing:
raise RuntimeError(f"missing REPD columns: {missing}")
for source_row, row in enumerate(reader, 2):
status = (clean(row.get("Development Status (short)")) or "").lower()
if status not in VIABLE:
continue
ref = clean(row.get("Ref ID"))
if not ref or ref in seen:
raise RuntimeError(f"missing or duplicate REPD Ref at source row {source_row}: {ref}")
try:
x = float(row.get("X-coordinate") or 0)
y = float(row.get("Y-coordinate") or 0)
lon, lat = transformer.transform(x, y)
except Exception:
continue
if not (math.isfinite(lon) and math.isfinite(lat) and -9 < lon < 2.5 and 49 < lat < 61):
continue
try:
capacity = float(row.get("Installed Capacity (MWelec)") or 0)
capacity = capacity if math.isfinite(capacity) else 0.0
except ValueError:
capacity = 0.0
technology = classify_tech(row.get("Technology Type"), row.get("Mounting Type for Solar"))
if technology == "solar_roof" and capacity > 50: capacity = round(capacity / 1000, 4)
if technology == "biomass" and capacity > 100: capacity = round(capacity / 1000, 4)
postcode_raw, postcode_canonical, postcode_valid = postcode(row.get("Post Code"))
applicant, applicant_state = public_applicant(row.get("Operator (or Applicant)"))
record = {
"repd_ref": ref,
"name": clean(row.get("Site Name")) or "Unknown",
"repd_address_raw": clean(row.get("Address")),
"repd_address_display": clean(row.get("Address")),
"repd_postcode_raw": postcode_raw,
"repd_postcode": postcode_canonical,
"postcode_valid": postcode_valid,
"county": clean(row.get("County")),
"region": clean(row.get("Region")),
"country": clean(row.get("Country")),
"planning_authority": clean(row.get("Planning Authority")),
"planning_application_reference": clean(row.get("Planning Application Reference")),
"repd_operator_or_applicant": applicant,
"applicant_publication_state": applicant_state,
"technology": technology,
"repd_technology": clean(row.get("Technology Type")),
"status": status,
"capacity_mw": capacity,
"longitude": round(lon, 6),
"latitude": round(lat, 6),
"source_record_updated": clean(row.get("Record Last Updated (dd/mm/yyyy)")),
"source_row": source_row,
"source_row_sha256": row_hash(row)
}
output.append(record)
seen.add(ref)
output.sort(key=lambda item: (int(item["repd_ref"]) if item["repd_ref"].isdigit() else 10**12, item["repd_ref"]))
return output
SCHEMA = """CREATE TABLE projects(
repd_ref VARCHAR NOT NULL, name VARCHAR NOT NULL, repd_address_raw VARCHAR, repd_address_display VARCHAR,
repd_postcode_raw VARCHAR, repd_postcode VARCHAR, postcode_valid BOOLEAN NOT NULL, county VARCHAR, region VARCHAR,
country VARCHAR, planning_authority VARCHAR, planning_application_reference VARCHAR, repd_operator_or_applicant VARCHAR,
applicant_publication_state VARCHAR NOT NULL, technology VARCHAR NOT NULL, repd_technology VARCHAR, status VARCHAR NOT NULL,
capacity_mw DOUBLE NOT NULL, longitude DOUBLE NOT NULL, latitude DOUBLE NOT NULL, source_record_updated VARCHAR,
source_row INTEGER NOT NULL, source_row_sha256 VARCHAR NOT NULL
)"""
def write_parquet(rows, target):
con = duckdb.connect()
con.execute("PRAGMA threads=1")
con.execute("SET preserve_insertion_order=true")
con.execute(SCHEMA)
columns = list(rows[0].keys())
con.executemany(f"INSERT INTO projects VALUES ({','.join(['?'] * len(columns))})", [tuple(row[c] for c in columns) for row in rows])
escaped = str(target).replace("'", "''")
con.execute(f"COPY (SELECT * FROM projects ORDER BY TRY_CAST(repd_ref AS BIGINT), repd_ref) TO '{escaped}' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 100000)")
readback = con.execute(f"SELECT count(*), count(DISTINCT repd_ref), min(latitude), max(latitude), min(longitude), max(longitude) FROM read_parquet('{escaped}')").fetchone()
schema = con.execute(f"DESCRIBE SELECT * FROM read_parquet('{escaped}')").fetchall()
con.close()
if readback[0] != len(rows) or readback[1] != len(rows):
raise RuntimeError(f"typed readback closure failed: {readback}")
return readback, [{"name": item[0], "type": item[1], "nullable": item[2]} for item in schema]
def v8_parity(rows, v8_path):
v8 = json.loads(Path(v8_path).read_text(encoding="utf-8"))
features = v8.get("features", [])
if len(features) != V8_FEATURES:
raise RuntimeError(f"V8 feature count drift: {len(features)}")
v9_keys = {(norm(r["name"]), round(r["longitude"], 4), round(r["latitude"], 4)) for r in rows}
matches = 0
for feature in features:
p = feature.get("properties") or {}
coords = (feature.get("geometry") or {}).get("coordinates") or []
if len(coords) >= 2 and (norm(p.get("name")), round(float(coords[0]), 4), round(float(coords[1]), 4)) in v9_keys:
matches += 1
ratio = matches / len(features)
if ratio < 0.95:
raise RuntimeError(f"V8 parity below 95%: {matches}/{len(features)}")
return {"oracle_features": len(features), "matched_by_name_and_rounded_coordinate": matches, "match_ratio": round(ratio, 6)}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--source", required=True)
parser.add_argument("--v8", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
source, v8_path, out = Path(args.source), Path(args.v8), Path(args.output)
if source.stat().st_size != SOURCE_BYTES or digest(source) != SOURCE_SHA256:
raise RuntimeError("official REPD input identity mismatch")
if v8_path.stat().st_size != V8_BYTES or digest(v8_path) != V8_SHA256:
raise RuntimeError("V8 oracle identity mismatch")
out.mkdir(parents=True, exist_ok=True)
rows = compile_rows(source)
if not 10000 <= len(rows) <= 12000:
raise RuntimeError(f"unexpected viable project count: {len(rows)}")
cases = {row["repd_ref"]: row for row in rows}
case = cases.get("16135")
required_case = {"repd_postcode": "MK43 0ZY", "county": "Bedfordshire", "status": "awaiting construction", "repd_operator_or_applicant": "Prologis UK Limited"}
if not case or any(case.get(k) != v for k, v in required_case.items()):
raise RuntimeError(f"golden Marston Gate case failed: {case}")
parquet = out / f"repd_projects_{GENERATION}.parquet"
readback, schema = write_parquet(rows, parquet)
registry = {
"schema": "gridatlas.browser-registry.v1",
"generation": GENERATION,
"source": {"publisher": "DESNZ", "dataset": SOURCE_DATASET, "published": SOURCE_PUBLISHED, "sha256": SOURCE_SHA256},
"relationship_label": "REPD operator or applicant (as published)",
"records": rows
}
registry_path = out / f"repd_browser_registry_{GENERATION}.json"
registry_path.write_text(json.dumps(registry, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8")
parity = v8_parity(rows, v8_path)
status_counts = Counter(row["status"] for row in rows)
manifest = {
"schema": "gridatlas.build-manifest.v1",
"generation": GENERATION,
"classification": "PREVIEW_CANDIDATE",
"source": {"url": SOURCE_URL, "official_sha256": OFFICIAL_SHA256, "file": SOURCE_NAME, "encoding": SOURCE_ENCODING, "bytes": SOURCE_BYTES, "sha256": SOURCE_SHA256, "published": SOURCE_PUBLISHED},
"v8_oracle": {"commit": "f2f343a92ee972cc74ed23b4b99d8a22896791ad", "bytes": V8_BYTES, "sha256": V8_SHA256, **parity},
"runtime": {"duckdb": duckdb.__version__, "parquet_compression": "ZSTD", "threads": 1},
"closure": {"rows": len(rows), "unique_repd_refs": len({r['repd_ref'] for r in rows}), "addresses": sum(bool(r['repd_address_display']) for r in rows), "postcodes": sum(bool(r['repd_postcode_raw']) for r in rows), "valid_postcodes": sum(r['postcode_valid'] for r in rows), "status_counts": dict(sorted(status_counts.items()))},
"parquet": {"path": parquet.name, "bytes": parquet.stat().st_size, "sha256": digest(parquet), "typed_readback": list(readback), "schema": schema},
"browser_registry": {"path": registry_path.name, "bytes": registry_path.stat().st_size, "sha256": digest(registry_path)},
"golden_case": {"query": "solar being built cranfield/marston bedfordshire", "repd_ref": "16135", "name": case["name"], **required_case},
"privacy": {"possible_individual_applicants_withheld": sum(r['applicant_publication_state'] == 'WITHHELD_POSSIBLE_INDIVIDUAL' for r in rows)},
"v8_untouched": True
}
(out / f"repd_v9_manifest_{GENERATION}.json").write_text(json.dumps(manifest, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")
print(json.dumps(manifest["closure"], sort_keys=True))
if __name__ == "__main__":
main()GridAtlas — Index Page
A web page. Published at https://gridatlas.globalgrid2050.com/.
rendergridatlas / index.html · lines 1–2 of 2 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- Out: web page.
- Downstream impact
- Used directly by 32 files: Build N1 Deep Link Candidates (code-generator); Single-Line Diagram (SLD) Mobile Arrival Card Browser (gridatlas); GlobalGrid2050 — Atlas V9 Page (globalgrid2050, https://globalgrid2050.com/202608300453-atlas-v9/); Prove Federated Deep Links (gridatlas); and 28 more. Reached from 27 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html); GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). It is itself an entry point, published at https://gridatlas.globalgrid2050.com/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the Atlas V9 page in GlobalGrid2050 at https://globalgrid2050.com/202608300453-atlas-v9/. Also imported by 30 files, including Build N1 Deep Link Candidates, Single-Line Diagram (SLD) Mobile Arrival Card Browser and Prove Federated Deep Links, from Claude, Code Generator, Cosmic and others. Checked by Overlay Offtakers Test.
- Application
- gridatlas · / · page
- Uses
- GridAtlas — Atlas Page (link)
- Used by
- named by URL in Build N1 Deep Link Candidates (estate URL), named by URL in Single-Line Diagram (SLD) Mobile Arrival Card Browser (estate URL), linked from GlobalGrid2050 — Atlas V9 Page (link), named by URL in Prove Federated Deep Links (estate URL), named by URL in Overlay Offtakers Test (estate URL), named by URL in Map Receiver Restoration Browser (estate URL), named by URL in Offtakers Cartridge (estate URL), named by URL in Flow Lib (estate URL), and 24 more, mentioned in Publish Iteration (comment link)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 index.html:1-2 · blob 845cbfe718c0827b63bd6c8eddf30c7bbb2a8529 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="gridatlas-current-route" content="atlas"><title>Grid Atlas</title><script>(()=>{const target='./atlas/';window.location.replace(target+window.location.search+window.location.hash);})();</script></head><body data-gridatlas-current-route="atlas"><main><h1>Grid Atlas</h1><p><a hr … [line shortened here: 453 characters; full line on GitHub]