GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Renewable Energy Planning Database (REPD) Updater and 4 more files

A Python command-line tool in the scripts folder that fetches REPD publication q2, REPD master, the REPD register and solar.

523 lines of Python from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 888 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) Sources V6 energy-data · globalgrid2050 / scripts/repd_sources_v6.py lines 566–597
  2. GlobalGrid2050 Renewable Energy Planning Database (REPD) Updater energy-data · globalgrid2050 / scripts/repd_updater.py lines 1–355
  3. GlobalGrid2050 Split Elexon Generation Sources by Year energy-data · globalgrid2050 / scripts/split_elexon_generation_sources_by_year.py lines 1–39
  4. GlobalGrid2050 Split Elexon System Prices by Year energy-data · globalgrid2050 / scripts/split_elexon_system_prices_by_year.py lines 1–38
  5. GlobalGrid2050 Split Generation Sources Year to Months V6 energy-data · globalgrid2050 / scripts/split_generation_sources_year_to_months_v6.py lines 1–59

GlobalGrid2050 Renewable Energy Planning Database (REPD) Sources V6

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

energy-dataglobalgrid2050 / scripts/repd_sources_v6.py · lines 566–597 of 597 (continued from section 887) · Entry point · pattern planning_refs_equivalent (shared by 2 files)

What it does
It fetches REPD canonical, REPD reconciliation, REPD publication q2 and the REPD register. Defines 24 functions or classes, including utc_now, sha256, collapse, norm_text, norm_date. Uses libraries __future__, hashlib, io, json, math. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: CSV file latest_repd_v6_canonical.csv; JSON file repd_source_reconciliation_v6.json; JSON file manifest_v6.json; CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx; command-line arguments. Out: CSV file.
Downstream impact
Used directly by 6 files: GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest (globalgrid2050); GlobalGrid2050 Validate Renewable Energy Planning Database (REPD) Sources V6 (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow (globalgrid2050); GlobalGrid2050 Build Project Identity V6 (globalgrid2050); and 2 more. Reached from 2 other entry points, including GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 Evidence Branch Workflow (globalgrid2050).
What it achieves
It cleans ref (`clean_ref`), fetches bytes (`fetch_bytes`) and reads CSV (`read_csv`). Official DESNZ Q2 2026 source retrieval and deterministic reconciliation. Its code works with 1 MW, 100 MW and 0.005 MW. It accepts `--csv-file` and `--xlsx-file`.
Why it matters
Imported by 5 files, including GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest, GlobalGrid2050 Validate Renewable Energy Planning Database (REPD) Sources V6 and GlobalGrid2050 Build Project Identity V6. Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, hashlib, io, json, math, os, re, time
Used by
imported by GlobalGrid2050 Renewable Energy Planning Database (REPD) Q3 2026 Ingest (import), imported by GlobalGrid2050 Validate Renewable Energy Planning Database (REPD) Sources V6 (import), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) 2026 Q3 Ingestion Workflow (workflow run), imported by GlobalGrid2050 Build Project Identity V6 (import), imported by GlobalGrid2050 Validate Project Identity V6 (import), imported by GlobalGrid2050 Validate V6 Manifest Provenance (import)
Produces
utc_now, sha256, collapse, norm_text, norm_date, strict_date, month_first_date, is_typed_date, drop_identical_duplicates, norm_number, clean_ref, canonicalise_headers
Defines here
write_outputs, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/repd_sources_v6.py:566-597 · blob d7470d97a2e34da8cdc5e9eb410a6e6d77f58016 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
    xlsx_file = xlsx_file or os.environ.get("REPD_SOURCE_XLSX_FILE", "").strip()
    if bool(csv_file) != bool(xlsx_file):
        raise RuntimeError("Offline mode needs both the CSV and the XLSX file")
    csv_raw = Path(csv_file).read_bytes() if csv_file else fetch(CSV_URL)
    xlsx_raw = Path(xlsx_file).read_bytes() if xlsx_file else fetch(XLSX_URL)
    return reconcile(csv_raw, xlsx_raw)


def write_outputs(canonical: pd.DataFrame, report: dict, manifest: dict) -> None:
    DIST.mkdir(parents=True, exist_ok=True)
    DATA.mkdir(parents=True, exist_ok=True)
    REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")
    if not report.get("pass"):
        raise RuntimeError(f"Official {QUARTER_LABEL} CSV/XLSX reconciliation failed; previous validated snapshot retained")
    canonical.to_csv(CANONICAL_CSV, index=False, encoding="utf-8-sig")
    MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")


def main(argv=None) -> None:
    import argparse

    parser = argparse.ArgumentParser(description="Reconcile the official REPD CSV/XLSX (descriptor via REPD_RELEASE_DESCRIPTOR)")
    parser.add_argument("--csv-file", default="", help="offline mode: local official CSV bytes")
    parser.add_argument("--xlsx-file", default="", help="offline mode: local official XLSX bytes")
    args = parser.parse_args(argv)
    canonical, report, manifest = run_reconciliation(args.csv_file, args.xlsx_file)
    write_outputs(canonical, report, manifest)
    print("REPD SOURCE RECONCILIATION PASS", json.dumps(report["metrics"], sort_keys=True))


if __name__ == "__main__":
    main()

GlobalGrid2050 Renewable Energy Planning Database (REPD) Updater

A Python command-line tool in the scripts folder that fetches REPD publication q2, REPD master, the REPD register and solar.

energy-dataglobalgrid2050 / scripts/repd_updater.py · lines 1–355 of 355 · Entry point · pattern already_current (shared by 2 files)

What it does
It fetches REPD publication q2, REPD master, the REPD register and solar. Defines 12 functions or classes, including REPDUpdater, __init__, clean_text, clean_ref, iso_date. Uses libraries pandas, json, yaml, os, re. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar.
Inputs & outputs
In: CSV file REPD_Publication_Q2_2026.csv; Excel file REPD_Publication_Q2_2026.xlsx; JSON file manifest_v4.json; JSON file repd_master.json; CSV file latest_repd.csv. Out: JSON file repd_master.json; JSON file manifest_v4.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Renewable Energy Planning Database (REPD) Sync Workflow (globalgrid2050).
What it achieves
It validates schema (`validate_schema`) and is built from the REPD updater class (`REPDUpdater`) and the iso date helper (`iso_date`). Defines `REPDUpdater`, `clean_text`, `clean_ref` and 8 more.
Why it matters
Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Sync Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pandas, json, yaml, os, re, requests, datetime, math
Used by
run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Sync Workflow (workflow run)
Produces
REPDUpdater
Defines here
REPDUpdater, __init__, clean_text, clean_ref, iso_date, validate_schema, discover_latest_sources, already_current, fetch_data, classify_tech, refine_dataset, execute
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_updater.py:1-355 · blob e13d76efba9e6403b5297c869cbe1bbb95f51b96 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import pandas as pd
import json
import yaml
import os
import re
import requests
from datetime import datetime, timezone
from math import isfinite
from pathlib import Path
from pyproj import Transformer
from bs4 import BeautifulSoup


class REPDUpdater:
    """
    VENTUS REPD UPDATER v6.0 | OFFICIAL REPD-BOUND MASTER GEOJSON

    The serving spine remains dist/repd_master.json, but every retained project is
    now carried with its official DESNZ REPD Ref ID and Record Last Updated date.
    Existing V1-V5 consumers ignore the extra properties and remain compatible.
    """

    REPD_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
    CURRENT_Q2_2026_CSV = "https://assets.publishing.service.gov.uk/media/6a6cbdc00c36759b5ccaa305/REPD_Publication_Q2_2026.csv"
    CURRENT_Q2_2026_XLSX = "https://assets.publishing.service.gov.uk/media/6a6cbdd2862aaf18d9c62b02/REPD_Publication_Q2_2026.xlsx"

    UK_LON_MIN, UK_LON_MAX = -9.0, 2.5
    UK_LAT_MIN, UK_LAT_MAX = 49.0, 61.0

    VIABLE_STATUSES = {
        "operational",
        "under construction",
        "awaiting construction",
        "consented",
        "planning permission granted",
        "planning approved",
        "application submitted",
        "pre-construction",
    }

    REQUIRED_COLUMNS = [
        "Ref ID",
        "Record Last Updated (dd/mm/yyyy)",
        "Site Name",
        "Technology Type",
        "Development Status (short)",
        "Installed Capacity (MWelec)",
        "X-coordinate",
        "Y-coordinate",
        "Operator (or Applicant)",
    ]

    OPTIONAL_COLUMNS = [
        "Old Ref ID",
        "Mounting Type for Solar",
        "County",
        "Region",
        "Planning Authority",
        "Local Planning Authority",
        "Planning Application Reference",
        "Planning Permission Granted",
        "Under Construction",
        "Operational",
    ]

    def __init__(self, registry_path="config/registry.yaml"):
        print("📡 VENTUS REPD UPDATER v6.0 | OFFICIAL REPD BINDING...")
        try:
            with open(registry_path, "r", encoding="utf-8") as f:
                self.config = yaml.safe_load(f)
        except FileNotFoundError:
            raise SystemExit(f"❌ ERROR: {registry_path} not found.")
        self.output_dir = "dist"
        self.raw_data_dir = "data"
        os.makedirs(self.output_dir, exist_ok=True)
        os.makedirs(self.raw_data_dir, exist_ok=True)
        self.transformer = Transformer.from_crs("epsg:27700", "epsg:4326", always_xy=True)

    @staticmethod
    def clean_text(value):
        if pd.isna(value):
            return ""
        s = str(value).strip()
        return "" if s.lower() in {"nan", "none", "not set", "null"} else s

    @staticmethod
    def clean_ref(value):
        if pd.isna(value):
            return ""
        s = str(value).strip()
        if re.fullmatch(r"\d+\.0", s):
            s = s[:-2]
        return "" if s.lower() in {"nan", "none", "not set", "null"} else s

    @staticmethod
    def iso_date(value):
        if pd.isna(value):
            return ""
        dt = pd.to_datetime(value, dayfirst=True, errors="coerce")
        return "" if pd.isna(dt) else dt.strftime("%Y-%m-%d")

    def validate_schema(self, df):
        cols = set(df.columns)
        missing_required = [c for c in self.REQUIRED_COLUMNS if c not in cols]
        missing_optional = [c for c in self.OPTIONAL_COLUMNS if c not in cols]
        if missing_required:
            print(f"❌ SCHEMA ERROR — missing required columns: {missing_required}")
            print(f"   Available columns: {sorted(cols)}")
            raise SystemExit(1)
        if missing_optional:
            print(f"⚠️ Missing optional columns (degraded enrichment only): {missing_optional}")
        else:
            print("✅ DESNZ schema valid — official Ref ID and update-date columns present")

    def discover_latest_sources(self):
        print("🔍 Discovering current DESNZ REPD publication from GOV.UK...")
        result = {
            "csv_url": "",
            "excel_url": "",
            "dataset_title": "",
            "page_last_updated": "",
        }
        try:
            r = requests.get(self.REPD_PAGE, timeout=20)
            r.raise_for_status()
            soup = BeautifulSoup(r.text, "html.parser")
            page_text = " ".join(soup.stripped_strings)
            m = re.search(r"Last updated:?\s+(\d{1,2}\s+[A-Za-z]+\s+\d{4})", page_text, re.I)
            if m:
                dt = pd.to_datetime(m.group(1), dayfirst=True, errors="coerce")
                if not pd.isna(dt):
                    result["page_last_updated"] = dt.strftime("%Y-%m-%d")

            for a in soup.find_all("a", href=True):
                href = a["href"].strip()
                text = a.get_text(" ", strip=True)
                low = (href + " " + text).lower()
                url = href if href.startswith("http") else f"https://www.gov.uk{href}"
                if ".csv" in low and "repd" in low and not result["csv_url"]:
                    result["csv_url"] = url
                    result["dataset_title"] = text
                if (".xlsx" in low or ".xls" in low) and "repd" in low and not result["excel_url"]:
                    result["excel_url"] = url

            if result["csv_url"]:
                print(f"✅ Official REPD CSV: {result['csv_url']}")
                if result["excel_url"]:
                    print(f"✅ Official REPD Excel: {result['excel_url']}")
                return result
        except Exception as e:
            print(f"⚠️ GOV.UK discovery failed: {e}")

        print("⚠️ Falling back to the known DESNZ July 2026 Q2 publication URLs")
        result.update(
            {
                "csv_url": self.CURRENT_Q2_2026_CSV,
                "excel_url": self.CURRENT_Q2_2026_XLSX,
                "dataset_title": "Renewable Energy Planning Database (REPD): July 2026 (CSV)",
                "page_last_updated": "2026-08-03",
            }
        )
        return result

    def already_current(self, url):
        manifest_path = Path(self.output_dir) / "manifest_v4.json"
        master_path = Path(self.output_dir) / "repd_master.json"
        if not manifest_path.exists() or not master_path.exists():
            return False
        try:
            manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
            if manifest.get("source_url") != url or int(manifest.get("schema_version") or 0) < 6:
                return False
            master = json.loads(master_path.read_text(encoding="utf-8"))
            features = master.get("features") or []
            if not features:
                return False
            props = features[0].get("properties") or {}
            if not props.get("repd_ref") or "repd_record_updated" not in props:
                return False
            print("✅ REPD source unchanged and V6 official-reference schema already present.")
            return True
        except Exception:
            return False

    def fetch_data(self, url):
        print(f"📥 FETCHING OFFICIAL CSV: {url}")
        try:
            r = requests.get(url, timeout=45)
            r.raise_for_status()
            path = Path(self.raw_data_dir) / "latest_repd.csv"
            path.write_bytes(r.content)
            return str(path)
        except Exception as e:
            print(f"❌ REPD FETCH FAILED: {e}")
            return None

    def classify_tech(self, tech_raw, mounting):
        tl = tech_raw.strip().lower()
        if "solar photovoltaic" in tl or "solar pv" in tl:
            return "solar_roof" if mounting == "roof" else "solar"
        if "wind onshore" in tl or "wind offshore" in tl or tl == "wind":
            return "wind"
        if tl == "hydrogen" or "fuel cell (hydrogen)" in tl:
            return "hydrogen"
        if "large hydro" in tl or "small hydro" in tl or "pumped storage hydro" in tl:
            return "hydro"
        if "compressed air energy storage" in tl or "liquid air energy storage" in tl:
            return "caes"
        if tl in {"battery", "battery storage"}:
            return "bess"
        if any(x in tl for x in ["biomass", "efw incineration", "anaerobic digestion", "landfill gas", "sewage sludge", "co-firing", "energy from waste", "incineration"]):
            return "biomass"
        if "advanced conversion" in tl or "gasification" in tl or "pyrolysis" in tl:
            return "act"
        if "geothermal" in tl or "hot dry rocks" in tl:
            return "geothermal"
        if "tidal" in tl or "shoreline wave" in tl:
            return "tidal"
        if "flywheel" in tl:
            return "flywheel"
        if "storage" in tl or "battery" in tl:
            return "bess"
        if "wind" in tl:
            return "wind"
        return "other"

    def refine_dataset(self, csv_path):
        print("🧪 REFINING OFFICIAL REPD MASTER DATASET...")
        try:
            df = pd.read_csv(csv_path, encoding="utf-8-sig", on_bad_lines="skip", engine="python")
        except UnicodeDecodeError:
            df = pd.read_csv(csv_path, encoding="unicode_escape", on_bad_lines="skip", engine="python")
        df.columns = [c.strip() for c in df.columns]
        self.validate_schema(df)

        mounting_col = "Mounting Type for Solar" if "Mounting Type for Solar" in df.columns else "Mounting Type" if "Mounting Type" in df.columns else None
        if not mounting_col:
            print("⚠️ No mounting type column found — all solar mapped to 'solar'")

        df["Development Status (short)"] = df["Development Status (short)"].astype(str).str.strip().str.lower()
        df = df[df["Development Status (short)"].isin(self.VIABLE_STATUSES)]

        features = []
        skipped = 0
        missing_refs = 0
        seen_refs = set()
        for _, row in df.iterrows():
            try:
                repd_ref = self.clean_ref(row.get("Ref ID"))
                if not repd_ref:
                    missing_refs += 1
                    skipped += 1
                    continue
                if repd_ref in seen_refs:
                    raise ValueError(f"duplicate official REPD Ref ID in viable dataset: {repd_ref}")
                seen_refs.add(repd_ref)

                e = float(row["X-coordinate"])
                n = float(row["Y-coordinate"])
                if not e or not n or e == 0 or n == 0:
                    skipped += 1
                    continue
                lon, lat = self.transformer.transform(e, n)
                if not (isfinite(lon) and isfinite(lat)):
                    skipped += 1
                    continue
                if not (self.UK_LON_MIN < lon < self.UK_LON_MAX and self.UK_LAT_MIN < lat < self.UK_LAT_MAX):
                    skipped += 1
                    continue

                tech_raw = self.clean_text(row.get("Technology Type"))
                mounting = self.clean_text(row.get(mounting_col)).lower() if mounting_col else ""
                tech_map = self.classify_tech(tech_raw, mounting)
                try:
                    capacity = float(row.get("Installed Capacity (MWelec)", 0))
                    if not isfinite(capacity):
                        capacity = 0.0
                    if tech_map == "solar_roof" and capacity > 50:
                        capacity = round(capacity / 1000, 4)
                    if tech_map == "biomass" and capacity > 100:
                        capacity = round(capacity / 1000, 4)
                except (ValueError, TypeError):
                    capacity = 0.0

                planning_authority = self.clean_text(row.get("Planning Authority")) or self.clean_text(row.get("Local Planning Authority"))
                features.append(
                    {
                        "type": "Feature",
                        "properties": {
                            "repd_ref": repd_ref,
                            "repd_old_ref": self.clean_ref(row.get("Old Ref ID")),
                            "repd_record_updated": self.iso_date(row.get("Record Last Updated (dd/mm/yyyy)")),
                            "name": self.clean_text(row.get("Site Name")) or "Unknown",
                            "county": self.clean_text(row.get("County")),
                            "region": self.clean_text(row.get("Region")),
                            "local_planning_authority": planning_authority,
                            "planning_authority": planning_authority,
                            "planning_application_reference": self.clean_text(row.get("Planning Application Reference")),
                            "planning_permission_granted": self.iso_date(row.get("Planning Permission Granted")),
                            "under_construction_date": self.iso_date(row.get("Under Construction")),
                            "operational_date": self.iso_date(row.get("Operational")),
                            "operator": (self.clean_text(row.get("Operator (or Applicant)")) or "Unknown").upper(),
                            "capacity": capacity,
                            "status": self.clean_text(row.get("Development Status (short)")),
                            "tech": tech_map,
                            "raw_tech": tech_raw,
                            "mounting": mounting,
                        },
                        "geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]},
                    }
                )
            except (ValueError, TypeError) as e:
                skipped += 1
                if "duplicate official REPD Ref ID" in str(e):
                    raise

        if missing_refs:
            raise RuntimeError(f"Official REPD binding failed: {missing_refs} viable rows lacked Ref ID")
        print(f"✅ REPD V6 binding: {len(features)} viable geocoded assets; skipped {skipped} unusable-coordinate rows")
        return {"type": "FeatureCollection", "schema": "globalgrid2050.repd-master.v6", "features": features}

    def execute(self):
        sources = self.discover_latest_sources()
        for layer in self.config["layers"]:
            if layer["id"] == "repd" or layer["type"] == "csv":
                url = sources.get("csv_url") or layer.get("url") or self.CURRENT_Q2_2026_CSV
                if self.already_current(url):
                    return
                local_csv = self.fetch_data(url)
                if not local_csv:
                    raise SystemExit(1)
                geojson = self.refine_dataset(local_csv)
                Path(self.output_dir, "repd_master.json").write_text(json.dumps(geojson, separators=(",", ":")), encoding="utf-8")
                print(f"✅ MASTER SYNC: {len(geojson['features'])} assets.")
                manifest = {
                    "system": "VENTUS_CORE",
                    "schema_version": 6,
                    "last_sync": datetime.now(timezone.utc).isoformat(),
                    "source_owner": "Department for Energy Security and Net Zero (DESNZ)",
                    "source_url": url,
                    "source_excel_url": sources.get("excel_url") or self.CURRENT_Q2_2026_XLSX,
                    "source_page": self.REPD_PAGE,
                    "source_dataset_title": sources.get("dataset_title") or "Renewable Energy Planning Database",
                    "source_page_last_updated": sources.get("page_last_updated"),
                    "source_file": url.rsplit("/", 1)[-1],
                    "official_ref_field": "Ref ID",
                    "official_record_update_field": "Record Last Updated (dd/mm/yyyy)",
                    "status": "OPERATIONAL",
                }
                Path(self.output_dir, "manifest_v4.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
                return


if __name__ == "__main__":
    REPDUpdater().execute()

GlobalGrid2050 Split Elexon Generation Sources by Year

A Python command-line tool in the scripts folder that works with row year (`row_year`), covering Elexon generation sources half hourly.

energy-dataglobalgrid2050 / scripts/split_elexon_generation_sources_by_year.py · lines 1–39 of 39 · Entry point · pattern row_year (shared by 2 files)

What it does
Defines row_year, sort_key, main. Uses libraries csv, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'elexon'): 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 elexon_generation_sources_half_hourly.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Elexon Generation Sources Weekly Workflow (globalgrid2050).
What it achieves
Defines `row_year` and `sort_key`.
Why it matters
Run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, pathlib
Used by
run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow (workflow run)
Produces
row_year, sort_key, main
Defines here
row_year, sort_key, 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/split_elexon_generation_sources_by_year.py:1-39 · blob 2c6f612ba606bb4cb40b3762c0811b1ecf5cacb0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
from pathlib import Path

SOURCE = Path('data/generation/elexon_generation_sources_half_hourly.csv')
OUT_DIR = Path('data/generation')
FIELDS = ['source','periodStartUTC','fuelType','generationMW','publishTimeUTC','fetchedAtUTC']


def row_year(row):
    value = (row.get('periodStartUTC') or '').strip()
    return value[:4] if len(value) >= 4 and value[:4].isdigit() else None


def sort_key(row):
    return (row.get('periodStartUTC', ''), row.get('fuelType', ''))


def main():
    if not SOURCE.exists():
        raise SystemExit(f'Missing source file: {SOURCE}')
    by_year = {}
    with SOURCE.open('r', encoding='utf-8', newline='') as handle:
        for row in csv.DictReader(handle):
            year = row_year(row)
            if year:
                by_year.setdefault(year, []).append({field: row.get(field, '') for field in FIELDS})
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    for year, rows in sorted(by_year.items()):
        path = OUT_DIR / f'elexon_generation_sources_{year}.csv'
        with path.open('w', encoding='utf-8', newline='') as handle:
            writer = csv.DictWriter(handle, fieldnames=FIELDS)
            writer.writeheader()
            writer.writerows(sorted(rows, key=sort_key))
        print(f'Wrote {len(rows)} rows to {path}')
    print(f'Split {sum(len(rows) for rows in by_year.values())} rows into {len(by_year)} annual files')


if __name__ == '__main__':
    main()

GlobalGrid2050 Split Elexon System Prices by Year

A Python command-line tool in the scripts folder that works with row year (`row_year`), covering Elexon system prices half hourly.

energy-dataglobalgrid2050 / scripts/split_elexon_system_prices_by_year.py · lines 1–38 of 38 · Entry point · pattern row_year (shared by 2 files)

What it does
Defines row_year, sort_key, main. Uses libraries csv, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'prices'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: CSV file elexon_system_prices_half_hourly.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Elexon System Prices Workflow (globalgrid2050).
What it achieves
Defines `row_year` and `sort_key`.
Why it matters
Run by GlobalGrid2050 Elexon System Prices Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, pathlib
Used by
run by GlobalGrid2050 Elexon System Prices Workflow (workflow run)
Produces
row_year, sort_key, main
Defines here
row_year, sort_key, 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/split_elexon_system_prices_by_year.py:1-38 · blob ed7e42cb4fefde7ea9bd0ac0a58e71f755a3d072 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
import csv
from pathlib import Path

SOURCE = Path('data/electricity/elexon_system_prices_half_hourly.csv')
OUT_DIR = Path('data/electricity')
FIELDS = ['source','settlementDate','settlementPeriod','periodStartUTC','systemBuyPriceGBPperMWh','systemSellPriceGBPperMWh','netImbalanceVolumeMWh','fetchedAtUTC']

def row_year(row):
    value = (row.get('settlementDate') or row.get('periodStartUTC') or '').strip()
    return value[:4] if len(value) >= 4 and value[:4].isdigit() else None

def sort_key(row):
    try:
        period = int(row.get('settlementPeriod', '999'))
    except Exception:
        period = 999
    return (row.get('settlementDate', ''), period)

def main():
    if not SOURCE.exists():
        raise SystemExit(f'Missing source file: {SOURCE}')
    by_year = {}
    with SOURCE.open('r', encoding='utf-8', newline='') as handle:
        for row in csv.DictReader(handle):
            year = row_year(row)
            if year:
                by_year.setdefault(year, []).append({field: row.get(field, '') for field in FIELDS})
    for year, rows in sorted(by_year.items()):
        path = OUT_DIR / f'elexon_system_prices_{year}.csv'
        with path.open('w', encoding='utf-8', newline='') as handle:
            writer = csv.DictWriter(handle, fieldnames=FIELDS)
            writer.writeheader()
            writer.writerows(sorted(rows, key=sort_key))
        print(f'Wrote {len(rows)} rows to {path}')
    print(f'Split {sum(len(rows) for rows in by_year.values())} rows into {len(by_year)} annual files')

if __name__ == '__main__':
    main()

GlobalGrid2050 Split Generation Sources Year to Months V6

A Python command-line tool in the scripts folder.

energy-dataglobalgrid2050 / scripts/split_generation_sources_year_to_months_v6.py · lines 1–59 of 59 · Entry point

What it does
Defines month_from_row, split_year, main. Uses libraries csv, sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): 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: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (globalgrid2050).
What it achieves
Defines `month_from_row` and `split_year`. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Run by GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, sys, pathlib
Used by
run by GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (workflow run)
Produces
month_from_row, split_year, main
Defines here
month_from_row, split_year, 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/split_generation_sources_year_to_months_v6.py:1-59 · blob e87f976456f64ab44ff5247a906a6f1724799b01 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import sys
from pathlib import Path

DATA_DIR = Path('data/generation')
FIELDS = ['source', 'periodStartUTC', 'fuelType', 'generationMW', 'publishTimeUTC', 'fetchedAtUTC']


def month_from_row(row):
    t = row.get('periodStartUTC', '')
    if len(t) >= 7:
        return t[:7]
    return None


def split_year(year):
    src = DATA_DIR / f'elexon_generation_sources_{year}.csv'
    archive_dir = DATA_DIR / 'archive' / str(year)
    if not src.exists():
        print(f'Missing annual source: {src}')
        return []

    archive_dir.mkdir(parents=True, exist_ok=True)
    buckets = {}
    counts = {}
    with src.open('r', encoding='utf-8', newline='') as handle:
        reader = csv.DictReader(handle)
        for row in reader:
            month = month_from_row(row)
            if not month:
                continue
            path = archive_dir / f'elexon_generation_sources_{month}.csv'
            if path not in buckets:
                fh = path.open('w', encoding='utf-8', newline='')
                writer = csv.DictWriter(fh, fieldnames=FIELDS)
                writer.writeheader()
                buckets[path] = (fh, writer)
                counts[path] = 0
            buckets[path][1].writerow({field: row.get(field, '') for field in FIELDS})
            counts[path] += 1

    for fh, _writer in buckets.values():
        fh.close()

    outputs = sorted(counts)
    for path in outputs:
        print(f'Wrote {counts[path]} rows to {path}')
    return outputs


def main():
    year = sys.argv[1] if len(sys.argv) > 1 else None
    if not year:
        raise SystemExit('Usage: python scripts/split_generation_sources_year_to_months_v6.py YEAR')
    split_year(year)


if __name__ == '__main__':
    main()