In this section
- Real V975 Test test · globalgrid2050 / automation/repd_reporting/v3/real_v975.test.mjs lines 1–37
- Verify V975 other · globalgrid2050 / automation/repd_reporting/v3/verify_v975.py lines 1–38
- Renewable Energy Planning Database (REPD) Sources V6 energy-data · globalgrid2050 / backups/repd/2026-11-13-pre-october-ingestion/repd_sources_v6.py lines 1–429
- Renewable Energy Planning Database (REPD) Updater V6 Hardened energy-data · globalgrid2050 / backups/repd/2026-11-13-pre-october-ingestion/repd_updater_v6_hardened.py lines 1–11
- Energy render · globalgrid2050 / cartridges/202609052143-open-energy/energy.css lines 1–12
- Energy interaction · globalgrid2050 / cartridges/202609052143-open-energy/energy.mjs lines 1–22
- Model transform · globalgrid2050 / cartridges/202609052143-open-energy/model.mjs lines 1–17
- Model Test test · globalgrid2050 / cartridges/202609052143-open-energy/model.test.mjs lines 1–10
Real V975 Test
A test in the REPD reporting folder of GlobalGrid2050 that checks Renewable Energy Planning Database (REPD) Reports Model and Operator Aliases.
testglobalgrid2050 / automation/repd_reporting/v3/real_v975.test.mjs · lines 1–37 of 37 · Entry point
- What it does
- It tests the REPD register. Defines read, close. Uses libraries node:test, node:assert/strict, node:fs. Side effects: 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: the REPD register.
- Inputs & outputs
- In: JSON file build_manifest.json.
- Downstream impact
- Used directly by 2 files: GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow (globalgrid2050).
- What it achieves
- Defines `read` and `close`. It reads `data/v9.1/build_manifest.json`.
- Why it matters
- Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow and GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow.
- Application
- globalgrid2050 · automation/repd_reporting/v3 · test
- Uses
- Renewable Energy Planning Database (REPD) Reports Model (import), Operator Aliases (import), node:test, node:assert/strict, node:fs
- Used by
- run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow (workflow run), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow (workflow run)
- Produces
- read, close
- Defines here
- read, close
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_reporting/v3/real_v975.test.mjs:1-37 · blob 999489cad8de27f3a5a1d0d86e9e89e63172cc8f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from "node:test";
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {buildRepdCapacityReport} from "../../../uk_renewables_pipeline/202611231600/repd-reports-model.mjs";
import {canonicalOperator} from "./operator-aliases.mjs";
const root="uk_renewables_pipeline/202611231600/";
const read=p=>JSON.parse(readFileSync(root+p,"utf8"));
const close=(a,b)=>assert.ok(Math.abs(a-b)<0.011,a+" != "+b);
test("V9.75 exact 7,775 REPD refs, three group dimensions and audited operator aliases",()=>{
const manifest=read("data/v9.1/build_manifest.json");
const rows=manifest.project_partitions.flatMap(x=>read(x.path).projects);
assert.equal(rows.length,7775);
const reports=["operator","status","region"].map(d=>buildRepdCapacityReport(rows,d));
for(const report of reports){
assert.equal(report.total.count,rows.length);
assert.equal(report.uniqueRefs,rows.length);
close(report.total.recordedCapacity,manifest.capacity_mw);
close(report.groups.reduce((s,g)=>s+g.count,0),rows.length);
close(report.groups.reduce((s,g)=>s+g.recordedCapacity,0),report.total.recordedCapacity);
close(report.total.solarMwp+report.total.otherMw,report.total.recordedCapacity);
}
const [operators,statuses,regions]=reports;
assert.deepEqual(new Set(statuses.groups.map(x=>x.name)),
new Set(rows.map(p=>p.status?.trim()||"Not reported")));
assert.deepEqual(new Set(regions.groups.map(x=>x.name)),
new Set(rows.map(p=>p.region?.trim()||"Not reported")));
const exact=new Set(rows.map(p=>p.operator?.trim()||"Not reported"));
const mapped=new Set(rows.map(p=>canonicalOperator(p.operator)));
assert.deepEqual(new Set(operators.groups.map(x=>x.name)),mapped);
assert.ok(operators.groups.length<=exact.size);
assert.ok(exact.has("Low Carbon Limited"),"Source operator preserved");
assert.ok(!mapped.has("Low Carbon Limited"),"Reporting alias applied");
assert.ok(mapped.has("Low Carbon"));
assert.ok(operators.groups.find(g=>g.name==="Low Carbon").projects.some(p=>p.operator==="Low Carbon Limited"));
assert.ok(rows.some(p=>p.operator==="Low Carbon Limited"),"Source REPD rows never rewritten");
console.log("PASS 7775 true REPD refs, 3 report dimensions, exact legal source intact, operator spelling aliases report-only; original",exact.size,"grouped",mapped.size);
});Verify V975
A Python module in the REPD reporting folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register, using SHA-256.
otherglobalgrid2050 / automation/repd_reporting/v3/verify_v975.py · lines 1–38 of 38 · Entry point
- What it does
- Uses libraries pathlib, hashlib. Side effects: 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: the REPD register.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow (globalgrid2050).
- What it achieves
- Read-only Python source-closure and nontruncation gate for V9.75.
- Why it matters
- Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow.
- Application
- globalgrid2050 · automation/repd_reporting/v3 · Python module
- Uses
- pathlib, hashlib
- Used by
- run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Native V975 Workflow (workflow run)
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_reporting/v3/verify_v975.py:1-38 · blob 6e20b7b36dcb61ad01e46703cee12ea434a80ec9 · 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
#!/usr/bin/env python3
"""Read-only Python source-closure and nontruncation gate for V9.75."""
from pathlib import Path
import hashlib
ROOT=Path(__file__).resolve().parents[3]
old=ROOT/"uk_renewables_pipeline/202611231400"
new=ROOT/"uk_renewables_pipeline/202611231600"
a={str(p.relative_to(old)):p.read_bytes() for p in old.rglob("*") if p.is_file()}
b={str(p.relative_to(new)):p.read_bytes() for p in new.rglob("*") if p.is_file()}
assert len(a)>300, ("Suspicious historical source size",len(a))
assert set(a).issubset(b), ("TRUNCATION",sorted(set(a)-set(b)))
assert set(b)-set(a)=={"tests/v975-native-browser.mjs"}, ("Unexpected additions",set(b)-set(a))
changes={name for name in a if a[name]!=b[name]}
expected={"index.html","repd-reports.mjs","repd-reports-model.mjs","repd-scan.mjs",
"scripts/plugins/projects-v9-8.js","README.md","CHANGES.md"}
assert changes==expected, ("Unexpected changed source",changes^expected)
for name in a:
if name.startswith(("data/","styles/","news/")) or name in (
"map-entry.mjs","report-a4.mjs","report-pdf.mjs","repd-expanded.mjs",
"scripts/data/canonical-projects-v9-5-1.js","scripts/plugins/gauges-v9-2.js"):
assert a[name]==b[name], "Protected source changed: "+name
html=b["index.html"].decode()
report=b["repd-reports.mjs"].decode()
project=b["scripts/plugins/projects-v9-8.js"].decode()
assert len(html)>20000 and len(project)>25000 and len(report)>5000, "Truncated functional source"
for id in ["repdNativeStatus","repdNativeOperator","repdNativeRegion","repdReportsPanel",
"g1","g2","g3","repdScroll","pnScanStatus"]:
assert ('id="'+id+'"') in html, "Missing native control "+id
assert html.count('id="status"')==1
assert not any(x in html for x in ("COCKPIT","Cockpit","repdReportScope"))
assert "makeFacet(" not in report and "reportScope" not in report
assert "state.filtered" in report and "updateGaugesV9_2(filtered)" in project
assert "canonicalOperator(project.operator)" in project
assert "repdNativeStatus" in project and "repdNativeOperator" in project
for name in ["report-a4.mjs","report-pdf.mjs","map-entry.mjs"]:
assert hashlib.sha256(a[name]).digest()==hashlib.sha256(b[name]).digest()
print("PASS V9.75 Python source closure",len(a),"preserved,",
len(changes),"reviewed changes, 1 browser test, 0 removed, 0 CSS/data/MAP/A4/PDF changes")Renewable Energy Planning Database (REPD) Sources V6
A Python command-line tool in the backups folder of GlobalGrid2050 that fetches REPD canonical, REPD reconciliation, REPD publication q2 and the REPD register, using SHA-256.
energy-dataglobalgrid2050 / backups/repd/2026-11-13-pre-october-ingestion/repd_sources_v6.py · lines 1–429 of 429 · Entry point · pattern planning_refs_equivalent (shared by 2 files)
- What it does
- It fetches REPD canonical, REPD reconciliation, REPD publication q2 and the REPD register. Defines 20 functions or classes, including utc_now, sha256, collapse, norm_text, norm_date. Uses libraries __future__, hashlib, io, json, math. Side effects: reads or writes files; makes network requests.
- 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: the REPD register.
- Inputs & outputs
- In: CSV file latest_repd_v6_canonical.csv; JSON file repd_source_reconciliation_v6.json; JSON file manifest_v6.json; CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx. Out: CSV file.
- Downstream impact
- Used directly by 1 file: Renewable Energy Planning Database (REPD) Updater V6 Hardened (globalgrid2050).
- What it achieves
- It cleans ref (`clean_ref`), fetches bytes (`fetch_bytes`) and reads CSV (`read_csv`). Official DESNZ Q2 2026 source retrieval and deterministic reconciliation. Its code works with 1 MW, 100 MW and 0.005 MW.
- Why it matters
- Imported by Renewable Energy Planning Database (REPD) Updater V6 Hardened.
- Application
- globalgrid2050 · backups/repd/2026-11-13-pre-october-ingestion · Python CLI
- Uses
- __future__, hashlib, io, json, math, re, time, datetime
- Used by
- imported by Renewable Energy Planning Database (REPD) Updater V6 Hardened (import)
- Produces
- utc_now, sha256, collapse, norm_text, norm_date, norm_number, clean_ref, canonicalise_headers, fetch_bytes, read_csv, read_xlsx, indexed
- Defines here
- utc_now, sha256, collapse, norm_text, norm_date, norm_number, clean_ref, canonicalise_headers, fetch_bytes, read_csv, read_xlsx, indexed, threshold_counts, planning_refs_equivalent, build_canonical, reconcile, check, run_reconciliation, write_outputs, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 backups/repd/2026-11-13-pre-october-ingestion/repd_sources_v6.py:1-429 · blob d6bd42f46a410e6bd2e8d208a2450f5ec1e4c6c3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Official DESNZ Q2 2026 source retrieval and deterministic reconciliation.
The published CSV is a two-decimal representation of several capacity values,
whereas the XLSX retains the underlying precision. V6 therefore uses the XLSX
capacity as the canonical official value only after both publications pass the
same row/Ref-ID gates and every difference is format-equivalent.
"""
from __future__ import annotations
import hashlib
import io
import json
import math
import re
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
DIST = ROOT / "dist"
CANONICAL_CSV = DATA / "latest_repd_v6_canonical.csv"
REPORT = DIST / "repd_source_reconciliation_v6.json"
MANIFEST = DIST / "manifest_v6.json"
SOURCE_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
CSV_URL = "https://assets.publishing.service.gov.uk/media/6a6cbdc00c36759b5ccaa305/REPD_Publication_Q2_2026.csv"
XLSX_URL = "https://assets.publishing.service.gov.uk/media/6a6cbdd2862aaf18d9c62b02/REPD_Publication_Q2_2026.xlsx"
PUBLICATION_DATE = "2026-08-03"
DATASET_TITLE = "Renewable Energy Planning Database (REPD): July 2026 (Q2 2026)"
EXPECTED_ROWS = 14657
EXPECTED_SOLAR_GT1 = 3445
EXPECTED_BESS_GT100 = 269
EXPECTED_CSV_SHA256 = "84c1b5f958a934d8b4b86ec88f50bdcf43830ded7ff2efc27bffca0c98695035"
EXPECTED_XLSX_SHA256 = "624a0a9712c58a7a93716e51f2bf054eec8b1af7170f6f9516cc10cd248e2657"
CAPACITY_ROUNDING_TOLERANCE_MW = 0.0050001
CORE_TEXT_FIELDS = [
"Site Name",
"Technology Type",
"Development Status (short)",
"Record Last Updated (dd/mm/yyyy)",
"Operator (or Applicant)",
"Planning Application Reference",
"Planning Authority",
]
OFFICIAL_DATE_FIELDS = [
"Planning Application Submitted",
"Planning Application Withdrawn",
"Planning Permission Refused",
"Planning Permission Granted",
"Planning Permission Expired",
"Under Construction",
"Operational",
]
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def sha256(raw: bytes) -> str:
return hashlib.sha256(raw).hexdigest()
def collapse(value) -> str:
if value is None or (not isinstance(value, str) and pd.isna(value)):
return ""
text = str(value).replace("_x000D_", " ").replace("\r", " ").replace("\n", " ")
return re.sub(r"\s+", " ", text).strip()
def norm_text(value) -> str:
return collapse(value).casefold()
def norm_date(value) -> str:
if value is None or (not isinstance(value, str) and pd.isna(value)) or not str(value).strip():
return ""
if isinstance(value, (datetime, pd.Timestamp)):
return value.strftime("%Y-%m-%d")
text = collapse(value)
for pattern in ("%d/%m/%Y", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"):
try:
return datetime.strptime(text, pattern).strftime("%Y-%m-%d")
except ValueError:
continue
return ""
def norm_number(value):
if value is None or (not isinstance(value, str) and pd.isna(value)) or not str(value).strip():
return None
try:
number = float(str(value).replace(",", ""))
return number if math.isfinite(number) else None
except Exception:
return None
def clean_ref(value) -> str:
text = collapse(value)
if re.fullmatch(r"\d+\.0", text):
text = text[:-2]
return text
def canonicalise_headers(frame: pd.DataFrame) -> pd.DataFrame:
recognised = CORE_TEXT_FIELDS + OFFICIAL_DATE_FIELDS + [
"Ref ID",
"Old Ref ID",
"Installed Capacity (MWelec)",
"County",
"Region",
"Country",
"Storage Co-location REPD Ref ID",
"Are they re-applying (New REPD Ref)",
"Are they re-applying (Old REPD Ref)",
"Planning Permission Granted",
]
aliases = {name.casefold(): name for name in recognised}
aliases.update({
"record last updated": "Record Last Updated (dd/mm/yyyy)",
"record last updated (dd/mm/yyyy)": "Record Last Updated (dd/mm/yyyy)",
"planning permission granted": "Planning Permission Granted",
})
renamed = {}
seen = {}
for source in frame.columns:
collapsed = re.sub(r"\s+", " ", str(source).strip())
target = aliases.get(collapsed.casefold(), collapsed)
if target in seen:
raise RuntimeError(f"Header canonicalisation collision: {seen[target]!r} and {source!r} -> {target!r}")
seen[target] = source
renamed[source] = target
return frame.rename(columns=renamed)
def fetch_bytes(url: str) -> bytes:
last_error = None
for attempt in range(3):
request = Request(url, headers={"User-Agent": "GlobalGrid2050/6.0 (+https://globalgrid2050.com/)"})
try:
with urlopen(request, timeout=75) as response:
payload = response.read()
if not payload:
raise RuntimeError("empty response")
return payload
except Exception as exc:
last_error = exc
if attempt < 2:
time.sleep(2 ** attempt)
raise RuntimeError(f"Unable to retrieve official source after three attempts: {url}: {last_error}")
def read_csv(raw: bytes) -> pd.DataFrame:
last_error = None
for encoding in ("utf-8-sig", "cp1252"):
try:
frame = pd.read_csv(
io.BytesIO(raw),
encoding=encoding,
dtype=str,
keep_default_na=False,
on_bad_lines="error",
engine="python",
)
return canonicalise_headers(frame)
except UnicodeDecodeError as exc:
last_error = exc
raise RuntimeError(f"Unable to decode official REPD CSV: {last_error}")
def read_xlsx(raw: bytes) -> tuple[pd.DataFrame, str]:
book = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
required = {"Ref ID", "Site Name", "Technology Type", "Installed Capacity (MWelec)"}
for sheet in book.sheet_names:
frame = canonicalise_headers(pd.read_excel(book, sheet_name=sheet, engine="openpyxl"))
if required.issubset(frame.columns):
return frame, sheet
raise RuntimeError(f"No REPD data sheet found in official XLSX; sheets={book.sheet_names}")
def indexed(frame: pd.DataFrame, label: str) -> pd.DataFrame:
if "Ref ID" not in frame.columns:
raise RuntimeError(f"{label} missing Ref ID")
refs = [clean_ref(value) for value in frame["Ref ID"].tolist()]
missing = sum(not value for value in refs)
duplicates = len(refs) - len(set(refs))
if missing or duplicates:
raise RuntimeError(f"{label} invalid Ref IDs: missing={missing} duplicates={duplicates}")
out = frame.copy()
out["__repd_ref"] = refs
return out.set_index("__repd_ref", drop=False)
def threshold_counts(frame: pd.DataFrame) -> tuple[int, int]:
solar = 0
bess = 0
for _, row in frame.iterrows():
capacity = norm_number(row.get("Installed Capacity (MWelec)"))
if capacity is None:
continue
technology = norm_text(row.get("Technology Type"))
if "solar photovoltaic" in technology and capacity > 1.0:
solar += 1
if "battery" in technology and capacity > 100.0:
bess += 1
return solar, bess
def planning_refs_equivalent(csv_value, xlsx_value) -> bool:
left, right = norm_text(csv_value), norm_text(xlsx_value)
missing = {"", "n/a", "na", "none", "not known", "unknown", "not supplied"}
if left in missing and right in missing:
return True
if left == right:
return True
# Excel may coerce a digits-only planning reference and remove a leading zero.
return left.isdigit() and right.isdigit() and int(left) == int(right)
def build_canonical(csv_frame: pd.DataFrame, xlsx_frame: pd.DataFrame) -> pd.DataFrame:
csv_ix = indexed(csv_frame, "CSV")
xlsx_ix = indexed(xlsx_frame, "XLSX")
canonical = csv_ix.copy()
# Sanitise control-code representation without inventing a replacement value.
for column in canonical.columns:
if column != "__repd_ref":
canonical[column] = canonical[column].map(collapse)
# The workbook is the precision-preserving official representation of capacity.
capacities = []
for ref in canonical.index:
value = norm_number(xlsx_ix.at[ref, "Installed Capacity (MWelec)"])
capacities.append("" if value is None else format(value, ".15g"))
canonical["Installed Capacity (MWelec)"] = capacities
# Planning references are identifiers rather than numbers. Excel's typed import
# can expose a leading zero that the CSV serialisation omitted; keep that exact
# official workbook representation after integer-equivalence has been validated.
if "Planning Application Reference" in canonical.columns:
canonical["Planning Application Reference"] = [
collapse(xlsx_ix.at[ref, "Planning Application Reference"]) for ref in canonical.index
]
canonical["Ref ID"] = [clean_ref(value) for value in canonical["Ref ID"]]
return canonical.drop(columns=["__repd_ref"])
def reconcile(csv_raw: bytes, xlsx_raw: bytes) -> tuple[pd.DataFrame, dict, dict]:
csv_frame = read_csv(csv_raw)
xlsx_frame, xlsx_sheet = read_xlsx(xlsx_raw)
csv_ix = indexed(csv_frame, "CSV")
xlsx_ix = indexed(xlsx_frame, "XLSX")
errors = []
checks = []
def check(ok, gate, detail=""):
checks.append({"gate": gate, "pass": bool(ok), "detail": detail})
if not ok:
errors.append(f"{gate}: {detail}" if detail else gate)
csv_refs, xlsx_refs = set(csv_ix.index), set(xlsx_ix.index)
check(len(csv_ix) == EXPECTED_ROWS, "CSV row count exact", f"actual={len(csv_ix)} expected={EXPECTED_ROWS}")
check(len(xlsx_ix) == EXPECTED_ROWS, "XLSX row count exact", f"actual={len(xlsx_ix)} expected={EXPECTED_ROWS}")
check(len(csv_refs) == EXPECTED_ROWS, "CSV unique Ref ID count exact", f"actual={len(csv_refs)}")
check(len(xlsx_refs) == EXPECTED_ROWS, "XLSX unique Ref ID count exact", f"actual={len(xlsx_refs)}")
check(csv_refs == xlsx_refs, "CSV/XLSX Ref ID sets equal", f"csv_only={len(csv_refs-xlsx_refs)} xlsx_only={len(xlsx_refs-csv_refs)}")
check(sha256(csv_raw) == EXPECTED_CSV_SHA256, "Q2 CSV immutable SHA-256", sha256(csv_raw))
check(sha256(xlsx_raw) == EXPECTED_XLSX_SHA256, "Q2 XLSX immutable SHA-256", sha256(xlsx_raw))
material = []
representation = {
"capacity_precision": 0,
"control_code_whitespace": 0,
"planning_reference_leading_zero": 0,
"planning_reference_missing_marker": 0,
}
representation_examples = {
"capacity_precision": [],
"control_code_whitespace": [],
"planning_reference_leading_zero": [],
"planning_reference_missing_marker": [],
}
for ref in sorted(csv_refs & xlsx_refs, key=lambda value: (int(value) if value.isdigit() else 10**18, value)):
left, right = csv_ix.loc[ref], xlsx_ix.loc[ref]
for field in CORE_TEXT_FIELDS + OFFICIAL_DATE_FIELDS:
if field not in csv_ix.columns or field not in xlsx_ix.columns:
material.append({"repd_ref": ref, "field": field, "reason": "missing field in one publication"})
continue
if field == "Record Last Updated (dd/mm/yyyy)" or field in OFFICIAL_DATE_FIELDS:
equivalent = norm_date(left.get(field)) == norm_date(right.get(field))
elif field == "Planning Application Reference":
equivalent = planning_refs_equivalent(left.get(field), right.get(field))
if equivalent and norm_text(left.get(field)) != norm_text(right.get(field)):
missing = {"", "n/a", "na", "none", "not known", "unknown", "not supplied"}
key = (
"planning_reference_missing_marker"
if norm_text(left.get(field)) in missing and norm_text(right.get(field)) in missing
else "planning_reference_leading_zero"
)
representation[key] += 1
if len(representation_examples[key]) < 10:
representation_examples[key].append(
{"repd_ref": ref, "csv": collapse(left.get(field)), "xlsx": collapse(right.get(field))}
)
else:
equivalent = norm_text(left.get(field)) == norm_text(right.get(field))
raw_left = re.sub(r"\s+", " ", str(left.get(field) or "")).strip().casefold()
raw_right = re.sub(r"\s+", " ", str(right.get(field) or "")).strip().casefold()
if equivalent and raw_left != raw_right:
representation["control_code_whitespace"] += 1
if len(representation_examples["control_code_whitespace"]) < 10:
representation_examples["control_code_whitespace"].append(
{"repd_ref": ref, "field": field, "csv": collapse(left.get(field)), "xlsx": collapse(right.get(field))}
)
if not equivalent:
material.append({"repd_ref": ref, "field": field, "csv": collapse(left.get(field)), "xlsx": collapse(right.get(field))})
csv_capacity = norm_number(left.get("Installed Capacity (MWelec)"))
xlsx_capacity = norm_number(right.get("Installed Capacity (MWelec)"))
if csv_capacity is None or xlsx_capacity is None:
if csv_capacity != xlsx_capacity:
material.append({"repd_ref": ref, "field": "Installed Capacity (MWelec)", "csv": csv_capacity, "xlsx": xlsx_capacity})
elif abs(csv_capacity - xlsx_capacity) > CAPACITY_ROUNDING_TOLERANCE_MW:
material.append({"repd_ref": ref, "field": "Installed Capacity (MWelec)", "csv": csv_capacity, "xlsx": xlsx_capacity})
elif csv_capacity != xlsx_capacity:
representation["capacity_precision"] += 1
if len(representation_examples["capacity_precision"]) < 10:
representation_examples["capacity_precision"].append(
{"repd_ref": ref, "csv": csv_capacity, "xlsx": xlsx_capacity}
)
check(not material, "CSV/XLSX material fields reconcile", f"material_mismatches={len(material)}")
canonical = build_canonical(csv_frame, xlsx_frame) if not errors else pd.DataFrame()
csv_solar, csv_bess = threshold_counts(csv_frame)
xlsx_solar, xlsx_bess = threshold_counts(xlsx_frame)
canonical_solar, canonical_bess = threshold_counts(canonical) if not canonical.empty else (0, 0)
check(xlsx_solar == EXPECTED_SOLAR_GT1, "XLSX/canonical solar >1MW exact", f"actual={xlsx_solar} expected={EXPECTED_SOLAR_GT1}")
check(xlsx_bess == EXPECTED_BESS_GT100, "XLSX/canonical BESS >100MW exact", f"actual={xlsx_bess} expected={EXPECTED_BESS_GT100}")
check(canonical_solar == EXPECTED_SOLAR_GT1, "canonical solar >1MW exact", f"actual={canonical_solar}")
check(canonical_bess == EXPECTED_BESS_GT100, "canonical BESS >100MW exact", f"actual={canonical_bess}")
validated_at = utc_now()
metrics = {
"csv_rows": len(csv_ix),
"xlsx_rows": len(xlsx_ix),
"csv_unique_refs": len(csv_refs),
"xlsx_unique_refs": len(xlsx_refs),
"csv_native_solar_gt1_rounded": csv_solar,
"xlsx_canonical_solar_gt1": xlsx_solar,
"canonical_solar_gt1": canonical_solar,
"csv_bess_gt100": csv_bess,
"xlsx_bess_gt100": xlsx_bess,
"canonical_bess_gt100": canonical_bess,
"canonical_combined_projects": canonical_solar + canonical_bess,
"material_mismatches": len(material),
"representation_differences": representation,
}
report = {
"schema": "globalgrid2050.repd-source-reconciliation.v6",
"pass": not errors,
"validated_at": validated_at,
"csv_url": CSV_URL,
"xlsx_url": XLSX_URL,
"xlsx_sheet": xlsx_sheet,
"source_hashes": {"csv_sha256": sha256(csv_raw), "xlsx_sha256": sha256(xlsx_raw)},
"capacity_policy": "XLSX precision is canonical; CSV must be within 0.005 MW display-rounding tolerance",
"text_policy": "trim/collapse whitespace; treat XLSX _x000D_ as whitespace; use the XLSX representation of integer-equivalent planning references and report leading-zero differences",
"metrics": metrics,
"checks": checks,
"representation_difference_examples": representation_examples,
"material_mismatch_examples": material[:25],
"errors": errors,
}
manifest = {
"schema": "globalgrid2050.repd-manifest.v6",
"schema_version": 6,
"status": "VALIDATED" if not errors else "REJECTED",
"validated_at": validated_at,
"source_owner": "Department for Energy Security and Net Zero (DESNZ)",
"source_page": SOURCE_PAGE,
"source_page_last_updated": PUBLICATION_DATE,
"source_dataset_title": DATASET_TITLE,
"source_url": CSV_URL,
"source_excel_url": XLSX_URL,
"source_hashes": report["source_hashes"],
"source_record_count": EXPECTED_ROWS,
"source_unique_ref_count": EXPECTED_ROWS,
"canonical_capacity_source": "official XLSX precision, reconciled to official CSV by Ref ID",
"header_policy": "trim + collapse internal whitespace + case-insensitive aliases",
"missing_value_policy": "official blanks remain null; no value or date is invented",
"thresholds": {"solar_mw_exclusive": 1.0, "bess_mw_exclusive": 100.0},
"canonical_counts": {"solar": EXPECTED_SOLAR_GT1, "bess": EXPECTED_BESS_GT100, "combined": EXPECTED_SOLAR_GT1 + EXPECTED_BESS_GT100},
}
return canonical, report, manifest
def run_reconciliation() -> tuple[pd.DataFrame, dict, dict]:
csv_raw = fetch_bytes(CSV_URL)
xlsx_raw = fetch_bytes(XLSX_URL)
return reconcile(csv_raw, xlsx_raw)
def write_outputs(canonical: pd.DataFrame, report: dict, manifest: dict) -> None:
DIST.mkdir(parents=True, exist_ok=True)
DATA.mkdir(parents=True, exist_ok=True)
REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")
if not report.get("pass"):
raise RuntimeError("Official Q2 CSV/XLSX reconciliation failed; previous validated snapshot retained")
canonical.to_csv(CANONICAL_CSV, index=False, encoding="utf-8-sig")
MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def main() -> None:
canonical, report, manifest = run_reconciliation()
write_outputs(canonical, report, manifest)
print("REPD SOURCE RECONCILIATION PASS", json.dumps(report["metrics"], sort_keys=True))
if __name__ == "__main__":
main()Renewable Energy Planning Database (REPD) Updater V6 Hardened
A Python command-line tool in the backups folder of GlobalGrid2050 covering REPD master and the REPD register.
energy-dataglobalgrid2050 / backups/repd/2026-11-13-pre-october-ingestion/repd_updater_v6_hardened.py · lines 1–11 of 11 · Entry point
- 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: the REPD register.
- Inputs & outputs
- In: JSON file repd_master.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Compatibility entry point for isolated V6 source reconciliation.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · backups/repd/2026-11-13-pre-october-ingestion · Python CLI
- Uses
- Renewable Energy Planning Database (REPD) Sources V6 (import)
- Used by
- none found
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 backups/repd/2026-11-13-pre-october-ingestion/repd_updater_v6_hardened.py:1-11 · blob e011e8dc96f8e573f2f52c59c0ba94f8f0172f12 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Compatibility entry point for isolated V6 source reconciliation.
The former implementation rewrote the shared V1–V5 `repd_master.json`. V6 now
publishes only V6-specific outputs from a reconciled Q2 CSV/XLSX staging table.
"""
from repd_sources_v6 import main
if __name__ == "__main__":
main()Energy
A style sheet in the cartridges folder of GlobalGrid2050.
renderglobalgrid2050 / cartridges/202609052143-open-energy/energy.css · lines 1–12 of 12 · version 2026-09-05 21:43 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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.
- Downstream impact
- Used directly by 35 files: Homepage V059 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v059.html); Homepage V060 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v060.html); Homepage V061 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v061.html); Homepage V062 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v062.html); and 31 more.
- What it achieves
- Original terminal UI; no Worldometer code, fonts, images or feed.
- Why it matters
- Loaded by the Homepage V059 page at https://globalgrid2050.com/homepage_versions/homepage_v059.html and 34 other pages.
- Application
- globalgrid2050 · cartridges/202609052143-open-energy · style sheet
- Uses
- none found
- Used by
- loaded by Homepage V059 (stylesheet), loaded by Homepage V060 (stylesheet), loaded by Homepage V061 (stylesheet), loaded by Homepage V062 (stylesheet), loaded by Homepage V063 (stylesheet), loaded by Homepage V064 (stylesheet), loaded by Homepage V065 (stylesheet), loaded by Homepage V066 (stylesheet), and 27 more
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 cartridges/202609052143-open-energy/energy.css:1-12 · blob cb4c3d89ba3c53162e3083a008042c6f1932b59c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Original terminal UI; no Worldometer code, fonts, images or feed. */
#open-energy{border-block:1px solid #72777c;padding:18px 0;margin:24px 0;font:15px/1.5 Consolas,"Courier New",monospace;color:#d6d8da}
#open-energy h2{font:inherit;font-weight:bold;letter-spacing:1px;color:inherit}
#open-energy .energy-row{margin:18px 0}
#open-energy .energy-label{display:flex;justify-content:space-between;gap:6px 20px;flex-wrap:wrap}
#open-energy output{font-variant-numeric:tabular-nums;font-weight:bold}
#open-energy progress{display:block;appearance:none;-webkit-appearance:none;width:100%;height:18px;border:1px solid #7b8085;border-radius:0;background:#303438;color:#c4c9ce;margin:5px 0}
#open-energy progress::-webkit-progress-bar{background:#303438}#open-energy progress::-webkit-progress-value{background:#c4c9ce}#open-energy progress::-moz-progress-bar{background:#c4c9ce}
#open-energy small,#open-energy p,#open-energy details{font-size:12px}
#open-energy button{font:inherit;color:inherit;background:#25292d;border:1px solid #8b9095;border-radius:0;padding:4px 10px;cursor:pointer}
#open-energy :focus-visible{outline:2px solid #ddd;outline-offset:3px}
#open-energy a{color:inherit}#open-energy summary{cursor:pointer}Energy
A JavaScript module in the cartridges folder of GlobalGrid2050.
interactionglobalgrid2050 / cartridges/202609052143-open-energy/energy.mjs · lines 1–22 of 22 · version 2026-09-05 21:43 · Entry point · pattern frame (shared by 66 files)
- What it does
- It fetches data. Defines start, render, frame. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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
- In: JSON file source.json.
- Downstream impact
- Used directly by 3 files: GlobalGrid2050 Open Energy Cartridge Workflow (globalgrid2050); Homepage V059 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v059.html); Homepage V060 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v060.html).
- What it achieves
- Defines `start`, `render` and `frame`. It responds to click events.
- Why it matters
- Loaded by the Homepage V059 page at https://globalgrid2050.com/homepage_versions/homepage_v059.html and 1 other page. Run by GlobalGrid2050 Open Energy Cartridge Workflow.
- Application
- globalgrid2050 · cartridges/202609052143-open-energy · JavaScript module
- Uses
- Model (import)
- Used by
- run by GlobalGrid2050 Open Energy Cartridge Workflow (workflow run), loaded by Homepage V059 (script src), loaded by Homepage V060 (script src)
- Produces
- start, render, frame
- Defines here
- start, render, frame
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 cartridges/202609052143-open-energy/energy.mjs:1-22 · blob 40ce4b6885c6006ce44d6be340b74ce3275ab328 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {calculate,validate} from './model.mjs';
const root=document.getElementById('open-energy');
if(root) start().catch(()=>{root.querySelector('[data-status]').textContent='Energy baseline unavailable. No estimated values shown.';});
async function start(){
const response=await fetch(new URL('./source.json',import.meta.url));
if(!response.ok)throw Error('Baseline unavailable');
const source=validate(await response.json());
const reduced=matchMedia('(prefers-reduced-motion: reduce)');
const fmt=new Intl.NumberFormat('en-GB',{maximumFractionDigits:0});
const rate=new Intl.NumberFormat('en-GB',{maximumFractionDigits:1});
let paused=false,last=0;
const button=root.querySelector('button');button.disabled=false;
button.addEventListener('click',()=>{paused=!paused;button.textContent=paused?'Resume counters':'Pause counters';button.setAttribute('aria-pressed',String(paused));if(!paused)render();else root.querySelector('[data-status]').textContent='Paused. Illustration at 2024 average rates.';});
function render(){
const result=calculate(source,Date.now());
root.querySelector('[data-status]').textContent=(paused?'Paused. ':'')+(result.stale?'Baseline due for review. ':'')+'Illustration at 2024 average rates. Day resets at 00:00 UTC.';
for(const row of result.rows){const el=root.querySelector('[data-energy="'+row.id+'"]');el.querySelector('output').textContent=fmt.format(row.mwh)+' MWh';el.querySelector('progress').value=row.bar;el.querySelector('[data-rate]').textContent='~'+rate.format(row.perSecond)+' MWh / second';}
}
render();
function frame(t){if(!root.isConnected)return;if(!paused&&!document.hidden&&t-last>=(reduced.matches?1000:50)){render();last=t;}requestAnimationFrame(frame);}
requestAnimationFrame(frame);
}Model
A JavaScript module in the cartridges folder of GlobalGrid2050. It is built from the validate step (`validate`) and the calculate step (`calculate`).
transformglobalgrid2050 / cartridges/202609052143-open-energy/model.mjs · lines 1–17 of 17 · version 2026-09-05 21:43
- What it does
- It calculates its inputs. Defines validate, calculate.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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.
- Downstream impact
- Used directly by 3 files: Energy (globalgrid2050); Model Test (globalgrid2050); Fast Existing (globalgrid2050). Reached from 36 other entry points, including Homepage V059 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v059.html); Homepage V060 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v060.html); Homepage V061 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v061.html).
- What it achieves
- Original VENTUS model. Statistics and reuse terms are recorded in `source.json`.
- Why it matters
- Imported by Energy and Fast Existing. Checked by Model Test.
- Application
- globalgrid2050 · cartridges/202609052143-open-energy · JavaScript module
- Uses
- none found
- Used by
- imported by Energy (import), imported by Model Test (import), imported by Fast Existing (import)
- Produces
- MWH_PER_QUAD, DAY_MS, validate, calculate
- Defines here
- validate, calculate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 cartridges/202609052143-open-energy/model.mjs:1-17 · blob bf78471bea043f369294d74d6661d499ec1af88c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Original VENTUS model. Statistics and reuse terms are recorded in source.json.
export const MWH_PER_QUAD = 1e15 * 1055.05585262 / 3.6e9;
export const DAY_MS = 86400000;
export function validate(s) {
if (s?.schema !== 'ventus.energy-baseline.v1' || !Number.isInteger(s.referenceYear) || s.referenceYear < 1900 || s.referenceYear > 9998 || !Number.isFinite(s.totalQuadBtu) || s.totalQuadBtu <= 0 || !Number.isFinite(s.renewableQuadBtu) || s.renewableQuadBtu < 0 || s.renewableQuadBtu > s.totalQuadBtu || !s.url?.startsWith('https://') || !s.reuseUrl?.startsWith('https://') || !Number.isFinite(Date. … [line shortened here: 481 characters; full line on GitHub]
return s;
}
export function calculate(source, now) {
const s=validate(source);
if(!Number.isFinite(now)) throw new Error('Invalid clock');
const days=(Date.UTC(s.referenceYear+1,0,1)-Date.UTC(s.referenceYear,0,1))/DAY_MS;
const fraction=((now%DAY_MS)+DAY_MS)%DAY_MS/DAY_MS;
const daily=s.totalQuadBtu*MWH_PER_QUAD/days;
const renewable=s.renewableQuadBtu*MWH_PER_QUAD/days;
return {days, fraction, stale:now>=Date.parse(s.reviewAfter), daily,
rows:[['total',daily],['renewable',renewable],['nonrenewable',daily-renewable]].map(([id,value])=>({id,daily:value,mwh:value*fraction,perSecond:value/86400,bar:value*fraction/daily}))};
}Model Test
A test in the cartridges folder of GlobalGrid2050 that checks Model.
testglobalgrid2050 / cartridges/202609052143-open-energy/model.test.mjs · lines 1–10 of 10 · version 2026-09-05 21:43 · Entry point
- What it does
- It tests its inputs. Uses libraries node:test, node:assert/strict, node:fs. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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
- In: JSON file source.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Open Energy Cartridge Workflow (globalgrid2050).
- What it achieves
- It reads `./source.json`.
- Why it matters
- Run by GlobalGrid2050 Open Energy Cartridge Workflow.
- Application
- globalgrid2050 · cartridges/202609052143-open-energy · test
- Uses
- Model (import), node:test, node:assert/strict, node:fs
- Used by
- run by GlobalGrid2050 Open Energy Cartridge Workflow (workflow run)
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 cartridges/202609052143-open-energy/model.test.mjs:1-10 · blob 3bfe295e3006b3d1d484cd05ad5a0a1670a2bc3b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {calculate,MWH_PER_QUAD,validate} from './model.mjs';
const source=JSON.parse(readFileSync(new URL('./source.json',import.meta.url)));
test('conversion agrees with quad to TWh reference',()=>assert.ok(Math.abs(MWH_PER_QUAD/1e6-293.07107)<0.00001));
test('2024 leap baseline and UTC midnight/noon conserve components',()=>{const midnight=calculate(source,Date.UTC(2026,8,5));assert.equal(midnight.days,366);assert.ok(midnight.rows.every(x=>x.mwh===0));const noon=calculate(source,Date.UTC(2026,8,5,12));assert.equal(noon.rows[0].bar,0.5);assert.ok(Math.abs(noon.rows[1].mwh+noon.rows[2].mwh-noon.rows[0].mwh)<1e-6);assert.ok(Math.abs(noon.daily-48524 … [line shortened here: 415 characters; full line on GitHub]
test('day rollover resets; last millisecond stays below daily total',()=>{const end=calculate(source,Date.UTC(2026,8,6)-1);assert.ok(end.rows[0].mwh<end.daily);assert.equal(calculate(source,Date.UTC(2026,8,6)).rows[0].mwh,0);});
test('reject missing, nonfinite and inconsistent data',()=>{for(const s of [null,{}, {...source,totalQuadBtu:NaN},{...source,renewableQuadBtu:607},{...source,renewableQuadBtu:-1}])assert.throws(()=>validate(s));});
test('review deadline is exposed and nonleap baseline uses 365 days',()=>{assert.equal(calculate(source,Date.UTC(2027,8,5)).stale,true);assert.equal(calculate({...source,referenceYear:2023},Date.UTC(2026,8,5)).days,365);});