GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Clean and 1 more file (part 2)

A Python command-line tool in the automation folder of GlobalGrid2050 that hashes paths, builds log and verifies against official, covering official, REPD cleaned and cleaning log, using SHA-256.

569 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 820 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. Renewable Energy Planning Database (REPD) Clean storage · globalgrid2050 / automation/repd/clean.py lines 460–848
  2. Automation — Renewable Energy Planning Database (REPD) docs-config · globalgrid2050 / automation/repd/config.py lines 1–180

Renewable Energy Planning Database (REPD) Clean

A Python command-line tool in the automation folder of GlobalGrid2050 that hashes paths, builds log and verifies against official, covering official, REPD cleaned and cleaning log, using SHA-256.

storageglobalgrid2050 / automation/repd/clean.py · lines 460–848 of 848 (continued from section 819) · Entry point · pattern hash_paths (shared by 2 files)

What it does
It lists and searches official, REPD cleaned, cleaning log and the REPD register. Defines 21 functions or classes, including CleaningRejected, __init__, CleanOptions, CleanResult, sha256. 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 official.csv; Excel file official.xlsx; CSV file REPD_cleaned.csv; JSON file cleaning_log.json; command-line arguments. Out: JSON file cleaning_log.json.
Downstream impact
Used directly by 1 file: Conftest (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Clean (globalgrid2050); Test Date Rule (globalgrid2050).
What it achieves
It cleans options (`CleanOptions`), cleans result (`CleanResult`) and cleans text (`clean_text`). REPD cleaning step: official CSV + XLSX -> canonical cleaned CSV + complete cleaning log. Its code works with 0.0050001 MW. It accepts `--csv`, `--xlsx` and `--out`.
Why it matters
Checked by Conftest.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
Renewable Energy Planning Database (REPD) Date Rule (relative import), __future__, argparse, csv, hashlib, io, json, math, os
Used by
imported by Conftest (sys.path import)
Produces
CleaningRejected, CleanOptions, CleanResult, sha256, clean_text, parse_number, format_number, excel_text, hash_paths, manifest_diff, serialise, clean
Defines here
_valid_dmy, cross_check, build_log, verify_against_official, render_text_log, _generated_at, 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 automation/repd/clean.py:460-848 · blob a2cc23b0ee8f567a7c7f071eb864077cda66d530 · 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

    out_bytes = serialise(out_header, out_rows)
    observations = cross_check(names, c_header, out_rows, out_refs, x_by_ref, date_cols, num_date_columns)
    log = build_log(inputs=inputs, opts=opts, c_header=c_header, out_header=out_header,
                    header_changes=header_changes, removed_rows=removed_rows, changes=changes,
                    rule=rule, out_bytes=out_bytes, out_rows=out_rows, names=names,
                    na_preserved=na_preserved, ws_preserved=ws_preserved, stray_dates=stray_dates,
                    num_date_columns=num_date_columns, observations=observations, occurrences=occurrences)
    verification = verify_against_official(csv_raw, out_bytes, log)
    log["verification"] = verification
    if not verification["ok"]:
        raise CleaningRejected([f"self-verification failed: {verification['problems'][:10]}"])
    return CleanResult(header=out_header, rows=out_rows, log=log, csv_bytes=out_bytes, changes=changes)


def _valid_dmy(text: str) -> bool:
    try:
        datetime.strptime(text, "%d/%m/%Y")
        return True
    except ValueError:
        return False


# --------------------------------------------------------------------------
# Cross-check of the non-date columns against the workbook (report only)
# --------------------------------------------------------------------------
def cross_check(names, c_header, out_rows, out_refs, x_by_ref, date_cols, num_date_columns) -> dict:
    """Compare every non-date output cell with the workbook.  Reports, never changes."""
    per_column: dict[str, Counter] = defaultdict(Counter)
    cells: list[dict] = []
    for ref, row in zip(out_refs, out_rows):
        xrow = x_by_ref[ref]
        for i, name in enumerate(names):
            if name in date_cols:
                continue
            out = row[i]
            xc = xrow[i]
            if xc.is_date and isinstance(xc.value, datetime) and xc.value.date() < dr.EARLIEST_PLAUSIBLE:
                xt = format_number(float(to_excel(xc.value)))
            else:
                xt = excel_text(xc)
            a, b = _cmp_norm(out), _cmp_norm(xt)
            if a == b:
                continue
            na, nb = parse_number(a), parse_number(b)
            if na is not None and nb is not None and na == nb and "," in a:
                category = "numeric_equal_display_format"   # thousands separators / trailing zeros only
            elif na is not None and nb is not None and na == nb:
                category = "numeric_equal_text_differs"
            elif na is not None and nb is not None and abs(na - nb) <= NUMERIC_TOLERANCE:
                category = "numeric_rounded_in_csv"
            elif a.casefold() in dr.DEFAULT_BLANK_TOKENS and b == "":
                category = "csv_na_text_xlsx_blank"
            else:
                category = "text_differs"
            per_column[c_header[i]][category] += 1
            cells.append({"ref": ref, "column": c_header[i], "category": category,
                          "output_text": out, "xlsx_text": xt})
    totals = Counter()
    for c in per_column.values():
        totals.update(c)
    return {
        "description": ("Every non-date output cell compared with the workbook after whitespace collapse. "
                        "Differences are REPORTED ONLY; the official CSV text is kept (capacity excepted "
                        "when --capacity-source excel)."),
        "totals": dict(sorted(totals.items())),
        "by_column": {k: dict(sorted(v.items())) for k, v in sorted(per_column.items())},
        "cells": cells,
    }


# --------------------------------------------------------------------------
# Log
# --------------------------------------------------------------------------
def build_log(*, inputs, opts, c_header, out_header, header_changes, removed_rows, changes, rule,
              out_bytes, out_rows, names, na_preserved, ws_preserved, stray_dates, num_date_columns,
              observations, occurrences) -> dict:
    by_kind: dict[str, list[dict]] = {k: [] for k in ALL_KINDS}
    for h in header_changes:
        by_kind[K_HEADER].append(h)
    for r in removed_rows:
        by_kind[K_DUP].append(r)
    for c in changes:
        for k in c["kinds"]:
            by_kind[k].append(c)
    by_kind_column: dict[str, dict[str, int]] = {}
    for k in CELL_KINDS:
        cnt = Counter(c["column"] for c in by_kind[k])
        if cnt:
            by_kind_column[k] = dict(sorted(cnt.items()))
    return {
        "schema": LOG_SCHEMA,
        "tool": TOOL,
        "status": "CLEANED",
        "inputs": inputs,
        "options": {
            "capacity_source": opts.capacity_source,
            "whitespace": opts.whitespace,
            "normalise_headers": opts.normalise_headers,
            "required_date_columns": list(opts.required_date_columns),
            "sheet": opts.sheet,
            "as_of": opts.as_of.isoformat() if opts.as_of else None,
            "future_ok_columns": list(opts.future_ok_columns),
            "expected_csv_sha256": opts.expected_csv_sha256,
            "expected_xlsx_sha256": opts.expected_xlsx_sha256,
        },
        "policy": {
            "encoding_out": "utf-8 (no BOM)", "line_terminator": "\\n", "quoting": "QUOTE_MINIMAL",
            "column_order": "official CSV order",
            "dates": "typed Excel date wins; month-first CSV text only where the cell's number format is "
                     "explicitly month-first; strict dd/mm/yyyy; NA/N/A/whitespace blanked in date columns only",
            "duplicates": "byte-identical CSV records kept once (first); conflicting duplicates reject",
            "whitespace": ("edge runs containing tab/CR/LF removed; internal line-break runs -> one space; "
                           "plain-space edges, whitespace-only cells and text NA outside date columns kept")
            if opts.whitespace == "control" else
            ("edge runs containing tab/CR/LF removed; internal line-break runs -> one space; all other "
             "leading/trailing whitespace removed; whitespace-only cells blanked; text NA kept"),
            "capacity": "official CSV text" if opts.capacity_source == "csv" else
                        "workbook value (.15g) where within 0.0050001 MW of the CSV",
            "numbers_stored_as_dates": "workbook number restored where the CSV shows its 1900 date rendering",
        },
        "output": {
            "sha256": sha256(out_bytes), "bytes": len(out_bytes), "rows": len(out_rows),
            "columns": len(out_header), "header": out_header,
        },
        "official_header": c_header,
        "date_columns": rule.date_columns,
        "counts": {k: len(v) for k, v in by_kind.items()},
        "cells_changed_distinct": len(changes),
        "counts_by_kind_and_column": by_kind_column,
        "changes_by_kind": by_kind,
        "observations": {
            "duplicate_refs": {ref: nums for ref, nums in occurrences.items() if len(nums) > 1},
            "date_rule_totals": rule.summary()["rule_totals"],
            "date_rule_counts_by_column": rule.rule_counts,
            "date_blank_equivalent_counts": rule.blank_equivalent_counts,
            "date_plausibility_flags": rule.plausibility_flags,
            "number_stored_as_date_columns": dict(num_date_columns),
            "stray_excel_dates_left_unchanged": stray_dates,
            "na_text_preserved_outside_date_columns": dict(sorted(na_preserved.items())),
            "whitespace_only_cells_preserved_outside_date_columns": dict(sorted(ws_preserved.items())),
            "whitespace_only_cells_preserved_total": sum(ws_preserved.values()),
            "csv_vs_xlsx_non_date_columns": observations,
        },
    }


def verify_against_official(csv_raw: bytes, out_bytes: bytes, log: dict) -> dict:
    """Re-read both files independently and prove every difference is logged (and vice versa)."""
    problems: list[str] = []
    if out_bytes.startswith(b"\xef\xbb\xbf"):
        problems.append("output has a BOM")
    if b"\r" in out_bytes:  # LF terminators only; cell line breaks are replaced by the policy
        problems.append("output contains CR characters")
    try:
        out_text = out_bytes.decode("utf-8")
    except UnicodeDecodeError as exc:
        problems.append(f"output is not UTF-8: {exc}")
        return {"ok": False, "problems": problems}
    out = list(csv.reader(io.StringIO(out_text, newline=""), strict=True))
    official_header, official_rows, _ = dr.read_csv_table(csv_raw)
    out_header, out_rows = out[0], out[1:]

    removed = {r["csv_record"] for r in log["changes_by_kind"][K_DUP]}
    kept = [row for n, row in enumerate(official_rows, start=1) if n not in removed]
    if len(kept) != len(out_rows):
        problems.append(f"row count {len(out_rows)} != official {len(official_rows)} - removed {len(removed)}")
    logged_header = {h["column_index"]: h for h in log["changes_by_kind"][K_HEADER]}
    for i, (a, b) in enumerate(zip(official_header, out_header)):
        if a != b and (i not in logged_header or logged_header[i]["after"] != b):
            problems.append(f"unlogged header change at {i}: {a!r} -> {b!r}")
    if len(out_header) != len(official_header):
        problems.append("column count changed")

    logged: dict[tuple[int, int], dict] = {}
    for kind in CELL_KINDS:
        for c in log["changes_by_kind"][kind]:
            logged[(c["out_row"], c["column_index"])] = c
    found = 0
    for r_no, (a_row, b_row) in enumerate(zip(kept, out_rows), start=1):
        for i, (a, b) in enumerate(zip(a_row, b_row)):
            if a == b:
                if (r_no, i) in logged:
                    problems.append(f"logged change has no effect: row {r_no} col {i}")
                continue
            found += 1
            entry = logged.get((r_no, i))
            if entry is None:
                problems.append(f"UNLOGGED difference row {r_no} col {official_header[i]!r}: {a!r} -> {b!r}")
            elif entry["before"] != a or entry["after"] != b:
                problems.append(f"log before/after mismatch row {r_no} col {i}")
    cells = len(out_rows) * len(out_header)
    return {
        "ok": not problems and found == len(logged),
        "method": "output re-read with csv module (utf-8, strict); official re-read independently; "
                  "rows aligned after removing the logged duplicate records; every cell compared",
        "cells_compared": cells,
        "cells_differing_from_official": found,
        "cells_logged": len(logged),
        "rows_removed_logged": len(removed),
        "unexplained_differences": sum("UNLOGGED" in p for p in problems),
        "problems": problems[:50],
    }


def render_text_log(log: dict) -> str:
    lines: list[str] = []
    w = lines.append
    w("REPD CLEANING LOG")
    w("=================")
    w(f"status: {log['status']}")
    w(f"tool: {log['tool']}   schema: {log['schema']}   generated_at: {log.get('generated_at', '')}")
    for label in ("csv", "xlsx"):
        i = log["inputs"][label]
        extra = (f" encoding={i.get('encoding')} records={i.get('records')}" if label == "csv"
                 else f" sheet={i.get('sheet')} records={i.get('records')}")
        w(f"input {label}: {i['name']} bytes={i['bytes']} sha256={i['sha256']}{extra}")
    if log["status"] != "CLEANED":
        w("")
        w("REJECTED:")
        for r in log.get("reasons", []):
            w(f"  - {r}")
        return "\n".join(lines) + "\n"
    o = log["output"]
    w(f"output: {log.get('output_file', '')} bytes={o['bytes']} rows={o['rows']} columns={o['columns']} "
      f"sha256={o['sha256']} (utf-8, no BOM, LF)")
    w(f"options: {json.dumps(log['options'], sort_keys=True)}")
    w(f"date columns ({len(log['date_columns'])}): {', '.join(log['date_columns'])}")
    w("")
    w("CHANGE COUNTS")
    for k, n in log["counts"].items():
        w(f"  {k:<40} {n:>6}")
    w(f"  {'distinct cells changed':<40} {log['cells_changed_distinct']:>6}")
    v = log["verification"]
    w("")
    w("SELF-VERIFICATION (output vs official CSV, cell by cell)")
    w(f"  ok={v['ok']} cells_compared={v['cells_compared']} differing={v['cells_differing_from_official']} "
      f"logged={v['cells_logged']} unexplained={v['unexplained_differences']} rows_removed={v['rows_removed_logged']}")
    for p in v["problems"]:
        w(f"  PROBLEM: {p}")
    w("")
    w("COUNTS BY KIND AND COLUMN")
    for k, cols in log["counts_by_kind_and_column"].items():
        w(f"  {k}")
        for c, n in cols.items():
            w(f"      {c!r}: {n}")
    obs = log["observations"]
    w("")
    w("OBSERVATIONS (not changes)")
    w(f"  duplicate refs (CSV data record numbers): {obs['duplicate_refs']}")
    w(f"  date rule totals: {obs['date_rule_totals']}")
    w(f"  date plausibility flags (kept, not changed): {len(obs['date_plausibility_flags'])}")
    for f in obs["date_plausibility_flags"]:
        w(f"      ref {f['ref']} {f['column']!r} {f['value']} {f['flag']}")
    w(f"  numbers stored as dates, by column: {obs['number_stored_as_date_columns']}")
    w(f"  stray Excel dates left unchanged: {len(obs['stray_excel_dates_left_unchanged'])}")
    w(f"  text NA preserved outside date columns: {obs['na_text_preserved_outside_date_columns']}")
    w(f"  whitespace-only cells preserved outside date columns: {obs['whitespace_only_cells_preserved_total']} "
      f"{obs['whitespace_only_cells_preserved_outside_date_columns']}")
    xc = obs["csv_vs_xlsx_non_date_columns"]
    w(f"  CSV vs XLSX, non-date columns (report only): {xc['totals']}")
    for col, cnt in xc["by_column"].items():
        w(f"      {col!r}: {cnt}")
    for c in xc["cells"]:
        if c["category"] not in ("numeric_rounded_in_csv", "numeric_equal_display_format"):
            w(f"      ref {c['ref']} {c['column']!r} [{c['category']}] csv={c['output_text']!r} xlsx={c['xlsx_text']!r}")
    w("      (numeric_rounded_in_csv and numeric_equal_display_format cells are listed in cleaning_log.json only)")
    w("")
    w("EVERY CHANGE")
    for k in ALL_KINDS:
        items = log["changes_by_kind"][k]
        w(f"-- {k} ({len(items)})")
        for c in items:
            if k == K_DUP:
                w(f"   ref {c['ref']}: CSV data record {c['csv_record']} removed (identical to record {c['kept_csv_record']})")
            elif k == K_HEADER:
                w(f"   column {c['column_index']}: {c['before']!r} -> {c['after']!r}")
            else:
                w(f"   ref {c['ref']} row {c['out_row']} {c['column']!r}: {c['before']!r} -> {c['after']!r}")
    return "\n".join(lines) + "\n"


# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def _generated_at(explicit: str | None) -> str:
    if explicit:
        return explicit
    epoch = os.environ.get("SOURCE_DATE_EPOCH")
    if epoch and epoch.strip().isdigit():
        return datetime.fromtimestamp(int(epoch), timezone.utc).isoformat()
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Clean an official REPD CSV + XLSX pair.")
    parser.add_argument("--csv", required=True, type=Path)
    parser.add_argument("--xlsx", required=True, type=Path)
    parser.add_argument("--out", required=True, type=Path, help="output directory (created; never an input dir)")
    parser.add_argument("--output-name", default="REPD_cleaned.csv")
    parser.add_argument("--capacity-source", choices=("csv", "excel"), default="csv")
    parser.add_argument("--whitespace", choices=("control", "all"), default="control",
                        help="control: only tab/CR/LF edge runs and line breaks (default); all: also trim "
                             "spaces/NBSP at cell edges and blank whitespace-only cells")
    parser.add_argument("--normalise-headers", action="store_true")
    parser.add_argument("--sheet")
    parser.add_argument("--as-of", help="yyyy-mm-dd; later dates are flagged, not changed")
    parser.add_argument("--future-ok-column", action="append", default=None,
                        help="replace the default future-ok date columns (repeatable)")
    parser.add_argument("--require-date-column", action="append", default=None,
                        help="replace the default 16 required date columns (repeatable)")
    parser.add_argument("--expected-csv-sha256")
    parser.add_argument("--expected-xlsx-sha256")
    parser.add_argument("--protect", action="append", default=[], type=Path,
                        help="file or directory that must be byte-identical after the run (repeatable)")
    parser.add_argument("--overwrite", action="store_true", help="allow replacing existing outputs in --out")
    parser.add_argument("--generated-at", help="timestamp to record (default: SOURCE_DATE_EPOCH or now)")
    args = parser.parse_args(argv)

    out_dir = args.out.resolve()
    targets = [out_dir / args.output_name, out_dir / "cleaning_log.json", out_dir / "CLEANING-LOG.txt"]
    protected = [args.csv, args.xlsx, *args.protect]
    # --out may not hold, sit inside, or be the folder of any input or protected path
    fences = [Path(p).resolve() for p in args.protect] + [args.csv.resolve().parent, args.xlsx.resolve().parent]
    for rp in fences:
        if rp == out_dir or out_dir in rp.parents or rp in out_dir.parents:
            print(f"REFUSED: --out {out_dir} overlaps protected path {rp}", file=sys.stderr)
            return 2
    existing = [str(t) for t in targets if t.exists()]
    if existing and not args.overwrite:
        print(f"REFUSED: outputs already exist (use --overwrite): {existing}", file=sys.stderr)
        return 2
    before = hash_paths(protected)

    opts = CleanOptions(
        capacity_source=args.capacity_source, whitespace=args.whitespace, normalise_headers=args.normalise_headers,
        required_date_columns=tuple(args.require_date_column) if args.require_date_column
        else DEFAULT_REQUIRED_DATE_COLUMNS,
        future_ok_columns=tuple(args.future_ok_column) if args.future_ok_column is not None
        else DEFAULT_FUTURE_OK_COLUMNS,
        sheet=args.sheet, as_of=date.fromisoformat(args.as_of) if args.as_of else None,
        expected_csv_sha256=args.expected_csv_sha256, expected_xlsx_sha256=args.expected_xlsx_sha256,
    )
    csv_raw, xlsx_raw = args.csv.read_bytes(), args.xlsx.read_bytes()
    out_dir.mkdir(parents=True, exist_ok=True)
    generated_at = _generated_at(args.generated_at)
    try:
        result = clean(csv_raw, xlsx_raw, opts, csv_name=args.csv.name, xlsx_name=args.xlsx.name)
        log = result.log
        code = 0
    except CleaningRejected as exc:
        result = None
        log = {"schema": LOG_SCHEMA, "tool": TOOL, "status": "REJECTED", "reasons": exc.reasons,
               "inputs": {"csv": {"name": args.csv.name, "bytes": len(csv_raw), "sha256": sha256(csv_raw)},
                          "xlsx": {"name": args.xlsx.name, "bytes": len(xlsx_raw), "sha256": sha256(xlsx_raw)}}}
        code = 1
    log["generated_at"] = generated_at
    if result is not None:
        (out_dir / args.output_name).write_bytes(result.csv_bytes)
        log["output_file"] = args.output_name
    elif (out_dir / args.output_name).exists():
        (out_dir / args.output_name).unlink()  # never leave a stale cleaned file beside a rejection

    after = hash_paths(protected)
    diffs = manifest_diff(before, after)
    log["hash_manifest"] = {"protected_paths": [str(Path(p).resolve()) for p in protected],
                            "before": before, "after": after, "differences": diffs, "ok": not diffs}
    if diffs:
        log["status"] = "FAILED_PROTECTED_FILE_CHANGED"
        code = 3
    (out_dir / "cleaning_log.json").write_text(json.dumps(log, indent=1, ensure_ascii=False) + "\n",
                                               encoding="utf-8")
    text = render_text_log(log)
    text += "\nHASH MANIFEST (files this step must not change)\n"
    for path, digest in before.items():
        text += f"  {digest}  {path}  {'UNCHANGED' if after.get(path) == digest else 'CHANGED'}\n"
    (out_dir / "CLEANING-LOG.txt").write_text(text, encoding="utf-8")
    if code == 0:
        print(f"CLEANED rows={log['output']['rows']} sha256={log['output']['sha256']} "
              f"changes={log['cells_changed_distinct']} counts={json.dumps(log['counts'])}")
    elif code == 1:
        print("REJECTED: " + "; ".join(log["reasons"]), file=sys.stderr)
    else:
        print(f"FAILED: protected files changed: {diffs}", file=sys.stderr)
    return code


if __name__ == "__main__":
    raise SystemExit(main())

Automation — Renewable Energy Planning Database (REPD)

A Python module in GlobalGrid2050 that reads REPD publication q3, REPD q2 jul and the REPD register, using SHA-256.

docs-configglobalgrid2050 / automation/repd/config.py · lines 1–180 of 180

What it does
It loads REPD publication q3, REPD q2 jul and the REPD register. Defines 14 functions or classes, including DescriptorError, quarter_from_filename, quarter_from_label, release_id_for, quarter_text. Uses libraries __future__, json, re, dataclasses, pathlib. 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_Q3_2026.csv; CSV file repd-q2-jul-2025.csv.
Downstream impact
Used directly by 5 files: Renewable Energy Planning Database (REPD) Detect (globalgrid2050); Renewable Energy Planning Database (REPD) Fetch (globalgrid2050); Renewable Energy Planning Database (REPD) Monthly (globalgrid2050); Test Detect Fetch (globalgrid2050); and 1 more. Reached from 2 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050).
What it achieves
It is built from the descriptor error class (`DescriptorError`), the quarter from filename helper (`quarter_from_filename`) and the quarter from label helper (`quarter_from_label`). REPD release descriptor: one JSON file per quarterly DESNZ publication.
Why it matters
Imported by Renewable Energy Planning Database (REPD) Detect, Renewable Energy Planning Database (REPD) Fetch and Renewable Energy Planning Database (REPD) Monthly. Checked by 2 tests, including Test Detect Fetch.
Application
globalgrid2050 · automation/repd · Python module
Uses
__future__, json, re, dataclasses, pathlib, typing
Used by
imported by Renewable Energy Planning Database (REPD) Detect (relative import), imported by Renewable Energy Planning Database (REPD) Fetch (relative import), imported by Renewable Energy Planning Database (REPD) Monthly (import), imported by Test Detect Fetch (import), imported by Test Monthly (import)
Produces
DescriptorError, quarter_from_filename, quarter_from_label, release_id_for, quarter_text, Expected, ReleaseDescriptor, load, dump, load_all, known_hashes
Defines here
DescriptorError, quarter_from_filename, quarter_from_label, release_id_for, quarter_text, Expected, ReleaseDescriptor, validate, to_dict, from_dict, load, dump, load_all, known_hashes
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/config.py:1-180 · blob d03b2d6f65f331d60be6009a5ca47ac81cb232c1 · 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
"""REPD release descriptor: one JSON file per quarterly DESNZ publication.

A descriptor replaces the July values that were hard-coded in
scripts/repd_sources_v6.py (CSV_URL, XLSX_URL, PUBLICATION_DATE, DATASET_TITLE,
EXPECTED_*) and scripts/repd_updater.py (CURRENT_Q2_2026_*).

Descriptors live in automation/repd/releases/<release_id>.json, e.g. 2026q3.json.
Every descriptor's pinned sha256 values form a registry of "bytes that belong to a
known release", which fetch.py uses to refuse labelling one quarter's bytes as
another (the GOV.UK replaced-attachment redirect trap).

Standard library only.
"""
from __future__ import annotations

import json
import re
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Optional

SCHEMA = "globalgrid2050.repd-release-descriptor.v1"
SOURCE_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
CONTENT_API = "https://www.gov.uk/api/content/government/publications/renewable-energy-planning-database-quarterly-extract"
RELEASES_DIR = Path(__file__).resolve().parent / "releases"

MONTHS = {m: i for i, m in enumerate(
    ["january", "february", "march", "april", "may", "june", "july", "august",
     "september", "october", "november", "december"], start=1)}
# DESNZ convention: the release named after a month covers the quarter that ended
# just before it (July 2026 = Q2 2026, October 2026 = Q3 2026, January 2027 = Q4 2026).
RELEASE_MONTH_TO_QUARTER = {1: 4, 4: 1, 7: 2, 10: 3}
_SHA = re.compile(r"^[0-9a-f]{64}$")


class DescriptorError(ValueError):
    pass


def quarter_from_filename(name: str) -> Optional[tuple[int, int]]:
    """'REPD_Publication_Q3_2026.csv' -> (2026, 3); 'repd-q2-jul-2025.csv' -> (2025, 2)."""
    base = name.rsplit("/", 1)[-1].lower()
    m = re.search(r"q([1-4])[^0-9]{0,8}?(20\d\d)", base)
    if m:
        return int(m.group(2)), int(m.group(1))
    m = re.search(r"(20\d\d)[^0-9]{0,3}q([1-4])", base)
    if m:
        return int(m.group(1)), int(m.group(2))
    return None


def quarter_from_label(label: str) -> Optional[tuple[int, int]]:
    """'October 2026' / 'REPD: July 2026 (CSV)' -> (2026, 3) / (2026, 2)."""
    m = re.search(r"(january|april|july|october)\s+(20\d\d)", label or "", re.I)
    if not m:
        return None
    month, year = MONTHS[m.group(1).lower()], int(m.group(2))
    q = RELEASE_MONTH_TO_QUARTER[month]
    return (year - 1, q) if q == 4 else (year, q)


def release_id_for(year: int, q: int) -> str:
    return f"{year}q{q}"


def quarter_text(year: int, q: int) -> str:
    return f"Q{q} {year}"


@dataclass
class Expected:
    csv_sha256: Optional[str] = None
    xlsx_sha256: Optional[str] = None
    csv_bytes: Optional[int] = None
    xlsx_bytes: Optional[int] = None
    csv_rows: Optional[int] = None
    unique_refs: Optional[int] = None
    duplicate_refs: list = field(default_factory=list)
    solar_gt_1mw: Optional[int] = None
    bess_gt_100mw: Optional[int] = None


@dataclass
class ReleaseDescriptor:
    release_id: str               # "2026q3" (used as file-name suffix)
    label: str                    # "October 2026"
    quarter: str                  # "Q3 2026"
    csv_url: str
    xlsx_url: str
    page_last_updated: Optional[str] = None   # YYYY-MM-DD as shown on the GOV.UK page
    govuk_public_updated_at: Optional[str] = None
    dataset_title: Optional[str] = None
    source_page: str = SOURCE_PAGE
    previous_release_id: Optional[str] = None
    baseline_path: Optional[str] = None       # previous-release cleaned file, for row-floor and diff
    expected: Expected = field(default_factory=Expected)
    provenance: list = field(default_factory=list)
    schema: str = SCHEMA

    # ---- validation -------------------------------------------------------
    def validate(self) -> "ReleaseDescriptor":
        problems = []
        m = re.fullmatch(r"(20\d\d)q([1-4])", self.release_id or "")
        if not m:
            problems.append(f"release_id {self.release_id!r} is not like 2026q3")
        else:
            yq = (int(m.group(1)), int(m.group(2)))
            if self.quarter != quarter_text(*yq):
                problems.append(f"quarter {self.quarter!r} != {quarter_text(*yq)!r} implied by release_id")
            if quarter_from_label(self.label) != yq:
                problems.append(f"label {self.label!r} does not name the release month of {self.quarter}")
            for role in ("csv", "xlsx"):
                url = getattr(self, f"{role}_url")
                if not url.startswith("https://"):
                    problems.append(f"{role}_url must be https: {url!r}")
                if not url.lower().endswith("." + role):
                    problems.append(f"{role}_url does not end in .{role}: {url!r}")
                fq = quarter_from_filename(url)
                if fq is not None and fq != yq:
                    problems.append(f"{role}_url file name names {quarter_text(*fq)}, descriptor says {self.quarter}")
        for role in ("csv", "xlsx"):
            sha = getattr(self.expected, f"{role}_sha256")
            if sha is not None and not _SHA.match(sha):
                problems.append(f"expected.{role}_sha256 is not 64 lowercase hex chars")
        if self.page_last_updated and not re.fullmatch(r"\d{4}-\d\d-\d\d", self.page_last_updated):
            problems.append("page_last_updated must be YYYY-MM-DD")
        if problems:
            raise DescriptorError("invalid release descriptor: " + "; ".join(problems))
        return self

    # ---- (de)serialisation ------------------------------------------------
    def to_dict(self) -> dict:
        d = asdict(self)
        return {"schema": d.pop("schema"), **d}

    @classmethod
    def from_dict(cls, d: dict) -> "ReleaseDescriptor":
        d = dict(d)
        if d.get("schema", SCHEMA) != SCHEMA:
            raise DescriptorError(f"unknown descriptor schema {d.get('schema')!r}")
        exp = Expected(**(d.pop("expected", None) or {}))
        known = set(cls.__dataclass_fields__)
        unknown = set(d) - known
        if unknown:
            raise DescriptorError(f"unknown descriptor fields: {sorted(unknown)}")
        return cls(expected=exp, **d).validate()


def load(path) -> ReleaseDescriptor:
    return ReleaseDescriptor.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))


def dump(desc: ReleaseDescriptor, path) -> None:
    desc.validate()
    Path(path).write_text(json.dumps(desc.to_dict(), indent=2) + "\n", encoding="utf-8")


def load_all(directory=RELEASES_DIR) -> dict[str, ReleaseDescriptor]:
    out = {}
    for p in sorted(Path(directory).glob("*.json")):
        d = load(p)
        if d.release_id in out:
            raise DescriptorError(f"duplicate release_id {d.release_id} in {directory}")
        out[d.release_id] = d
    return out


def known_hashes(descriptors) -> dict[str, tuple[str, str]]:
    """sha256 -> (release_id, role) over every pinned hash. Fails if one hash is
    pinned to two different releases (that would make labelling ambiguous)."""
    reg: dict[str, tuple[str, str]] = {}
    for d in (descriptors.values() if isinstance(descriptors, dict) else descriptors):
        for role in ("csv", "xlsx"):
            sha = getattr(d.expected, f"{role}_sha256")
            if not sha:
                continue
            if sha in reg and reg[sha][0] != d.release_id:
                raise DescriptorError(f"sha256 {sha[:12]} pinned to both {reg[sha][0]} and {d.release_id}")
            reg[sha] = (d.release_id, role)
    return reg