GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest and 2 more files

A Python command-line tool in the scripts folder that reads REPD publication q3, REPD publication q2, q2 baseline sha256 audit and q3 date provenance, using SHA-256.

700 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 886 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Renewable Energy Planning Database (REPD) Publication Baseline Probe energy-data · globalgrid2050 / scripts/repd_publication_baseline_probe.py lines 1–192
  2. GlobalGrid2050 Renewable Energy Planning Database (REPD) Q2 Q3 Verified Delta energy-data · globalgrid2050 / scripts/repd_q2_q3_verified_delta.py lines 1–150
  3. GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest energy-data · globalgrid2050 / scripts/repd_q3_2026_ingest.py lines 1–358

GlobalGrid2050 Renewable Energy Planning Database (REPD) Publication Baseline Probe

A Python module in the scripts folder that fetches REPD publication q2 and the REPD register, using SHA-256 from the GridAtlas repository.

energy-dataglobalgrid2050 / scripts/repd_publication_baseline_probe.py · lines 1–192 of 192 · Entry point · pattern browse (shared by 2 files)

What it does
It fetches REPD publication q2 and the REPD register. Defines sha, fetch, head, browse. Uses libraries __future__, asyncio, hashlib, json, os. Side effects: reads or writes files; makes network requests; starts processes.
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: data source: gridatlas data; CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx. Out: JSON file REPORT.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Renewable Energy Planning Database (REPD) Publication Baseline Probe Workflow (globalgrid2050).
What it achieves
It is built from the sha step (`sha`), the fetch step (`fetch`) and the head step (`head`). Read-only October 2026 REPD publication/archive and live-UI baseline probe.
Why it matters
Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Publication Baseline Probe Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
GridAtlas — Atlas Page (estate URL), __future__, asyncio, hashlib, json, os, re, subprocess, datetime
Used by
run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Publication Baseline Probe Workflow (workflow run)
Produces
sha, fetch, head, browse
Defines here
sha, fetch, head, browse
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/repd_publication_baseline_probe.py:1-192 · blob 02050338bbb5679c56370c03e450b92a7aaa28a9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Read-only October 2026 REPD publication/archive and live-UI baseline probe.

Writes only to an ignored/temporary report directory; NEVER updates site data,
release pointers, repository files, source records, or production applications.
A completed diagnostic job is NOT browser/MAP acceptance.
"""
from __future__ import annotations

import asyncio
import hashlib
import json
import os
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen

OUT = Path(os.environ.get("REPD_PROBE_OUT", ".repd-probe/2026-11-13"))
OUT.mkdir(parents=True, exist_ok=True)
BASE = "https://assets.publishing.service.gov.uk/media/"
OLD = {
    "csv": BASE + "6a6cbdc00c36759b5ccaa305/REPD_Publication_Q2_2026.csv",
    "xlsx": BASE + "6a6cbdd2862aaf18d9c62b02/REPD_Publication_Q2_2026.xlsx",
}
EXPECTED = {
    "csv": "84c1b5f958a934d8b4b86ec88f50bdcf43830ded7ff2efc27bffca0c98695035",
    "xlsx": "624a0a9712c58a7a93716e51f2bf054eec8b1af7170f6f9516cc10cd248e2657",
}
ARCHIVE_PAGE = (
    "https://tnaqa.mirrorweb.com/ukgwa/20261102130314oe_/"
    "https%3A/www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
)
PUBLICATION = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
PAGES = {
    "homepage": "https://globalgrid2050.com/",
    "pipeline": "https://globalgrid2050.com/uk_renewables_pipeline/202609082224/",
    "atlas": "https://ventusltd.github.io/gridatlas/atlas/",
}
REPORT = {
    "purpose": "NONPRODUCTION_DIAGNOSTIC_ONLY_NOT_RELEASE_QA",
    "checked_utc": datetime.now(timezone.utc).isoformat(),
    "publication": {},
    "old_q2": {},
    "archives": {},
    "browser": {},
    "limitations": [
        "Browser screenshots and page counters are observations, not application acceptance.",
        "No downstream October REPD candidate was deployed or tested by this script.",
        "No raw July Q2 comparison is valid unless BOTH expected original SHA256 values match.",
    ],
}


def sha(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


def fetch(url: str, timeout: int = 55) -> tuple[bytes, str]:
    with urlopen(Request(url, headers={"User-Agent": "GlobalGrid2050-REPD-source-audit/1.0"}), timeout=timeout) as response:
        return response.read(), response.geturl()


def head(url: str) -> dict:
    # curl without -L: do not follow redirects, preserve original response headers.
    result = subprocess.run(
        ["curl", "-sSI", "--max-time", "30", "--connect-timeout", "12", url],
        text=True, capture_output=True, timeout=38, check=False,
    )
    return {"url": url, "curl_exit": result.returncode,
            "headers": result.stdout[:10000], "stderr": result.stderr[:1000]}


for kind, url in OLD.items():
    entry = {"head_without_redirect": head(url), "expected_sha256": EXPECTED[kind]}
    try:
        data, final_url = fetch(url, 95)
        entry.update({"get_final_url": final_url, "get_bytes": len(data),
                      "get_sha256": sha(data), "original_q2_verified": sha(data) == EXPECTED[kind]})
        if entry["original_q2_verified"]:
            (OUT / ("verified-original-Q2." + kind)).write_bytes(data)
    except Exception as exc:
        entry["get_error"] = str(exc)[:350]
        entry["original_q2_verified"] = False
    REPORT["old_q2"][kind] = entry

try:
    raw, final = fetch(PUBLICATION)
    html = raw.decode("utf-8", "replace")
    REPORT["publication"] = {
        "url": final, "bytes": len(raw), "sha256": sha(raw),
        "october_2026_mentioned": bool(re.search("October\\s+2026", html, re.I)),
        "updated_13_nov_2026_mentioned": bool(re.search("13\\s+November\\s+2026", html, re.I)),
    }
except Exception as exc:
    REPORT["publication"] = {"error": str(exc)[:350]}

for name, url in {
    "ukgwa_2026_11_02_page": ARCHIVE_PAGE,
    "wayback_cdx_csv": "https://web.archive.org/cdx/search/cdx?url=" + OLD["csv"] + "&output=json&filter=statuscode:200",
    "wayback_cdx_xlsx": "https://web.archive.org/cdx/search/cdx?url=" + OLD["xlsx"] + "&output=json&filter=statuscode:200",
    "ukgwa_asset_csv": "https://tnaqa.mirrorweb.com/ukgwa/20261102130314oe_/https%3A/assets.publishing.service.gov.uk/media/6a6cbdc00c36759b5ccaa305/REPD_Publication_Q2_2026.csv",
    "ukgwa_asset_xlsx": "https://tnaqa.mirrorweb.com/ukgwa/20261102130314oe_/https%3A/assets.publishing.service.gov.uk/media/6a6cbdd2862aaf18d9c62b02/REPD_Publication_Q2_2026.xlsx",
}.items():
    entry = head(url)
    # Archived HTML/CDX is evidence of listing, NOT the original attachment bytes.
    if name.endswith("page") or "cdx" in name:
        try:
            raw, final = fetch(url, 30)
            entry.update({"get_final_url": final, "get_bytes": len(raw),
                          "get_sha256": sha(raw),
                          "excerpt": raw[:1200].decode("utf-8", "replace")})
        except Exception as exc:
            entry["get_error"] = str(exc)[:350]
    if name.startswith("ukgwa_asset_"):
        kind = name.rsplit("_", 1)[-1]
        try:
            raw, final = fetch(url, 70)
            entry.update({"get_final_url": final, "get_bytes": len(raw),
                          "get_sha256": sha(raw),
                          "expected_original_sha256": EXPECTED[kind],
                          "original_q2_verified": sha(raw) == EXPECTED[kind]})
            if entry["original_q2_verified"]:
                (OUT / ("verified-archived-original-Q2." + kind)).write_bytes(raw)
        except Exception as exc:
            entry["get_error"] = str(exc)[:350]
            entry["original_q2_verified"] = False
    REPORT["archives"][name] = entry


async def browse() -> None:
    try:
        from playwright.async_api import async_playwright
    except ImportError as exc:
        REPORT["browser"]["error"] = "playwright unavailable: " + str(exc)
        return
    async with async_playwright() as playwright:
        browser = await playwright.chromium.launch(headless=True, args=["--disable-dev-shm-usage"])
        try:
            for size, viewport, mobile in [
                ("desktop", {"width": 1440, "height": 900}, False),
                ("mobile", {"width": 390, "height": 844}, True),
            ]:
                context = await browser.new_context(viewport=viewport, is_mobile=mobile,
                                                    has_touch=mobile, device_scale_factor=1)
                try:
                    for name, url in PAGES.items():
                        key = name + "_" + size
                        page = await context.new_page()
                        errors = []
                        page.on("pageerror", lambda exc: errors.append(str(exc)[:300]))
                        entry = {"requested_url": url, "viewport": viewport}
                        try:
                            response = await page.goto(url, wait_until="domcontentloaded", timeout=50000)
                            await page.wait_for_timeout(9000 if name == "atlas" else 6500)
                            entry.update({
                                "http_status": response.status if response else None,
                                "final_url": page.url,
                                "title": await page.title(),
                                "visible_text_excerpt": (await page.locator("body").inner_text(timeout=15000))[:2800],
                                "table_body_rows": await page.locator("table tbody tr").count(),
                                "canvas_count": await page.locator("canvas").count(),
                                "page_errors": errors[:15],
                            })
                            screenshot = OUT / (key + ".png")
                            await page.screenshot(path=str(screenshot), full_page=False, timeout=18000)
                            entry["screenshot"] = screenshot.name
                        except Exception as exc:
                            entry["error"] = str(exc)[:450]
                            entry["page_errors"] = errors[:15]
                        REPORT["browser"][key] = entry
                        await page.close()
                finally:
                    await context.close()
        finally:
            await browser.close()


try:
    asyncio.run(browse())
except Exception as exc:
    REPORT["browser"]["fatal_error"] = str(exc)[:500]
(OUT / "REPORT.json").write_text(json.dumps(REPORT, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(json.dumps({
    "status": "DIAGNOSTIC_ONLY",
    "publication": REPORT["publication"],
    "old_q2": {k: {"get_sha256": v.get("get_sha256"), "original_q2_verified": v["original_q2_verified"],
                    "head_first_line": v["head_without_redirect"]["headers"].split("\n")[0]}
               for k, v in REPORT["old_q2"].items()},
    "browser_observations": len(REPORT["browser"]),
}, indent=2))

GlobalGrid2050 Renewable Energy Planning Database (REPD) Q2 Q3 Verified Delta

A Python command-line tool in the scripts folder covering REPD publication q2 and the REPD register, using SHA-256.

energy-dataglobalgrid2050 / scripts/repd_q2_q3_verified_delta.py · lines 1–150 of 150 · Entry point · pattern numeric (shared by 5 files)

What it does
Defines verify, rows, index, numeric, main. Uses libraries __future__, argparse, csv, hashlib, io. 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: CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Renewable Energy Planning Database (REPD) Q2 Original Evidence Workflow (globalgrid2050).
What it achieves
It is built from the verify step (`verify`), the rows step (`rows`) and the index step (`index`). Prove original July 2026 REPD recovery and compare raw Q2/Q3 source records. It accepts `--out`.
Why it matters
Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Q2 Original Evidence Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, hashlib, io, json, collections, datetime
Used by
run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Q2 Original Evidence Workflow (workflow run)
Produces
verify, rows, index, numeric, main
Defines here
verify, rows, index, numeric, 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 scripts/repd_q2_q3_verified_delta.py:1-150 · blob 4f36bc60962f56aa770f45d3575824b91fad0c41 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Prove original July 2026 REPD recovery and compare raw Q2/Q3 source records.

Evidence-only. Never writes production data or changes an existing release.
Field change counts are raw CSV text differences, NOT all substantive changes.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
from collections import Counter
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path

EXPECTED = {
    "q2_csv": "84c1b5f958a934d8b4b86ec88f50bdcf43830ded7ff2efc27bffca0c98695035",
    "q2_xlsx": "624a0a9712c58a7a93716e51f2bf054eec8b1af7170f6f9516cc10cd248e2657",
    "q3_csv": "48e76c49f33a1090e78108d1ea9bfe689b35963ea3be1bb4f6516d038a5ff862",
    "q3_xlsx": "87811e249395a05b223db6855952334f425e66cc9a2106caea0e38fd9e5037ea",
}
ARCHIVE_PAGE = "https://tnaqa.mirrorweb.com/ukgwa/20261102130314oe_/https%3A/www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
ARCHIVED_CSV = "https://tnaqa.mirrorweb.com/ukgwa/20261103070426oe_/https://assets.publishing.service.gov.uk/media/6a6cbdc00c36759b5ccaa305/REPD_Publication_Q2_2026.csv"
ARCHIVED_XLSX = "https://tnaqa.mirrorweb.com/ukgwa/20261103065723oe_/https://assets.publishing.service.gov.uk/media/6a6cbdd2862aaf18d9c62b02/REPD_Publication_Q2_2026.xlsx"


def verify(path: Path, expected: str) -> bytes:
    data = path.read_bytes()
    actual = hashlib.sha256(data).hexdigest()
    if actual != expected:
        raise ValueError(f"Source hash mismatch {path}: {actual} != {expected}")
    return data


def rows(raw: bytes) -> tuple[list[str], list[dict[str, str]]]:
    try:
        text = raw.decode("utf-8-sig")
    except UnicodeDecodeError:
        text = raw.decode("cp1252")
    reader = csv.reader(io.StringIO(text, newline=""))
    header = [" ".join(s.split()) for s in next(reader)]
    if len(header) != 53 or len(set(header)) != 53:
        raise ValueError("Official 53-column header invalid")
    result = []
    for number, fields in enumerate(reader, 2):
        if len(fields) != 53:
            raise ValueError(f"Truncated/malformed record at CSV line {number}: {len(fields)} fields")
        result.append(dict(zip(header, fields)))
    return header, result


def index(items: list[dict[str, str]], allow_one_identical_duplicate: bool) -> tuple[dict[str, dict[str, str]], dict]:
    by_ref = {}
    duplicates = Counter()
    for item in items:
        ref = item["Ref ID"].strip()
        if not ref or not ref.isdecimal():
            raise ValueError(f"Invalid Ref ID: {ref!r}")
        if ref in by_ref:
            if not allow_one_identical_duplicate or ref != "7679" or item != by_ref[ref]:
                raise ValueError(f"Unexpected conflicting/duplicate Ref ID: {ref}")
            duplicates[ref] += 1
        else:
            by_ref[ref] = item
    if allow_one_identical_duplicate and dict(duplicates) != {"7679": 1}:
        raise ValueError(f"Expected exact duplicate 7679, got {dict(duplicates)}")
    if not allow_one_identical_duplicate and duplicates:
        raise ValueError(f"Unexpected duplicate in July: {dict(duplicates)}")
    return by_ref, dict(duplicates)


def numeric(value: str):
    try:
        return Decimal(value.replace(",", "").strip())
    except InvalidOperation:
        return None


def main() -> None:
    parser = argparse.ArgumentParser()
    for key in EXPECTED:
        parser.add_argument("--" + key.replace("_", "-"), type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args()
    raw = {k: verify(getattr(args, k), v) for k, v in EXPECTED.items()}
    h2, source2 = rows(raw["q2_csv"])
    h3, source3 = rows(raw["q3_csv"])
    if h2 != h3:
        raise ValueError("Q2 and Q3 source column names/order differ")
    if len(source2) != 14657 or len(source3) != 14968:
        raise ValueError("Unexpected official source row count")
    old, d2 = index(source2, False)
    new, d3 = index(source3, True)
    if len(old) != 14657 or len(new) != 14967:
        raise ValueError("Unexpected unique identity count")
    old_ids, new_ids = set(old), set(new)
    common = sorted(old_ids & new_ids, key=int)
    added = sorted(new_ids - old_ids, key=int)
    removed = sorted(old_ids - new_ids, key=int)
    field_changes = {}
    for field in h2:
        changed = sum(old[ref][field].strip() != new[ref][field].strip() for ref in common)
        if changed:
            field_changes[field] = changed
    capacity = "Installed Capacity (MWelec)"
    numeric_capacity_changed = sum(
        numeric(old[ref][capacity]) != numeric(new[ref][capacity]) for ref in common
    )
    report = {
        "schema": "globalgrid2050.repd-q2-to-q3-raw-verified.v1",
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "source": "Official DESNZ REPD July and October 2026 raw CSV and Excel",
        "q2_recovered_archive_page": ARCHIVE_PAGE,
        "q2_recovered_csv_url": ARCHIVED_CSV,
        "q2_recovered_xlsx_url": ARCHIVED_XLSX,
        "source_sha256": EXPECTED,
        "source_bytes": {k: len(v) for k, v in raw.items()},
        "q2_original_rows": len(source2),
        "q2_unique_refs": len(old),
        "q3_original_rows": len(source3),
        "q3_unique_refs": len(new),
        "source_columns": len(h2),
        "q2_duplicates": d2,
        "q3_identical_duplicates": d3,
        "q3_last_ref": source3[-1]["Ref ID"],
        "identity_delta": {
            "added": len(added), "removed": len(removed), "retained": len(common),
            "added_refs": added, "removed_refs": removed,
        },
        "field_change_counts_raw_csv_text": field_changes,
        "capacity_changed_numeric_csv": numeric_capacity_changed,
        "interpretation": "Source-to-source record comparison. Differences in dates, whitespace and rounded capacities can be representational; typed Excel review is needed before treating each changed cell as a substantive project event.",
        "production_deployed": False,
    }
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(json.dumps({
        "result": "PASS", "q2_rows": len(source2), "q3_rows": len(source3),
        "q3_unique": len(new), "added": len(added), "removed": len(removed),
        "status_changed": field_changes.get("Development Status (short)", 0),
        "technology_changed": field_changes.get("Technology Type", 0),
        "capacity_numeric_changed": numeric_capacity_changed,
    }, indent=2))


if __name__ == "__main__":
    main()

GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest

A Python command-line tool in the scripts folder that reads REPD publication q3, REPD publication q2, q2 baseline sha256 audit and q3 date provenance, using SHA-256.

energy-dataglobalgrid2050 / scripts/repd_q3_2026_ingest.py · lines 1–358 of 370 · Entry point · pattern reconcile (shared by 7 files)

What it does
It loads REPD publication q3, REPD publication q2, q2 baseline sha256 audit and q3 date provenance. Defines 7 functions or classes, including strict_date_iso, day_first, digest, check, canonicalise_exact_duplicates. Uses libraries __future__, hashlib, json, os, sys. 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.
Inputs & outputs
In: CSV file REPD_Publication_Q3_2026.csv; Excel file REPD_Publication_Q3_2026.xlsx; CSV file repd.csv; CSV file Q3_DATE_PROVENANCE.csv. Out: CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx; JSON file Q2_BASELINE_SHA256_AUDIT.json; CSV file REPD_Publication_Q3_2026.csv; Excel file REPD_Publication_Q3_2026.xlsx; JSON file Q3_RECONCILIATION.json; CSV file Q3_CANONICAL_STAGED.csv.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 Evidence Branch Workflow (globalgrid2050).
What it achieves
It is built from the strict date iso helper (`strict_date_iso`), the day first helper (`day_first`) and the digest step (`digest`). Isolated DESNZ October 2026 (Q3) REPD intake and Q2 delta audit. Its code works with 0.0050001 MW.
Why it matters
Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow and GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 Evidence Branch Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Renewable Energy Planning Database (REPD) Sources V6 (import), __future__, hashlib, json, os, sys, datetime, pandas, pathlib
Used by
run by GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow (workflow run), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 Evidence Branch Workflow (workflow run)
Produces
strict_date_iso, day_first, digest, check, canonicalise_exact_duplicates, reconcile, main
Defines here
strict_date_iso, day_first, digest, check, canonicalise_exact_duplicates, reconcile, 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 scripts/repd_q3_2026_ingest.py:1-358 · blob e59eec0b7ed013345cf603686f3260b9350849a1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Isolated DESNZ October 2026 (Q3) REPD intake and Q2 delta audit.

NO live files, Q2/V6 outputs, homepage files or historical releases are modified.
Outputs are staged for review and uploaded as temporary GitHub Actions artifacts.
"""
from __future__ import annotations

import hashlib
import json
import os
import sys
from datetime import date, datetime

import pandas as pd
from pathlib import Path

# Reuse the already validated Q2 parsing, identity and canonical capacity rules.
sys.path.insert(0, str(Path(__file__).resolve().parent))
import repd_sources_v6 as q2  # noqa: E402
import repd_date_rule  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
OUT = Path(os.environ.get("REPD_Q3_OUTPUT", ROOT / ".repd-staging" / "2026-10"))
SOURCE_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
Q3_CSV = "https://assets.publishing.service.gov.uk/media/6af42ff0a4004bdbe54e54a5/REPD_Publication_Q3_2026.csv"
Q3_XLSX = "https://assets.publishing.service.gov.uk/media/6af42ffdb83b3cae0d0a21c9/REPD_Publication_Q3_2026.xlsx"
PUBLICATION_DATE = "2026-11-13"
LAST_UPDATED = "Record Last Updated (dd/mm/yyyy)"
# No per-release ref allow-list.  repd_date_rule decides every date cell from the
# two official files: the typed Excel date is the value; CSV text must agree as
# d/m/yyyy, or as m/d/yyyy only where that cell's own Excel number format is an
# explicit month-first format.  Anything else rejects the release.
# These columns must be present as date columns; any further column that Excel
# types as dates throughout (the appeal and Secretary of State dates, Judicial
# Review) is discovered and held to the same rule.
REQUIRED_DATE_COLUMNS = tuple(dict.fromkeys(q2.OFFICIAL_DATE_FIELDS + [LAST_UPDATED]))
FUTURE_DATED_BY_DESIGN = ("Planning Permission Expired",)
VALIDATED_Q2_UNIQUE_REFS = 14657


def strict_date_iso(value) -> str:
    """Strict canonical date interpretation: never silently infer US month-first."""
    if value is None or (not isinstance(value, str) and pd.isna(value)):
        return ""
    if isinstance(value, (datetime, pd.Timestamp)):
        return value.strftime("%Y-%m-%d")
    raw = q2.collapse(value)
    if raw.casefold() in {"", "na", "n/a"}:
        return ""
    for fmt in ("%d/%m/%Y", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.strptime(raw, fmt).strftime("%Y-%m-%d")
        except ValueError:
            continue
    return ""


def day_first(iso: str) -> str:
    return datetime.strptime(iso, "%Y-%m-%d").strftime("%d/%m/%Y") if iso else ""


BASELINE_COMMIT = "73cbdec10bbd3fe2f8313b60b1acc2d22d31b517"


def digest(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def check(condition: bool, label: str, issues: list[str]) -> None:
    if not condition:
        issues.append(label)


def canonicalise_exact_duplicates(frame, label: str, issues: list[str]) -> tuple[pd.DataFrame, list[dict]]:
    """Quarantine only exactly equivalent repeated identity rows; never merge contradictions."""
    ref_col = "Ref ID"
    if ref_col not in frame.columns:
        raise RuntimeError(f"{label}: Ref ID column missing")
    refs = [q2.clean_ref(value) for value in frame[ref_col]]
    positions: dict[str, list[int]] = {}
    for i, ref in enumerate(refs):
        positions.setdefault(ref, []).append(i)
    quarantined = []
    for ref, indices in positions.items():
        if len(indices) == 1:
            continue
        first = tuple(q2.collapse(v) for v in frame.iloc[indices[0]].tolist())
        identical = all(tuple(q2.collapse(v) for v in frame.iloc[i].tolist()) == first for i in indices[1:])
        quarantined.append({
            "repd_ref": ref, "source_rows_1_based_including_header": [i + 2 for i in indices],
            "occurrences": len(indices), "exactly_identical": identical,
        })
        if not identical:
            issues.append(f"{label}: conflicting duplicate REPD reference {ref}; refusing canonical data")
    seen = set()
    retained = []
    for i, ref in enumerate(refs):
        if ref not in seen:
            retained.append(i)
            seen.add(ref)
    return frame.iloc[retained].copy().reset_index(drop=True), quarantined


def reconcile(csv_data: bytes, xlsx_data: bytes, old_data: bytes, baseline_name: str, baseline_is_q2: bool,
              minimum_refs: int = VALIDATED_Q2_UNIQUE_REFS,
              provenance_path: Path | None = None) -> tuple[pd.DataFrame | None, dict]:
    issues: list[str] = []
    csv_original = q2.read_csv(csv_data)
    xlsx_original, sheet = q2.read_xlsx(xlsx_data)
    current_csv, csv_duplicate_evidence = canonicalise_exact_duplicates(csv_original, "Q3 CSV", issues)
    current_xlsx, excel_duplicate_evidence = canonicalise_exact_duplicates(xlsx_original, "Q3 Excel", issues)
    # The previous release may itself carry identical duplicate rows (October 2026
    # does: ref 7679), so it gets the same treatment before it is indexed.
    previous, _ = canonicalise_exact_duplicates(q2.read_csv(old_data), "Comparison baseline", issues)
    c = q2.indexed(current_csv, "Q3 CSV")
    x = q2.indexed(current_xlsx, "Q3 XLSX")
    old = q2.indexed(previous, "Q2 CSV")
    csv_ids, excel_ids, old_ids = set(c.index), set(x.index), set(old.index)
    # Fail closed against the last independently validated July/Q2 release.
    # The historical root file is not a Q2 source and must not lower this floor.
    # Also never accept fewer references than the release actually compared against.
    floor = max(minimum_refs, len(old))
    check(len(c) >= floor and len(x) >= floor,
          f"Q3 unique reference count below the previous-release floor ({floor:,})", issues)
    check(csv_data.endswith(b"\n"), "Q3 source CSV has no final newline", issues)
    # General date rule (typed openpyxl read: pandas discards the number formats
    # the rule depends on).  Every date cell is explained or the release rejects.
    dates = repd_date_rule.evaluate(
        csv_data, xlsx_data, sheet=sheet,
        required_date_columns=REQUIRED_DATE_COLUMNS,
        future_ok_columns=FUTURE_DATED_BY_DESIGN,
        as_of=date.fromisoformat(PUBLICATION_DATE),
        normalise_header=lambda name: q2.canonicalise_headers(pd.DataFrame(columns=[name])).columns[0],
    )
    issues.extend(dates.failure_messages())
    date_fields = list(dates.date_columns)
    invalid_dates = [{"source": "CSV/XLSX", "ref": item["ref"], "field": item["column"],
                      "raw_value": item["csv_text"][:80], "excel_value": item["excel_value"],
                      "rule": item["rule"]} for item in dates.failures]
    if provenance_path is not None:
        repd_date_rule.write_provenance_csv(dates, provenance_path)
    check(csv_ids == excel_ids, "CSV and Excel REPD reference sets differ", issues)
    check({x["repd_ref"] for x in csv_duplicate_evidence} == {x["repd_ref"] for x in excel_duplicate_evidence}, "CSV/Excel duplicate identity disagreement", issues)
    check(len(c) == len(csv_ids), "Duplicate Q3 CSV references", issues)
    check(len(x) == len(excel_ids), "Duplicate Q3 XLSX references", issues)
    # A historical root CSV is suitable for continuity comparisons but not a Q2 release.
    check(len(old_ids) == len(old), "Historical baseline has duplicate references", issues)
    check("Ref ID" in c and "Ref ID" in x, "Q3 missing Ref ID", issues)
    check(set(q2.CORE_TEXT_FIELDS + q2.OFFICIAL_DATE_FIELDS).issubset(c.columns), "Q3 CSV missing required original fields", issues)
    check(set(q2.CORE_TEXT_FIELDS + q2.OFFICIAL_DATE_FIELDS).issubset(x.columns), "Q3 Excel missing required original fields", issues)

    # Month-first cells are whatever the rule finds, in any date column.  The
    # record-update chronology is recorded as corroboration, not used as a gate:
    # 108 day-first Planning Application Submitted dates in this very release
    # are later than their Record Last Updated, so it is not an invariant.
    source_locale_date_normalisations = []
    for cell in dates.month_first_cells:
        ref = cell["ref"]
        last_updated = dates.output.get((ref, LAST_UPDATED), "")
        last_updated = datetime.strptime(last_updated, "%d/%m/%Y").strftime("%Y-%m-%d") if last_updated else ""
        source_locale_date_normalisations.append({
            "repd_ref": ref, "field": cell["column"],
            "official_csv": cell["csv_text"], "official_xlsx": cell["excel_value"],
            "excel_number_format": cell["excel_number_format"],
            "record_last_updated": last_updated,
            "chronology_consistent": bool(last_updated) and cell["excel_value"] <= last_updated <= PUBLICATION_DATE,
            "csv_also_valid_day_first": bool(cell.get("csv_valid_day_first")),
            "csv_text_changed": cell["rule"] == repd_date_rule.OK_MONTH_FIRST,
            "candidate_value": cell["output"],
            "resolution": "PROVISIONAL_EXCEL_TYPED_DATE_LOCALE_NORMALISATION",
        })

    mismatches = []
    rounding_differences = 0
    checked = 0
    fields = list(dict.fromkeys(q2.CORE_TEXT_FIELDS + q2.OFFICIAL_DATE_FIELDS))
    comparable = all(field in c and field in x for field in fields)
    if comparable:
        for ref in sorted(csv_ids & excel_ids):
            a, b = c.loc[ref], x.loc[ref]
            checked += 1
            for field in fields:
                if field == "Planning Application Reference":
                    equal = q2.planning_refs_equivalent(a[field], b[field])
                elif field in date_fields:
                    # Already decided cell by cell by repd_date_rule; a
                    # disagreement is in ``issues`` with both raw values.
                    equal = True
                else:
                    equal = q2.norm_text(a[field]) == q2.norm_text(b[field])
                if not equal:
                    mismatches.append((ref, field))
            left = q2.norm_number(a.get("Installed Capacity (MWelec)"))
            right = q2.norm_number(b.get("Installed Capacity (MWelec)"))
            if left is None or right is None:
                if left != right:
                    mismatches.append((ref, "Installed Capacity (MWelec)"))
            elif abs(left - right) > q2.CAPACITY_ROUNDING_TOLERANCE_MW:
                mismatches.append((ref, "Installed Capacity (MWelec)"))
            elif left != right:
                rounding_differences += 1
    unexpected_mismatches = list(mismatches)
    check(not unexpected_mismatches,
          f"Unexpected material CSV/Excel disagreements: {unexpected_mismatches[:10]}", issues)
    # Cells whose CSV text is also a valid but different day-first date: only the
    # Excel typing and number format distinguish them, so list them separately.
    previously_disputed = [
        event for event in source_locale_date_normalisations
        if event["csv_also_valid_day_first"] and event["csv_text_changed"]
    ]

    added, removed, retained = csv_ids - old_ids, old_ids - csv_ids, csv_ids & old_ids
    updated_status = []
    updated_capacity = []
    updated_technology = []
    for ref in retained:
        before, after = old.loc[ref], c.loc[ref]
        if q2.norm_text(before.get("Development Status (short)")) != q2.norm_text(after.get("Development Status (short)")):
            updated_status.append(ref)
        if q2.norm_text(before.get("Technology Type")) != q2.norm_text(after.get("Technology Type")):
            updated_technology.append(ref)
        if q2.norm_number(before.get("Installed Capacity (MWelec)")) != q2.norm_number(after.get("Installed Capacity (MWelec)")):
            updated_capacity.append(ref)

    canonical = q2.build_canonical(current_csv, current_xlsx) if not issues else None
    if canonical is not None:
        # Serialise ALL official dates in strict dd/mm/yyyy so no month-first
        # fragments can survive unnoticed in a column consumed as day-first.
        for field in date_fields:
            if field not in canonical.columns:
                continue
            canonical[field] = [dates.output[(ref, field)] for ref in canonical["Ref ID"].astype(str)]
        solar, bess = q2.threshold_counts(canonical)
    else:
        solar, bess = 0, 0
    report = {
        "schema": "globalgrid2050.repd-q3-2026-intake.v1",
        "stage": "REJECTED" if issues else "STAGED_WITH_SOURCE_DATE_LOCALE_NORMALISATIONS",
        "validated_at": q2.utc_now(),
        "source_owner": "UK DESNZ / Barbour ABI",
        "source_page": SOURCE_PAGE,
        "publication_date": PUBLICATION_DATE,
        "baseline_commit": BASELINE_COMMIT,
        "comparison_baseline": baseline_name,
        "comparison_baseline_sha256": digest(old_data),
        "comparison_baseline_rows": len(old),
        "comparison_is_validated_q2": baseline_is_q2,
        "last_validated_q2_row_count": 14657,
        "q2_row_level_delta_available": baseline_is_q2,
        "q3_source_csv": Q3_CSV,
        "q3_source_xlsx": Q3_XLSX,
        "q3_source_sha256": {"csv": digest(csv_data), "xlsx": digest(xlsx_data)},
        "xlsx_sheet": sheet,
        "csv_rows": len(c),
        "xlsx_rows": len(x),
        "original_csv_rows": len(csv_original),
        "original_xlsx_rows": len(xlsx_original),
        "identical_source_duplicates_quarantined": {
            "csv": csv_duplicate_evidence, "xlsx": excel_duplicate_evidence,
            "source_rows_not_in_candidate": len(csv_original) - len(c)
        },
        "q3_unique_ids": len(csv_ids),
        "duplicate_handling": "Raw official files retained unchanged; only identical source duplicates eliminated from candidate; conflicting records reject data.",
        "csv_excel_id_sets_match": csv_ids == excel_ids,
        "source_columns": {"csv": len(current_csv.columns), "xlsx": len(current_xlsx.columns)},
        "material_mismatch_count": len(mismatches),
        "source_locale_date_normalisation_count": len(source_locale_date_normalisations),
        "unparseable_nonblank_date_cells": invalid_dates,
        "material_mismatch_ref_field_examples": mismatches[:20],
        "quarantined_official_date_disagreements": [],
        "formerly_ambiguous_date_representations": previously_disputed,
        "source_locale_date_normalisations": source_locale_date_normalisations,
        "date_rule": dates.summary(),
        "date_rule_plausibility_flags": dates.plausibility_flags,
        "date_typed_cells_in_non_date_columns": dates.stray_excel_dates,
        "date_cells_not_plain_day_first": [
            item for item in dates.provenance if item["rule"] != repd_date_rule.OK_DAY_FIRST],
        "unexpected_material_disagreements": unexpected_mismatches,
        "date_policy": f"General rule, no ref allow-list: typed Excel date is the value in every date column; CSV text must agree as d/m/yyyy, or as m/d/yyyy only where the cell's Excel number format is explicitly month-first ({len(source_locale_date_normalisations)} such cells). Blank-equivalent text is counted in date_rule. Raw official representations retained in audit. Independent review and o  … [line shortened here: 433 characters; full line on GitHub]
        "capacity_rounding_differences": rounding_differences,
        "records_compared_across_csv_and_excel": checked,
        "reference_changes_vs_comparison_baseline": {
            "new_refs": len(added), "removed_refs": len(removed),
            "retained_refs": len(retained), "status_changed": len(updated_status),
            "technology_changed": len(updated_technology),
            "csv_capacity_changed": len(updated_capacity),
            "new_ref_examples": sorted(added)[:20],
            "removed_ref_examples": sorted(removed)[:20],
        },
        "candidate_threshold_counts": {"solar_gt_1mw": solar, "battery_gt_100mw": bess},
        "capacity_policy": "Reconciled official Excel precision, CSV within 0.0050001 MW rounding tolerance",
        "no_production_promotion": True,
        "failures": issues,
    }
    return canonical, report


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    raw_dir = OUT / "official-sources"
    raw_dir.mkdir(exist_ok=True)
    # Preserve official Q2 inputs alongside the Git SHA and text backup log.
    old_csv = q2.fetch_bytes(q2.CSV_URL)
    old_xlsx = q2.fetch_bytes(q2.XLSX_URL)
    (raw_dir / "REPD_Publication_Q2_2026.csv").write_bytes(old_csv)
    (raw_dir / "REPD_Publication_Q2_2026.xlsx").write_bytes(old_xlsx)
    baseline_provenance = {
        "q2_csv_expected_sha256": q2.EXPECTED_CSV_SHA256,
        "q2_csv_observed_sha256": digest(old_csv),
        "q2_csv_bytes": len(old_csv),
        "q2_xlsx_expected_sha256": q2.EXPECTED_XLSX_SHA256,
        "q2_xlsx_observed_sha256": digest(old_xlsx),
        "q2_xlsx_bytes": len(old_xlsx),
    }
    (OUT / "Q2_BASELINE_SHA256_AUDIT.json").write_text(
        json.dumps(baseline_provenance, indent=2) + "\n", encoding="utf-8"
    )
    q2_verified = digest(old_csv) == q2.EXPECTED_CSV_SHA256 and digest(old_xlsx) == q2.EXPECTED_XLSX_SHA256
    if q2_verified:
        comparison_data = old_csv
        comparison_name = "Validated July 2026 (Q2) official CSV"
    else:
        # Historical download URLs have changed contents. Never represent them as July 2026.
        comparison_data = (ROOT / "repd.csv").read_bytes()
        comparison_name = "Historical root repd.csv (January 2026 era; NOT Q2)"
    baseline_provenance.update({
        "q2_download_matches_pinned_snapshot": q2_verified,
        "q2_delta_unavailable": not q2_verified,
        "comparison_baseline": comparison_name,
        "historical_root_sha256": digest(comparison_data),
        "note": "Downloaded July-labelled sources differ from immutable Q2 fingerprints. July Q2 per-reference comparison unavailable until original official bytes are recovered." if not q2_verified else "July source fingerprints matched."
    })
    (OUT / "Q2_BASELINE_SHA256_AUDIT.json").write_text(json.dumps(baseline_provenance, indent=2) + "\n", encoding="utf-8")

    csv_raw = q2.fetch_bytes(Q3_CSV)
    excel_raw = q2.fetch_bytes(Q3_XLSX)
    (raw_dir / "REPD_Publication_Q3_2026.csv").write_bytes(csv_raw)
    (raw_dir / "REPD_Publication_Q3_2026.xlsx").write_bytes(excel_raw)
    canonical, report = reconcile(csv_raw, excel_raw, comparison_data, comparison_name, q2_verified,
                                  provenance_path=OUT / "Q3_DATE_PROVENANCE.csv")
    baseline_provenance["observed_q2_csv_identical_to_q3_csv"] = digest(old_csv) == digest(csv_raw)
    baseline_provenance["observed_q2_excel_identical_to_q3_excel"] = digest(old_xlsx) == digest(excel_raw)
    (OUT / "Q2_BASELINE_SHA256_AUDIT.json").write_text(json.dumps(baseline_provenance, indent=2) + "\n", encoding="utf-8")
    report["baseline_q2_provenance"] = baseline_provenance
    (OUT / "Q3_RECONCILIATION.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    with (OUT / "INGESTION-LOG.txt").open("w", encoding="utf-8") as handle:
        handle.write(f"REPD October 2026 intake: {report['stage']}\n")
        handle.write(f"Published: {PUBLICATION_DATE}; baseline commit: {BASELINE_COMMIT}\n")
        handle.write(f"CSV rows: {report['csv_rows']}; Excel rows: {report['xlsx_rows']}\n")
        handle.write(f"CSV SHA-256: {digest(csv_raw)}\nExcel SHA-256: {digest(excel_raw)}\n")
        handle.write("Comparison baseline: " + comparison_name + "\n")
        handle.write("Original Q2 bytes at historical links: " + ("verified" if q2_verified else "CHANGED; historical root used instead") + "\n")
        handle.write("Changed records: " + json.dumps(report["reference_changes_vs_comparison_baseline"], sort_keys=True) + "\n")
        handle.write(f"Provisional source date-locale corrections ({report['source_locale_date_normalisation_count']}): " + json.dumps(report["source_locale_date_normalisations"], sort_keys=True) + "\n")
        handle.write("Blank-equivalent date cells: " + json.dumps(report["date_rule"]["blank_equivalent_counts"], sort_keys=True) + "\n")
        handle.write("Duplicate source rows: " + json.dumps(report["identical_source_duplicates_quarantined"], sort_keys=True) + "\n")
        handle.write("Failures: " + json.dumps(report["failures"]) + "\n")