GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9

Renewable Energy Planning Database (REPD) Build News and 2 more files

A Python command-line tool in the automation folder of GlobalGrid2050 that reads project spine and the REPD register, using SHA-256.

605 lines of Python and JavaScript from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 818 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. View interaction · globalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/view.mjs lines 1–69
  2. Renewable Energy Planning Database (REPD) Build News storage · globalgrid2050 / automation/repd/build_news.py lines 1–290
  3. Renewable Energy Planning Database (REPD) Build Root energy-data · globalgrid2050 / automation/repd/build_root.py lines 1–246

View

A JavaScript module in the price daily ui folder of GlobalGrid2050 that draws sources.

interactionglobalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/view.mjs · lines 1–69 of 69 · Not reached from any entry point (candidate for review) · pattern unavailable (shared by 6 files)

What it does
It draws sources. Defines 8 functions or classes, including number, element, anchor, mountDailyPrices, clearResults. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file index.json; JSON file sources.json.
What it achieves
It is built from the mount daily prices helper (`mountDailyPrices`), the clear results helper (`clearResults`) and the unavailable step (`unavailable`). Defines `number`, `element`, `anchor` and 5 more. It responds to change events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9 · JavaScript module
Uses
Model (import), Canvas (import)
Used by
none found
Produces
mountDailyPrices
Defines here
number, element, anchor, mountDailyPrices, clearResults, unavailable, paint, load
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/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/view.mjs:1-69 · blob c312f2380670d583b09c6f3b1bcc197d3902b983 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
import {SOURCE,createStore,summarise,trailingWindow,dateMs,dateAt} from './model.mjs';
import {drawDaily} from './canvas.mjs';
const MOUNTS=new WeakMap();
const number=n=>n.toLocaleString('en-GB'),money=n=>n===null?'Not available':'£'+n.toLocaleString('en-GB',{minimumFractionDigits:2,maximumFractionDigits:2})+'/MWh';
const element=(doc,tag,text,cls)=>{const n=doc.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
function anchor(doc,label,url){const a=element(doc,'a',label);a.href=url;a.target='_blank';a.rel='noopener noreferrer';return a;}
export function mountDailyPrices(host,{transport=fetch}={}){
  if(host?.nodeType!==1)throw Error('Daily price host required');if(MOUNTS.has(host))return MOUNTS.get(host);
  const doc=host.ownerDocument,root=element(doc,'section',undefined,'pn-daily-prices');root.setAttribute('aria-label','Historical daily system-sell prices');
  root.append(element(doc,'h3','Historical electricity system-sell prices'));
  const sourceLine=element(doc,'p','Loading dated source data…','pnd-source');root.append(sourceLine);
  const tools=element(doc,'div',undefined,'pnd-tools'),year=element(doc,'select'),period=element(doc,'select'),end=element(doc,'input');end.type='date';
  year.setAttribute('aria-label','Source year');period.setAttribute('aria-label','Daily window');end.setAttribute('aria-label','Window end date');
  for(const [value,label] of [['30','30 days'],['90','90 days'],['365','365 days'],['year','Selected year']]){const option=element(doc,'option',label);option.value=value;period.append(option);}
  for(const [label,input] of [['Year',year],['Window',period],['End date',end]]){const item=element(doc,'label',label);item.append(input);tools.append(item);}root.append(tools);
  const status=element(doc,'p','Loading…','pnd-status');status.setAttribute('role','status');status.setAttribute('aria-live','polite');root.append(status);
  const canvas=element(doc,'canvas');canvas.setAttribute('role','img');canvas.setAttribute('aria-label','Daily high, available mean and low system-sell prices; gaps and partial source days retained.');root.append(canvas);
  const stats=element(doc,'dl',undefined,'pnd-stats');root.append(stats);
  const coverage=element(doc,'p',undefined,'pnd-coverage'),quality=element(doc,'p',undefined,'pnd-quality');root.append(coverage,quality);
  root.append(element(doc,'p','Historical observations only. Daily groups use source-declared GB settlement dates. Complete source-day coverage does not certify stored UTC alignment.','pnd-note'));
  const details=element(doc,'details'),summary=element(doc,'summary','Source and daily observations');details.append(summary);
  const links=element(doc,'p');links.append(anchor(doc,'Pinned data index',SOURCE.base+'index.json'),doc.createTextNode(' · '),anchor(doc,'Source file hashes',SOURCE.base+'sources.json'),doc.createTextNode(' · '),anchor(doc,'Data-owner method','https://github.com/'+SOURCE.repository+'/blob/'+SOURCE.commit+'/derived/PRICE_DAILY_BROWSER.md'));details.append(links);
  details.append(element(doc,'p','Elexon system-sell prices, GBP/MWh. Daily means use available prices; the displayed window mean is the unweighted mean of available daily means. Partial days can affect that mean. No market-index merge, interpolation, forecast or realtime quote.'));
  const tableWrap=element(doc,'div',undefined,'pnd-table'),table=element(doc,'table'),thead=element(doc,'thead'),header=element(doc,'tr');
  for(const label of ['Source date','Available mean £/MWh','High £/MWh','Low £/MWh','Priced / expected','Source-day coverage','UTC disagreements']){const th=element(doc,'th',label);th.scope='col';header.append(th);}thead.append(header);const tbody=element(doc,'tbody');table.append(thead,tbody);tableWrap.append(table);details.append(tableWrap);root.append(details);
  host.append(root);tools.hidden=true;canvas.hidden=true;stats.hidden=true;coverage.hidden=true;quality.hidden=true;
  let store=null,closed=false,generation=0,current=null,resizeFrame=null;
  function clearResults(){
    canvas.hidden=true;stats.hidden=true;coverage.hidden=true;quality.hidden=true;current=null;
    stats.replaceChildren();tbody.replaceChildren();coverage.textContent='';quality.textContent='';delete canvas.dataset.series;
  }
  function unavailable(message){clearResults();root.dataset.state='unavailable';status.textContent=message;}
  function paint(result){
    if(closed)return;current=result;const s=summarise(result.rows);canvas.hidden=false;stats.hidden=false;coverage.hidden=false;quality.hidden=false;
    const receipt=drawDaily(canvas,result);canvas.dataset.series=JSON.stringify(receipt);
    status.textContent=result.start+' to '+result.end+' · '+number(s.calendarDays)+' calendar days';root.dataset.state='available';
    stats.replaceChildren();for(const [label,value] of [['High observed',money(s.high)],['Mean of available daily means',money(s.dailyMean)],['Low observed',money(s.low)]]){const block=element(doc,'div');block.append(element(doc,'dt',label),element(doc,'dd',value));stats.append(block);}
    coverage.textContent=number(s.completeDays)+' complete source days · '+number(s.partialDays)+' partial · '+number(s.missingDays)+' missing · '+number(s.priced)+' priced / '+number(s.expected)+' expected periods ('+number(s.observed)+' observed).';
    quality.textContent='Stored UTC disagreements: '+number(s.clockMismatches)+' in this window; '+number(store.index.utc_alignment_mismatches)+' in the full source snapshot. History is retained without timestamp repair.';
    tbody.replaceChildren();for(const row of result.rows){const tr=element(doc,'tr');for(const value of [row.date,row.mean_available_gbp_per_mwh,row.maximum_observed_gbp_per_mwh,row.minimum_observed_gbp_per_mwh,row.priced_periods+' / '+row.expected_periods,row.coverage_status,row.utc_alignment_mismatches])tr.append(element(doc,'td',value===null?'Not available':String(value)));tbody.append(tr);}
  }
  async function load(){
    if(!store||closed)return;const token=++generation;root.dataset.state='loading';status.textContent='Loading selected source days…';
    // Hide the previous window while another window is loading or fails.
    clearResults();
    try{
      const last=store.index.last_date,first=store.index.first_date;
      const boundedEnd=dateAt(Math.min(dateMs(last),Math.max(dateMs(first),dateMs(end.value))));end.value=boundedEnd;
      let range;
      if(period.value==='year'){const y=Number(year.value);range={start:dateAt(Math.max(dateMs(first),Date.UTC(y,0,1))),end:dateAt(Math.min(dateMs(last),Date.UTC(y+1,0,1)-86400000))};end.value=range.end;}
      else{range=trailingWindow(boundedEnd,Number(period.value),first);year.value=boundedEnd.slice(0,4);}
      const result=await store.window(range.start,range.end);if(!closed&&token===generation)paint(result);
    }catch{if(!closed&&token===generation)unavailable('Selected daily price data unavailable. Inspect the pinned source links or select another window.');}
  }
  year.addEventListener('change',()=>{period.value='year';void load();});period.addEventListener('change',()=>void load());end.addEventListener('change',()=>{if(period.value==='year')period.value='30';void load();});
  const resize=new ResizeObserver(()=>{if(!current||closed)return;cancelAnimationFrame(resizeFrame);resizeFrame=requestAnimationFrame(()=>{
    if(current&&!closed)try{drawDaily(canvas,current);}catch{unavailable('Daily price graph unavailable. Select another window to retry.');}
  });});resize.observe(root);
  const controller={ready:null,disconnect(){if(closed)return;closed=true;generation++;resize.disconnect();cancelAnimationFrame(resizeFrame);root.remove();if(MOUNTS.get(host)===controller)MOUNTS.delete(host);}};
  MOUNTS.set(host,controller);
  controller.ready=(async()=>{
    try{
      store=await createStore(transport);if(closed)return;const index=store.index;
      sourceLine.textContent='Latest source date: '+index.last_date+' · historical Elexon system-sell prices · GBP/MWh';
      for(const part of [...index.parts].reverse()){const option=element(doc,'option',String(part.year));option.value=String(part.year);year.append(option);}
      year.value=index.last_date.slice(0,4);end.min=index.first_date;end.max=index.last_date;end.value=index.last_date;tools.hidden=false;await load();
    }catch{if(!closed){sourceLine.textContent='Historical system-sell source unavailable.';unavailable('Daily price data unavailable. The original electricity workspace remains separate.');}}
  })();return controller;
}

Renewable Energy Planning Database (REPD) Build News

A Python command-line tool in the automation folder of GlobalGrid2050 that reads project spine and the REPD register, using SHA-256.

storageglobalgrid2050 / automation/repd/build_news.py · lines 1–290 of 290 · Entry point · pattern hash_tree (shared by 3 files)

What it does
It loads project spine and the REPD register. Defines 7 functions or classes, including sha256_file, hash_tree, replace_once, set_json_scalar, build_identity. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; 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: JSON file project-spine.v7.2.json; JSON file release.v9.1.json; JSON file build_manifest.json; JSON file release.v9.5.1.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It hashes tree (`hash_tree`), replaces once (`replace_once`) and sets JSON scalar (`set_json_scalar`). Build a Pipeline News release-folder candidate for a new REPD quarter. It accepts `--repo`, `--parent` and `--release`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, hashlib, json, os, re, shutil, subprocess
Used by
none found
Produces
sha256_file, hash_tree, replace_once, set_json_scalar, build_identity, run, main
Defines here
sha256_file, hash_tree, replace_once, set_json_scalar, build_identity, run, 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/build_news.py:1-290 · blob a467499a35115925dad96cfba8fdcf4f8c99ff3e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build a Pipeline News release-folder candidate for a new REPD quarter.

This is a thin driver around the EXISTING builders; it writes no new data logic.

  1. copy the parent release folder (default: the operative 202609082224) to a NEW
     folder; refuse if it exists (never rebuild a release in place);
  2. identity fixture: the repo's own scripts/build_project_identity_v6.py
     (read_official_rows + build_registry, unchanged) run on a reconciled
     canonical CSV (V6 canonical format), written to a NEW fixture path;
  3. coordinate fixture: the release's own scripts/data/build_v7_2_spine.py
     --repd-xlsx, via a NEW contract whose v7.2 outputs go to a scratch directory
     outside the repo (it would otherwise write into uk_renewables_pipeline/v7);
  4. spine: the release's own scripts/data/build_v9_1_spine.py with ONE line
     changed (V9 = the release folder instead of uk_renewables_pipeline/v9), so
     contract and output are the new folder's own;
  5. contracts release.v9.1.json and release.v9.5.1.json: dataset label, fixture
     paths/hashes, workbook hash and `expected` values (from the builder's own
     acceptance-mismatch message, only with --accept-expected);
  6. hash manifest: sha256 of every file under uk_renewables_pipeline/ and dist/
     outside the new folder before and after; any difference fails the run.

Text-level edits (index.html wording, runner, CHANGES.md) are done by
--release-text-edits JSON (list of {path, old, new}); each `old` must occur once.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path

SPINE_LINE_OLD = 'V9 = ROOT / "uk_renewables_pipeline/v9"\n'
SPINE_LINE_NEW = 'V9 = Path(__file__).resolve().parents[2]  # this release folder, never uk_renewables_pipeline/v9\n'


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def hash_tree(root: Path, subdirs: list[str], exclude: Path | None) -> dict[str, str]:
    out: dict[str, str] = {}
    for sub in subdirs:
        base = root / sub
        if not base.exists():
            continue
        for p in sorted(base.rglob("*")):
            if not p.is_file() or ".git" in p.relative_to(root).parts:
                continue
            if exclude is not None and (p == exclude or exclude in p.parents):
                continue
            out[p.relative_to(root).as_posix()] = sha256_file(p)
    return out


def replace_once(text: str, old: str, new: str, label: str) -> str:
    n = text.count(old)
    if n != 1:
        raise SystemExit(f"FAIL: expected exactly one occurrence in {label} of {old!r}, found {n}")
    return text.replace(old, new)


def set_json_scalar(text: str, block: str, key: str, value, label: str) -> str:
    """Replace `"key": <scalar>` inside the first `"block": {...}` object, keeping layout."""
    m = re.search(r'"%s"\s*:\s*\{' % re.escape(block), text)
    if not m:
        raise SystemExit(f"FAIL: {label}: block {block!r} not found")
    depth, i = 0, m.end() - 1
    while True:
        if text[i] == "{":
            depth += 1
        elif text[i] == "}":
            depth -= 1
            if depth == 0:
                break
        i += 1
    body = text[m.end():i]
    pat = re.compile(r'("%s"\s*:\s*)("(?:[^"\\]|\\.)*"|-?[0-9.eE+-]+|true|false|null)' % re.escape(key))
    if len(pat.findall(body)) != 1:
        raise SystemExit(f"FAIL: {label}: key {block}.{key} not found exactly once")
    body = pat.sub(lambda mm: mm.group(1) + json.dumps(value), body)
    return text[:m.end()] + body + text[i:]


def build_identity(repo: Path, canonical_csv: Path, manifest: dict, out: Path) -> dict:
    sys.path.insert(0, str(repo / "scripts"))
    import build_project_identity_v6 as ident  # existing logic, unchanged

    rows, headers, relationship_columns = ident.read_official_rows(canonical_csv)
    registry = ident.build_registry(rows, manifest, manifest["source_url"])
    registry["detected_header_count"] = len(headers)
    registry["detected_relationship_columns"] = relationship_columns
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(registry, indent=2), encoding="utf-8")  # same serialisation as ident.main()
    return registry


def run(cmd: list[str]) -> subprocess.CompletedProcess:
    # no bytecode: the repo tracks some __pycache__ files and nothing here may add or remove any
    return subprocess.run(cmd, capture_output=True, text=True, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"})


def main() -> None:
    sys.dont_write_bytecode = True
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--repo", type=Path, required=True, help="plain copy of the repository root")
    ap.add_argument("--parent", default="202609082224")
    ap.add_argument("--release", required=True, help="new release folder id, e.g. 202611132345")
    ap.add_argument("--quarter", required=True, help="file-name suffix, e.g. 2026q3")
    ap.add_argument("--dataset", required=True, help='e.g. "DESNZ Renewable Energy Planning Database Q3 2026"')
    ap.add_argument("--canonical-csv", type=Path, required=True)
    ap.add_argument("--xlsx", type=Path, required=True, help="official REPD workbook (sheet REPD) for coordinates")
    ap.add_argument("--source-manifest", type=Path, required=True,
                    help="JSON with source_url, source_excel_url, source_page, source_owner, source_dataset_title, "
                         "source_page_last_updated, validated_at, source_hashes")
    ap.add_argument("--scratch", type=Path, required=True, help="directory OUTSIDE the repo for v7.2 by-products")
    ap.add_argument("--expected-rows", type=int, help="fail unless the identity has this many records")
    ap.add_argument("--accept-expected", action="store_true",
                    help="write the builder's actual figures into the new contracts (human review required)")
    ap.add_argument("--release-text-edits", type=Path, help="JSON list of {path, old, new} edits inside the release")
    ap.add_argument("--hash-report", type=Path, required=True)
    args = ap.parse_args()

    repo = args.repo.resolve()
    pipeline = repo / "uk_renewables_pipeline"
    parent = pipeline / args.parent
    release = pipeline / args.release
    rel = f"uk_renewables_pipeline/{args.release}"
    if not parent.is_dir():
        raise SystemExit(f"FAIL: parent {parent} missing")
    if release.exists():
        raise SystemExit(f"FAIL: {release} already exists; a release is never rebuilt in place")
    scratch = args.scratch.resolve()
    if repo in scratch.parents or scratch == repo:
        raise SystemExit("FAIL: --scratch must be outside the repository copy")

    before = hash_tree(repo, ["."], exclude=release)

    # 1. copy the parent
    shutil.copytree(parent, release, symlinks=True)

    # 2. identity fixture
    manifest = json.loads(args.source_manifest.read_text(encoding="utf-8"))
    identity_rel = f"{rel}/fixtures/{args.quarter}/project_identity_{args.quarter}.json"
    registry = build_identity(repo, args.canonical_csv, manifest, repo / identity_rel)
    if args.expected_rows is not None and registry["raw_record_count"] != args.expected_rows:
        raise SystemExit(f"FAIL: identity has {registry['raw_record_count']} records, expected {args.expected_rows}")

    # 3. coordinate fixture through the existing builder, v7.2 outputs to scratch
    coords_rel = f"{rel}/fixtures/{args.quarter}/repd_{args.quarter}_coordinates.json"
    v72 = json.loads((parent / "contracts/project-spine.v7.2.json").read_text(encoding="utf-8"))
    v72.update({
        "status": "COORDINATE_FIXTURE_BUILD_ONLY",
        "identity_fixture": identity_rel,
        "identity_fixture_sha256": sha256_file(repo / identity_rel),
        "coordinate_fixture": coords_rel,
        "coordinate_fixture_sha256": None,
        "source_workbook_sha256": sha256_file(args.xlsx),
    })
    v72["source_provenance"] = {
        "dataset": args.dataset,
        "canonical_identity_source_csv_sha256": sha256_file(args.canonical_csv),
        "coordinate_workbook_copy_sha256": sha256_file(args.xlsx),
        "reconciliation": "workbook Ref-ID set equals identity Ref-ID set; technology, capacity and site name exact (build_v7_2_spine.build_coordinate_fixture)",
    }
    v72["expected"] = {}
    scratch.mkdir(parents=True, exist_ok=True)
    v72["outputs"] = {k: str(scratch / Path(v).name) for k, v in v72["outputs"].items()}
    coord_contract = scratch / f"project-spine.{args.quarter}.coordinates.json"
    coord_contract.write_text(json.dumps(v72, indent=2) + "\n", encoding="utf-8")
    proc = run([sys.executable, str(release / "scripts/data/build_v7_2_spine.py"),
                "--contract", str(coord_contract), "--repd-xlsx", str(args.xlsx)])
    print(proc.stdout.strip())
    if proc.returncode != 0:
        raise SystemExit(f"FAIL: coordinate fixture build: {proc.stderr.strip()[-2000:]}")

    # 4. spine builder: one line, so it reads and writes this release folder
    spine = release / "scripts/data/build_v9_1_spine.py"
    spine.write_text(replace_once(spine.read_text(encoding="utf-8"), SPINE_LINE_OLD, SPINE_LINE_NEW, str(spine)),
                     encoding="utf-8")

    # 5. contracts
    c91 = release / "contracts/release.v9.1.json"
    t = c91.read_text(encoding="utf-8")
    for key, value in {
        "dataset": args.dataset,
        "identity_fixture": identity_rel,
        "identity_fixture_sha256": sha256_file(repo / identity_rel),
        "coordinate_fixture": coords_rel,
        "coordinate_fixture_sha256": sha256_file(repo / coords_rel),
        "workbook_sha256": sha256_file(args.xlsx),
    }.items():
        t = set_json_scalar(t, "source", key, value, "release.v9.1.json")
    c91.write_text(t, encoding="utf-8")

    proc = run([sys.executable, str(spine)])
    actual = None
    if proc.returncode != 0:
        m = re.search(r"RuntimeError: V9\.1 acceptance mismatch: (\{.*\})", proc.stderr)
        if not m:
            raise SystemExit(f"FAIL: spine build: {proc.stderr.strip()[-2000:]}")
        import ast
        actual = ast.literal_eval(m.group(1))
        print("builder actual:", json.dumps(actual))
        if not args.accept_expected:
            raise SystemExit("FAIL: contract expected != actual; review the figures above, rerun with --accept-expected")
        t = c91.read_text(encoding="utf-8")
        for key, value in actual.items():
            t = set_json_scalar(t, "expected", key, value, "release.v9.1.json")
        c91.write_text(t, encoding="utf-8")
        proc = run([sys.executable, str(spine)])
        if proc.returncode != 0:
            raise SystemExit(f"FAIL: spine build after acceptance: {proc.stderr.strip()[-2000:]}")
    print(proc.stdout.strip())

    built = json.loads((release / "data/v9.1/build_manifest.json").read_text(encoding="utf-8"))
    c951 = release / "contracts/release.v9.5.1.json"
    t = c951.read_text(encoding="utf-8")
    for key, value in {
        "project_count": built["project_count"],
        "capacity_mw": built["capacity_mw"],
        "displayed_capacity_mw": round(built["capacity_mw"]),
        "largest_mw": built["largest_mw"],
        "valid_geometry_count": built["geometry_count"],
        "missing_geometry_count": built["missing_geometry_count"],
        "solar_count": built["solar_count"],
        "bess_count": built["bess_count"],
        "wind_onshore_count": built["wind_onshore_count"],
        "wind_offshore_count": built["wind_offshore_count"],
    }.items():
        t = set_json_scalar(t, "expected", key, value, "release.v9.5.1.json")
    c951.write_text(t, encoding="utf-8")

    # stale atlas partitions: the builder deletes and rewrites its own outputs, so
    # anything left under data/v9.1 that the manifest does not name is an error
    named = {p["path"] for p in built["project_partitions"] + built["atlas_partitions"]} | {"data/v9.1/build_manifest.json"}
    present = {p.relative_to(release).as_posix() for p in (release / "data/v9.1").rglob("*") if p.is_file()}
    if present != named:
        raise SystemExit(f"FAIL: data/v9.1 holds files the manifest does not name: {sorted(present ^ named)}")

    # 6. release-local text edits
    if args.release_text_edits:
        for edit in json.loads(args.release_text_edits.read_text(encoding="utf-8")):
            path = release / edit["path"]
            if edit.get("delete"):
                path.unlink()
                continue
            if edit.get("create") is not None:
                path.parent.mkdir(parents=True, exist_ok=True)
                path.write_text(edit["create"], encoding="utf-8")
                continue
            path.write_text(replace_once(path.read_text(encoding="utf-8"), edit["old"], edit["new"], edit["path"]),
                            encoding="utf-8")

    # atomic_write_json leaves tempfile's 0600; the repo tracks plain 100644 files
    for p in release.rglob("*"):
        if p.is_file() and (p.stat().st_mode & 0o777) == 0o600:
            p.chmod(0o644)
    after = hash_tree(repo, ["."], exclude=release)
    changed = sorted(k for k in before.keys() | after.keys() if before.get(k) != after.get(k))
    report = {
        "release": rel,
        "parent": f"uk_renewables_pipeline/{args.parent}",
        "protected_file_count": len(before),
        "changed_protected_files": changed,
        "identity_records": registry["raw_record_count"],
        "spine": {k: built[k] for k in ("project_count", "capacity_mw", "largest_mw", "geometry_count",
                                         "missing_geometry_count", "solar_count", "bess_count",
                                         "wind_onshore_count", "wind_offshore_count", "projects_sha256",
                                         "features_sha256")},
        "before": before,
    }
    args.hash_report.parent.mkdir(parents=True, exist_ok=True)
    args.hash_report.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")
    if changed:
        raise SystemExit(f"FAIL: {len(changed)} protected files changed: {changed[:10]}")
    print(f"OK: {rel} built; {len(before)} protected files byte-identical")


if __name__ == "__main__":
    main()

Renewable Energy Planning Database (REPD) Build Root

A Python command-line tool in the automation folder of GlobalGrid2050 that reads REPD grid batteries, REPD solar operational over 4MW, REPD master and the REPD register, using SHA-256.

energy-dataglobalgrid2050 / automation/repd/build_root.py · lines 1–246 of 246 · Entry point · pattern build_root (shared by 2 files)

What it does
It loads REPD grid batteries, REPD solar operational over 4MW, REPD master and the REPD register. Defines 11 functions or classes, including _norm, _capacity, read_canonical, _write_csv, _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 repd.csv; CSV file repd-grid-batteries.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-over-4mw.csv; JSON file repd_master.json; JSON file manifest_v4.json; command-line arguments.
Downstream impact
Used directly by 1 file: Test Hardening Nl013 (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It reads canonical (`read_canonical`), normalises descriptor (`normalise_descriptor`) and builds master (`build_master`). Root-format REPD datasets for a new release, built from the cleaned canonical CSV. Its code works with 1 MW and 4 MW. It accepts `--out`, `--repo-root` and `--descriptor`.
Why it matters
Checked by Test Hardening Nl013.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, csv, hashlib, io, json, sys, datetime
Used by
imported by Test Hardening Nl013 (import)
Produces
read_canonical, normalise_descriptor, solar_operational_header, build_master, build_root, main
Defines here
_norm, _capacity, read_canonical, _write_csv, _sha256, normalise_descriptor, solar_operational_header, build_master, build_root, operational_solar, 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/build_root.py:1-246 · blob abd44387ef365bfcefc02e4c8618906533993633 · 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
"""Root-format REPD datasets for a new release, built from the cleaned canonical CSV.

Reproduces, under NEW names, the files the legacy atlas and table pages read:

    repd.csv                              full register, official 53-column layout
    repd-grid-batteries.csv               Battery, active statuses
    repd-solar-operational.csv            Solar PV, Operational, > 1 MW, ground or roof (43 columns)
    repd-solar-operational-over-4mw.csv   Solar PV, Operational, > 4 MW
    dist/repd_master.json                 GeoJSON of viable geocoded records (scripts/repd_updater.py)
    dist/manifest_v4.json                 provenance of that GeoJSON

Nothing existing is overwritten: the orchestrator (run.py) renames each output with the
release label (repd-2026q3.csv, dist/repd_master_2026q3.json, ...). The January 2026 files
of the same base names stay byte-identical; other releases and repositories pin their hashes.

The filters are the ones that reproduce the committed January subsets exactly by Ref ID
(crawl note 16, lineage note 3.3). Blank capacity is unknown and never passes a threshold.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

BATTERY_STATUSES = {
    "Operational", "Under Construction", "Awaiting Construction",
    "Application Submitted", "Appeal Lodged", "No Application Required",
}
SOLAR = "Solar Photovoltaics"
CAPACITY = "Installed Capacity (MWelec)"
STATUS = "Development Status (short)"
TECH = "Technology Type"
MOUNT = "Mounting Type for Solar"

# Header of the committed repd-solar-operational.csv (43 of the 53 official columns, same order).
SOLAR_OPERATIONAL_DROPPED = {
    "Storage Type", "Share Community Scheme", "Turbine Capacity (MW)", "No. of Turbines",
    "Height of Turbines (m)", "Offshore Wind Round", "Appeal Withdrawn", "Appeal Refused",
    "Secretary of State - Refusal", "Heat Network Ref",
}


def _norm(name: str) -> str:
    return " ".join(str(name).replace("", "").split())


def _capacity(value: str):
    text = (value or "").strip().replace(",", "")
    if not text:
        return None
    try:
        return float(text)
    except ValueError:
        return None


def read_canonical(path: Path) -> tuple[list[str], list[dict]]:
    raw = Path(path).read_bytes()
    text = raw.decode("utf-8-sig")
    reader = csv.reader(io.StringIO(text, newline=""))
    header = next(reader)
    rows = []
    for record in reader:
        if len(record) != len(header):
            raise RuntimeError(f"record with {len(record)} fields, header has {len(header)}")
        rows.append(dict(zip(header, record)))
    return header, rows


def _write_csv(path: Path, header: list[str], rows: list[dict]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.writer(handle, lineterminator="\r\n")
        writer.writerow(header)
        for row in rows:
            writer.writerow([row[column] for column in header])


def _sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def normalise_descriptor(descriptor: dict | None) -> dict:
    """Accept both descriptor shapes: run.py's flat dict and the committed release descriptor
    (schema globalgrid2050.repd-release-descriptor.v1, hashes nested under "expected", the publication
    date as "page_last_updated", the release id as "release_id"). Flat keys win; nothing is invented."""
    d = dict(descriptor or {})
    expected = d.get("expected") if isinstance(d.get("expected"), dict) else {}
    for flat, nested in (("expected_csv_sha256", "csv_sha256"), ("expected_xlsx_sha256", "xlsx_sha256")):
        if not d.get(flat) and expected.get(nested):
            d[flat] = expected[nested]
    if not d.get("page_last_updated") and d.get("published"):
        d["page_last_updated"] = d["published"]
    return d


def solar_operational_header(official_header: list[str], legacy_file: Path | None) -> list[str]:
    """43-column header: taken from the committed legacy file when present, else derived."""
    by_norm = {_norm(column): column for column in official_header}
    if legacy_file and Path(legacy_file).is_file():
        with Path(legacy_file).open("r", encoding="utf-8-sig", newline="") as handle:
            legacy = next(csv.reader(handle))
        missing = [column for column in legacy if _norm(column) not in by_norm]
        if missing:
            raise RuntimeError(f"legacy solar header has columns absent from the release: {missing}")
        return [by_norm[_norm(column)] for column in legacy]
    return [column for column in official_header if _norm(column) not in SOLAR_OPERATIONAL_DROPPED]


def build_master(canonical_csv: Path, repo_root: Path) -> dict:
    """GeoJSON via the repository's own refiner (scripts/repd_updater.py), unchanged."""
    import os
    import tempfile

    scripts = str(Path(repo_root) / "scripts")
    if scripts not in sys.path:
        sys.path.insert(0, scripts)
    canonical_csv = Path(canonical_csv).resolve()
    previous = os.getcwd()
    # REPDUpdater.__init__ creates ./dist and ./data and reads config/registry.yaml relative to the
    # working directory; refine_dataset() itself reads neither. Run it in a scratch directory so the
    # repository is never written (not even an empty data/ directory), and pass the registry by
    # absolute path. A checkout without config/ (the release-candidate workflow's sparse checkout)
    # gets a stub registry instead of a SystemExit.
    with tempfile.TemporaryDirectory(prefix="repd-build-master-") as scratch:
        registry = Path(repo_root).resolve() / "config" / "registry.yaml"
        if not registry.is_file():
            registry = Path(scratch) / "registry.yaml"
            registry.write_text("# stub: refine_dataset() does not read the registry\nlayers: []\n", encoding="utf-8")
        os.chdir(scratch)
        try:
            from repd_updater import REPDUpdater
            return REPDUpdater(registry_path=str(registry)).refine_dataset(str(canonical_csv))
        finally:
            os.chdir(previous)


def build_root(canonical_csv, out_dir, repo_root=None, descriptor=None, label=None) -> dict:
    canonical_csv, out_dir = Path(canonical_csv), Path(out_dir)
    repo_root = Path(repo_root) if repo_root else Path(__file__).resolve().parents[2]
    descriptor = normalise_descriptor(descriptor)
    out_dir.mkdir(parents=True, exist_ok=True)

    header, rows = read_canonical(canonical_csv)
    refs = [row["Ref ID"] for row in rows]
    if len(set(refs)) != len(refs):
        raise RuntimeError("canonical CSV has duplicate Ref IDs; refusing to build")
    for column in (TECH, STATUS, CAPACITY, MOUNT, "Ref ID"):
        if column not in header:
            raise RuntimeError(f"canonical CSV lacks required column {column!r}")

    files: dict[str, Path] = {}
    counts: dict[str, int] = {}

    # 1. full register: the cleaned canonical file, byte for byte
    full = out_dir / "repd.csv"
    full.write_bytes(canonical_csv.read_bytes())
    files["repd.csv"], counts["repd.csv"] = full, len(rows)

    # 2. batteries, active statuses
    batteries = [r for r in rows if r[TECH].strip() == "Battery" and r[STATUS].strip() in BATTERY_STATUSES]
    path = out_dir / "repd-grid-batteries.csv"
    _write_csv(path, header, batteries)
    files["repd-grid-batteries.csv"], counts["repd-grid-batteries.csv"] = path, len(batteries)

    # 3. operational solar above 1 MW, ground or roof, 43 columns
    def operational_solar(row, floor):
        capacity = _capacity(row[CAPACITY])
        return (row[TECH].strip() == SOLAR and row[STATUS].strip() == "Operational"
                and capacity is not None and capacity > floor)

    solar_1 = [r for r in rows if operational_solar(r, 1.0) and r[MOUNT].strip() in {"Ground", "Roof"}]
    solar_header = solar_operational_header(header, repo_root / "repd-solar-operational.csv")
    path = out_dir / "repd-solar-operational.csv"
    _write_csv(path, solar_header, solar_1)
    files["repd-solar-operational.csv"], counts["repd-solar-operational.csv"] = path, len(solar_1)

    # 4. operational solar above 4 MW, all mountings, 53 columns
    solar_4 = [r for r in rows if operational_solar(r, 4.0)]
    path = out_dir / "repd-solar-operational-over-4mw.csv"
    _write_csv(path, header, solar_4)
    files["repd-solar-operational-over-4mw.csv"], counts["repd-solar-operational-over-4mw.csv"] = path, len(solar_4)

    # 5. master GeoJSON and its manifest
    geojson = build_master(full, repo_root)
    master = out_dir / "dist" / "repd_master.json"
    master.parent.mkdir(parents=True, exist_ok=True)
    master.write_text(json.dumps(geojson, separators=(",", ":"), ensure_ascii=False), encoding="utf-8")
    files["dist/repd_master.json"], counts["dist/repd_master.json"] = master, len(geojson["features"])

    manifest = {
        "system": "VENTUS_CORE",
        "schema_version": 6,
        "last_sync": descriptor.get("retrieved_at") or datetime.now(timezone.utc).isoformat(),
        "source_owner": "Department for Energy Security and Net Zero (DESNZ)",
        "source_url": descriptor.get("csv_url"),
        "source_excel_url": descriptor.get("xlsx_url"),
        "source_page": descriptor.get("source_page")
        or "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract",
        "source_dataset_title": descriptor.get("title") or descriptor.get("dataset_title")
        or "Renewable Energy Planning Database",
        "source_page_last_updated": descriptor.get("page_last_updated"),
        "source_file": (descriptor.get("csv_url") or "").rsplit("/", 1)[-1] or None,
        "source_sha256": {"csv": descriptor.get("expected_csv_sha256"), "xlsx": descriptor.get("expected_xlsx_sha256")},
        "cleaned_csv_sha256": _sha256(full),
        "official_ref_field": "Ref ID",
        "official_record_update_field": "Record Last Updated (dd/mm/yyyy)",
        "record_count": len(rows),
        "feature_count": len(geojson["features"]),
        "release_label": label or descriptor.get("release_id") or descriptor.get("label"),
        "status": "CANDIDATE",
    }
    manifest_path = out_dir / "dist" / "manifest_v4.json"
    manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
    files["dist/manifest_v4.json"] = manifest_path

    return {
        "status": "ok",
        "files": {rel: str(path) for rel, path in files.items()},
        "counts": counts,
        "sha256": {rel: _sha256(path) for rel, path in files.items()},
    }


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
    parser.add_argument("canonical_csv")
    parser.add_argument("--out", required=True)
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--descriptor", default=None, help="release descriptor JSON")
    parser.add_argument("--label", default=None)
    args = parser.parse_args(argv)
    descriptor = json.loads(Path(args.descriptor).read_text(encoding="utf-8")) if args.descriptor else {}
    result = build_root(args.canonical_csv, args.out, args.repo_root, descriptor, args.label)
    print(json.dumps({"counts": result["counts"], "sha256": result["sha256"]}, indent=2))
    return 0


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