In this section
- GlobalGrid2050 Backfill Generation Sources Year V6 energy-data · globalgrid2050 / scripts/backfill_generation_sources_year_v6.py lines 1–259
- GlobalGrid2050 Build Generation Daily Fuelhh Browser Slim energy-data · globalgrid2050 / scripts/build_generation_daily_fuelhh_browser_slim.py lines 1–181
- GlobalGrid2050 Build Generation Daily MW Spine energy-data · globalgrid2050 / scripts/build_generation_daily_mw_spine.py lines 1–217
GlobalGrid2050 Backfill Generation Sources Year V6
A Python command-line tool in the scripts folder that fetches Elexon generation sources year and solar from Elexon Balancing Mechanism Reporting Service (BMRS).
energy-dataglobalgrid2050 / scripts/backfill_generation_sources_year_v6.py · lines 1–259 of 259 · Entry point · pattern fetch_elexon_day (shared by 2 files)
- What it does
- It fetches Elexon generation sources year and solar. Defines 15 functions or classes, including utc_now, iso_z, pick, num, http_json. Uses libraries csv, datetime, json, os, sys. Side effects: reads or writes files; makes network requests.
- 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. Domain terms in the code: solar.
- Inputs & outputs
- In: data source: Elexon BMRS; CSV file elexon_generation_sources_YEAR.csv; command-line arguments.
- Downstream impact
- Used directly by 9 files: GlobalGrid2050 Backfill Generation Aggregates Year V6 (globalgrid2050); GlobalGrid2050 Backfill Generation Clean Halfhourly Month V6 (globalgrid2050); GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (globalgrid2050); GlobalGrid2050 Update Generation Recent MW V6 (globalgrid2050); and 5 more. Reached from 8 other entry points, including GlobalGrid2050 Backfill Generation Aggregates Manual V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Aggregates Sequence V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Clean Halfhourly Month V6 Workflow (globalgrid2050).
- What it achieves
- It extracts rows (`extract_rows`), fetches Elexon day (`fetch_elexon_day`) and parses pvlive row (`parse_pvlive_row`). Defines `utc_now`, `iso_z`, `pick` and 11 more.
- Why it matters
- Imported by GlobalGrid2050 Backfill Generation Aggregates Year V6, GlobalGrid2050 Backfill Generation Clean Halfhourly Month V6 and GlobalGrid2050 Update Generation Recent MW V6. Run by 5 workflows and scripts, including GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit, GlobalGrid2050 Backfill Generation Sources Decade V6 Workflow and GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow. Checked by GlobalGrid2050 Auto Test Generation Sources 2026 V6 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, datetime, json, os, sys, time, urllib.parse, urllib.request
- Used by
- imported by GlobalGrid2050 Backfill Generation Aggregates Year V6 (import), imported by GlobalGrid2050 Backfill Generation Clean Halfhourly Month V6 (import), run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (script call), imported by GlobalGrid2050 Update Generation Recent MW V6 (import), run by GlobalGrid2050 Auto Test Generation Sources 2026 V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Decade V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (workflow run), and 1 more
- Produces
- utc_now, iso_z, pick, num, http_json, extract_rows, elexon_url, fetch_elexon_day, pvlive_candidate_urls, parse_pvlive_row, fetch_pvlive_day, load_existing_year
- Defines here
- utc_now, iso_z, pick, num, http_json, extract_rows, elexon_url, fetch_elexon_day, pvlive_candidate_urls, parse_pvlive_row, fetch_pvlive_day, load_existing_year, write_year, write_report, 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/backfill_generation_sources_year_v6.py:1-259 · blob 5b3e3adf639fb7cd5c7dc2b45a17b31f46354f38 · 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 csv
import datetime as dt
import json
import os
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
ELEXON_FUELINST = "https://data.elexon.co.uk/bmrs/api/v1/datasets/FUELINST"
PVLIVE_GSP0 = "https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0"
OUT_DIR = Path("data/generation")
REPORT_DIR = Path("uk_energy_tracking_v6/generation_history/backfill_reports")
FIELDS = ["source", "periodStartUTC", "fuelType", "generationMW", "publishTimeUTC", "fetchedAtUTC"]
def utc_now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def iso_z(value):
if not value:
return ""
text = str(value).replace("Z", "+00:00")
try:
parsed = dt.datetime.fromisoformat(text)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
return parsed.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
except Exception:
return str(value)
def pick(row, names):
folded = {str(k).lower(): v for k, v in row.items()}
for name in names:
value = folded.get(name.lower())
if value not in (None, ""):
return value
return ""
def num(value):
if value in (None, ""):
return None
try:
return f"{float(value):.3f}"
except Exception:
return None
def http_json(url):
req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
with urllib.request.urlopen(req, timeout=60) as response:
return json.loads(response.read().decode("utf-8"))
def extract_rows(payload):
if isinstance(payload, list):
return payload
if isinstance(payload, dict):
for key in ("data", "results", "items"):
if isinstance(payload.get(key), list):
return payload[key]
return []
def elexon_url(start_dt, end_dt):
query = urllib.parse.urlencode({
"publishDateTimeFrom": start_dt.strftime("%Y-%m-%dT%H:%MZ"),
"publishDateTimeTo": end_dt.strftime("%Y-%m-%dT%H:%MZ"),
"format": "json",
})
return f"{ELEXON_FUELINST}?{query}"
def fetch_elexon_day(day):
start_dt = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
end_dt = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
payload = http_json(elexon_url(start_dt, end_dt))
fetched = utc_now()
output = []
for row in extract_rows(payload):
if not isinstance(row, dict):
continue
fuel = pick(row, ["fuelType", "fuelTypeName", "fuel", "psrType"])
generation = pick(row, ["generation", "generationMW", "currentUsage", "quantity"])
period_start = pick(row, ["startTime", "publishDateTime", "periodStartUTC", "settlementDate"])
publish_time = pick(row, ["publishDateTime", "publishTime", "createdTime"])
generation_mw = num(generation)
if not fuel or generation_mw is None or not period_start:
continue
output.append({
"source": "Elexon BMRS FUELINST",
"periodStartUTC": iso_z(period_start),
"fuelType": str(fuel).strip().upper(),
"generationMW": generation_mw,
"publishTimeUTC": iso_z(publish_time),
"fetchedAtUTC": fetched,
})
return output
def pvlive_candidate_urls(start_dt, end_dt):
start_iso = start_dt.isoformat().replace("+00:00", "Z")
end_iso = end_dt.isoformat().replace("+00:00", "Z")
start_plain = start_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
end_plain = end_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
start_date = start_dt.date().isoformat()
end_date = end_dt.date().isoformat()
candidates = [
{"start": start_iso, "end": end_iso},
{"start": start_plain, "end": end_plain},
{"from": start_iso, "to": end_iso},
{"datetime_from": start_iso, "datetime_to": end_iso},
{"start_date": start_date, "end_date": end_date},
]
return [PVLIVE_GSP0 + "?" + urllib.parse.urlencode(params) for params in candidates]
def parse_pvlive_row(row, fetched):
if isinstance(row, list):
if len(row) < 3:
return None
timestamp = row[1]
generation = row[2]
elif isinstance(row, dict):
timestamp = row.get("datetime_gmt") or row.get("datetime") or row.get("time") or row.get("timestamp") or row.get("periodStartUTC")
generation = row.get("generation_mw") or row.get("generationMW") or row.get("generation") or row.get("power")
else:
return None
generation_mw = num(generation)
period_start = iso_z(timestamp)
if not period_start or generation_mw is None:
return None
return {
"source": "Sheffield Solar PVLive",
"periodStartUTC": period_start,
"fuelType": "SOLAR",
"generationMW": generation_mw,
"publishTimeUTC": "",
"fetchedAtUTC": fetched,
}
def fetch_pvlive_day(day):
start_dt = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
end_dt = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
errors = []
for url in pvlive_candidate_urls(start_dt, end_dt):
try:
payload = http_json(url)
fetched = utc_now()
rows = []
for row in extract_rows(payload):
parsed = parse_pvlive_row(row, fetched)
if parsed:
rows.append(parsed)
if rows:
return rows, "ok", url
except Exception as exc:
errors.append(str(exc))
return [], "; ".join(errors[-2:]) or "no parseable PVLive rows", ""
def load_existing_year(year):
path = OUT_DIR / f"elexon_generation_sources_{year}.csv"
if not path.exists():
return {}
rows = {}
with path.open("r", encoding="utf-8", newline="") as handle:
for row in csv.DictReader(handle):
key = (row.get("periodStartUTC", ""), row.get("fuelType", ""))
if key[0] and key[1]:
rows[key] = {field: row.get(field, "") for field in FIELDS}
return rows
def write_year(year, rows_by_key):
OUT_DIR.mkdir(parents=True, exist_ok=True)
path = OUT_DIR / f"elexon_generation_sources_{year}.csv"
rows = [rows_by_key[key] for key in sorted(rows_by_key, key=lambda x: (x[0], x[1]))]
with path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(rows)
return path, len(rows)
def write_report(year, start_day, end_day, elexon_rows, solar_rows, total_rows, solar_status, solar_url):
REPORT_DIR.mkdir(parents=True, exist_ok=True)
report = REPORT_DIR / f"GENERATION_HISTORY_BACKFILL_{year}.md"
report.write_text("\n".join([
f"# Generation History Backfill {year}",
"",
f"Updated UTC: {utc_now()}",
f"Year: {year}",
f"Window: {start_day} to {end_day}",
f"Elexon rows fetched this run: {elexon_rows}",
f"PVLive solar rows fetched this run: {solar_rows}",
f"Annual rows after merge: {total_rows}",
f"PVLive status: {solar_status}",
f"PVLive working URL sample: {solar_url or 'not confirmed'}",
"Sources: Elexon BMRS FUELINST and Sheffield Solar PVLive where available",
"Output: data/generation/elexon_generation_sources_YEAR.csv",
]) + "\n", encoding="utf-8")
return report
def main():
year = int(os.getenv("YEAR") or (sys.argv[1] if len(sys.argv) > 1 else dt.datetime.now(dt.timezone.utc).year))
include_solar = os.getenv("INCLUDE_SOLAR", "true").lower() not in ("0", "false", "no")
current_year = dt.datetime.now(dt.timezone.utc).year
current_date = dt.datetime.now(dt.timezone.utc).date()
start_day = dt.date(year, 1, 1)
end_day = dt.date(year, 12, 31)
if year == current_year:
end_day = min(end_day, current_date - dt.timedelta(days=1))
if end_day < start_day:
print(f"No complete days available for {year}")
return
rows_by_key = load_existing_year(year)
elexon_count = 0
solar_count = 0
solar_status = "not requested"
solar_url = ""
day = start_day
while day <= end_day:
try:
rows = fetch_elexon_day(day)
elexon_count += len(rows)
for row in rows:
rows_by_key[(row["periodStartUTC"], row["fuelType"])] = row
print(f"{year} {day}: Elexon {len(rows)} rows")
except Exception as exc:
print(f"Warning {year} {day}: Elexon failed: {exc}")
if include_solar:
rows, status, url = fetch_pvlive_day(day)
if url and not solar_url:
solar_url = url
if rows:
solar_status = "ok"
elif solar_status != "ok":
solar_status = status
solar_count += len(rows)
for row in rows:
rows_by_key[(row["periodStartUTC"], row["fuelType"])] = row
print(f"{year} {day}: PVLive solar {len(rows)} rows")
day += dt.timedelta(days=1)
time.sleep(0.05)
path, total = write_year(year, rows_by_key)
report = write_report(year, start_day, end_day, elexon_count, solar_count, total, solar_status, solar_url)
print(f"Wrote {total} rows to {path}")
print(f"Wrote report {report}")
if __name__ == "__main__":
main()GlobalGrid2050 Build Generation Daily Fuelhh Browser Slim
A Python command-line tool in the scripts folder that reads generation daily mw spine fuelhh candidate and solar, using SHA-256.
energy-dataglobalgrid2050 / scripts/build_generation_daily_fuelhh_browser_slim.py · lines 1–181 of 181 · Entry point · pattern write_payload (shared by 2 files)
- What it does
- It loads generation daily mw spine fuelhh candidate and solar. Defines 9 functions or classes, including utc_now, stamp, rel, load_rows, slim_row. Uses libraries __future__, argparse, datetime, hashlib, json. 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. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file generation_daily_mw_spine_fuelhh_candidate.json; JSON file generation_daily_fuelhh_browser_slim.json; JSON file FUELHH_BROWSER_SLIM_LATEST.json; JSON file generation_daily_fuelhh_browser_slim.manifest.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Build Generation Fuelhh Browser Slim Workflow (globalgrid2050).
- What it achieves
- It loads rows (`load_rows`), writes payload (`write_payload`) and writes reports (`write_reports`). Title: Build Generation Daily FUELHH Browser Slim File Date UTC: 2026 06 09 Executive summary: Derives a compact browser safe daily MW payload from the canonical FUELHH candidate spine while preserving the full provenance rich spine as the audit source. It accepts `--input`, `--output` and `--max-bytes`.
- Why it matters
- Run by GlobalGrid2050 Build Generation Fuelhh Browser Slim Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, pathlib, typing
- Used by
- run by GlobalGrid2050 Build Generation Fuelhh Browser Slim Workflow (workflow run)
- Produces
- utc_now, stamp, rel, load_rows, slim_row, build, write_payload, write_reports, main
- Defines here
- utc_now, stamp, rel, load_rows, slim_row, build, write_payload, write_reports, 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/build_generation_daily_fuelhh_browser_slim.py:1-181 · blob 5200c0727f0380ea86858c3a499223d2a59f52bd · 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
"""
Title: Build Generation Daily FUELHH Browser Slim File
Date UTC: 2026 06 09
Executive summary: Derives a compact browser safe daily MW payload from the canonical
FUELHH candidate spine while preserving the full provenance rich spine as the audit source.
Design rule:
The canonical file remains data/confirmed/generation_daily_mw_spine_fuelhh_candidate.json.
The browser file is uk_energy_tracking_v6/generation_history/generation_daily_fuelhh_browser_slim.json.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_INPUT = ROOT / "data" / "confirmed" / "generation_daily_mw_spine_fuelhh_candidate.json"
DEFAULT_OUTPUT = ROOT / "uk_energy_tracking_v6" / "generation_history" / "generation_daily_fuelhh_browser_slim.json"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
MANIFEST_DIR = ROOT / "uk_energy_tracking_v6" / "generation_history" / "manifests"
KEEP_FIELDS = (
"date",
"technology",
"averageMW",
"highMW",
"lowMW",
"highAtUTC",
"lowAtUTC",
)
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def stamp() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def rel(path: Path) -> str:
return path.relative_to(ROOT).as_posix()
def load_rows(path: Path) -> list[dict[str, Any]]:
if not path.exists():
raise FileNotFoundError(f"Input file not found: {rel(path)}")
payload = json.loads(path.read_text(encoding="utf-8"))
if isinstance(payload, dict) and isinstance(payload.get("rows"), list):
rows = payload["rows"]
elif isinstance(payload, list):
rows = payload
else:
raise ValueError("Input JSON must be either a list or an object with a rows list")
if not all(isinstance(row, dict) for row in rows):
raise ValueError("Every row must be a JSON object")
return rows
def slim_row(row: dict[str, Any]) -> dict[str, Any]:
out: dict[str, Any] = {}
for key in KEEP_FIELDS:
if key in row and row[key] is not None:
out[key] = row[key]
if "date" not in out or "technology" not in out or "averageMW" not in out:
raise ValueError(f"Required field missing in row: {row}")
return out
def build(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
slim = [slim_row(row) for row in rows]
slim.sort(key=lambda row: (str(row.get("date", "")), str(row.get("technology", ""))))
seen: set[tuple[str, str]] = set()
duplicates: list[tuple[str, str]] = []
for row in slim:
key = (str(row.get("date", "")), str(row.get("technology", "")))
if key in seen:
duplicates.append(key)
seen.add(key)
if duplicates:
raise ValueError(f"Duplicate daily technology rows found: {duplicates[:5]}")
return slim
def write_payload(output: Path, rows: list[dict[str, Any]], source: Path) -> tuple[int, str]:
output.parent.mkdir(parents=True, exist_ok=True)
payload = {
"schemaVersion": "0.1.0-fuelhh-browser-slim",
"generatedUTC": utc_now(),
"title": "Generation daily MW FUELHH browser slim file",
"grain": "daily average high low MW per technology",
"timezone": "UTC",
"sourcePath": rel(source),
"sourceNote": "Derived from Elexon BMRS FUELHH candidate spine. Embedded distribution generation is not added here.",
"rows": rows,
}
text = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
output.write_text(text, encoding="utf-8")
sha = hashlib.sha256(text.encode("utf-8")).hexdigest()
return output.stat().st_size, sha
def write_reports(report: dict[str, Any], manifest_path: Path) -> None:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
MANIFEST_DIR.mkdir(parents=True, exist_ok=True)
s = stamp()
md = "\n".join([
"# GlobalGrid2050 FUELHH Browser Slim Build Report",
"",
f"Generated UTC: `{report['generatedUTC']}`",
f"Input path: `{report['inputPath']}`",
f"Output path: `{report['outputPath']}`",
f"Input rows: `{report['inputRows']}`",
f"Output rows: `{report['outputRows']}`",
f"Output size bytes: `{report['outputSizeBytes']}`",
f"SHA 256: `{report['sha256']}`",
"",
"## Executive summary",
"",
"This build creates the browser safe historic daily MW file from the full FUELHH candidate spine. The full spine remains the canonical audit file. The browser file keeps only the fields needed by the chart.",
"",
"## Source warning",
"",
"FUELHH is transmission metered generation. It must not be represented as complete national solar output until an embedded solar layer is added.",
]) + "\n"
for path in (REPORT_DIR / f"FUELHH_BROWSER_SLIM_{s}.md", REPORT_DIR / "FUELHH_BROWSER_SLIM_LATEST.md"):
path.write_text(md, encoding="utf-8")
js = json.dumps(report, indent=2, ensure_ascii=False) + "\n"
for path in (REPORT_JSON_DIR / f"FUELHH_BROWSER_SLIM_{s}.json", REPORT_JSON_DIR / "FUELHH_BROWSER_SLIM_LATEST.json", manifest_path):
path.write_text(js, encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--input", default=str(DEFAULT_INPUT))
parser.add_argument("--output", default=str(DEFAULT_OUTPUT))
parser.add_argument("--max-bytes", type=int, default=3_000_000)
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
input_path = (ROOT / args.input).resolve() if not Path(args.input).is_absolute() else Path(args.input)
output_path = (ROOT / args.output).resolve() if not Path(args.output).is_absolute() else Path(args.output)
rows = load_rows(input_path)
slim = build(rows)
if args.apply:
output_size, sha = write_payload(output_path, slim, input_path)
else:
text = json.dumps({"rows": slim}, separators=(",", ":"), ensure_ascii=False)
output_size = len(text.encode("utf-8"))
sha = hashlib.sha256(text.encode("utf-8")).hexdigest()
if output_size > args.max_bytes:
raise SystemExit(f"Slim browser file is too large: {output_size} bytes above {args.max_bytes}")
report = {
"generatedUTC": utc_now(),
"mode": "apply" if args.apply else "audit only",
"inputPath": rel(input_path),
"outputPath": rel(output_path),
"inputRows": len(rows),
"outputRows": len(slim),
"outputSizeBytes": output_size,
"sha256": sha,
"maxBytes": args.max_bytes,
"keptFields": list(KEEP_FIELDS),
}
manifest_path = MANIFEST_DIR / "generation_daily_fuelhh_browser_slim.manifest.json"
write_reports(report, manifest_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())GlobalGrid2050 Build Generation Daily MW Spine
A Python command-line tool in the scripts folder that parses time (`parse_time`), reads rows (`read_rows`) and writes report (`write_report`) (units: MW), covering generation daily mw spine candidate, wind and solar.
energy-dataglobalgrid2050 / scripts/build_generation_daily_mw_spine.py · lines 1–217 of 217 · Entry point · pattern build_spine (shared by 3 files)
- What it does
- Defines 9 functions or classes, including utc_now, stamp, group_for, parse_time, read_rows. Uses libraries __future__, argparse, csv, datetime, json. 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. Domain terms in the code: wind, solar.
- Inputs & outputs
- In: JSON file generation_daily_mw_spine_candidate.json; JSON file GENERATION_DAILY_MW_SPINE_LATEST.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Overnight Generation MW Backfill Workflow (globalgrid2050).
- What it achieves
- It builds spine (`build_spine`) and is built from the utc now helper (`utc_now`) and the stamp step (`stamp`). Reads staged generation MW source files and produces compact daily average, high and low MW facts per technology. It accepts `--years` and `--apply`.
- Why it matters
- Run by GlobalGrid2050 Overnight Generation MW Backfill Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, csv, datetime, json, math, collections, pathlib
- Used by
- run by GlobalGrid2050 Overnight Generation MW Backfill Workflow (workflow run)
- Produces
- utc_now, stamp, group_for, parse_time, read_rows, build_spine, write_json, write_report, main
- Defines here
- utc_now, stamp, group_for, parse_time, read_rows, build_spine, write_json, write_report, 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/build_generation_daily_mw_spine.py:1-217 · blob 43d541d75c79b25a5d286668309db7f4aa24f5cb · 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
"""
GlobalGrid2050 daily MW spine builder.
Reads staged generation MW source files and produces compact daily average, high
and low MW facts per technology. This is the browser friendly 10 year shape.
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import json
import math
from collections import defaultdict
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
STAGE_ROOT = ROOT / "data" / "generation" / "staged_mw"
OUT_DIR = ROOT / "data" / "confirmed"
OUT_FILE = OUT_DIR / "generation_daily_mw_spine_candidate.json"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
TECH_MAP = {
"SOLAR": "Solar",
"PV": "Solar",
"WIND": "Wind",
"WIND OFFSHORE": "Wind",
"WIND ONSHORE": "Wind",
"NPSHYD": "Hydro",
"HYDRO": "Hydro",
"CCGT": "Gas",
"OCGT": "Gas",
"GAS": "Gas",
"COAL": "Coal",
"BIOMASS": "Biomass",
"NUCLEAR": "Nuclear",
"PS": "Pumped Storage",
}
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def stamp() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def group_for(fuel: str) -> str:
f = str(fuel or "").strip().upper()
if f.startswith("INT"):
return "Imports & Exports"
for key, value in TECH_MAP.items():
if f.startswith(key):
return value
return "Other"
def parse_time(value: str) -> dt.datetime | None:
if not value:
return None
try:
text = value.replace("Z", "+00:00")
parsed = dt.datetime.fromisoformat(text)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
return parsed.astimezone(dt.timezone.utc)
except Exception:
return None
def read_rows(years: list[int] | None) -> tuple[dict[tuple[str, str], list[dict[str, Any]]], dict[str, Any]]:
buckets: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
files = []
if years:
for year in years:
files.extend(sorted((STAGE_ROOT / str(year)).glob("*.csv")))
else:
files = sorted(STAGE_ROOT.glob("*/*.csv"))
source_files = []
raw_rows = 0
parsed_rows = 0
for path in files:
file_rows = 0
with path.open("r", encoding="utf-8", newline="") as handle:
for row in csv.DictReader(handle):
raw_rows += 1
file_rows += 1
t = parse_time(row.get("periodStartUTC", ""))
try:
mw = float(row.get("generationMW", ""))
except Exception:
continue
if t is None or not math.isfinite(mw):
continue
tech = group_for(row.get("fuelType", ""))
key = (t.date().isoformat(), tech)
buckets[key].append({
"time": t.isoformat().replace("+00:00", "Z"),
"mw": mw,
"sourceStatus": row.get("sourceStatus") or "candidate",
"sourceLineage": row.get("sourceLineage") or row.get("source") or "unknown",
})
parsed_rows += 1
source_files.append({"path": path.relative_to(ROOT).as_posix(), "rows": file_rows, "sizeBytes": path.stat().st_size})
return buckets, {"files": source_files, "rawRows": raw_rows, "parsedRows": parsed_rows}
def build_spine(buckets: dict[tuple[str, str], list[dict[str, Any]]]) -> list[dict[str, Any]]:
out = []
for (date, tech), rows in sorted(buckets.items()):
if not rows:
continue
vals = [float(r["mw"]) for r in rows]
hi = max(rows, key=lambda r: float(r["mw"]))
lo = min(rows, key=lambda r: float(r["mw"]))
lineage = sorted({str(r.get("sourceLineage") or "unknown") for r in rows})
statuses = sorted({str(r.get("sourceStatus") or "candidate") for r in rows})
expected = 48
completeness = round(min(1.0, len(rows) / expected), 4)
out.append({
"date": date,
"technology": tech,
"averageMW": round(sum(vals) / len(vals), 3),
"highMW": round(float(hi["mw"]), 3),
"lowMW": round(float(lo["mw"]), 3),
"highAtUTC": hi["time"],
"lowAtUTC": lo["time"],
"sampleCount": len(rows),
"expectedSamples": expected,
"completeness": completeness,
"status": "candidate",
"sourceStatus": "+".join(statuses),
"sourceLineage": "; ".join(lineage),
})
return out
def write_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def write_report(payload: dict[str, Any]) -> None:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
s = stamp()
md = REPORT_DIR / f"GENERATION_DAILY_MW_SPINE_{s}.md"
js = REPORT_JSON_DIR / f"GENERATION_DAILY_MW_SPINE_{s}.json"
latest_md = REPORT_DIR / "GENERATION_DAILY_MW_SPINE_LATEST.md"
latest_js = REPORT_JSON_DIR / "GENERATION_DAILY_MW_SPINE_LATEST.json"
lines = [
"# GlobalGrid2050 Daily MW Spine Report",
"",
f"Generated UTC: `{payload['generatedUTC']}`",
f"Mode: `{payload['mode']}`",
f"Years: `{', '.join(map(str, payload['years'])) if payload['years'] else 'all staged years'}`",
f"Source files: `{len(payload['sourceFiles'])}`",
f"Raw rows: `{payload['rawRows']}`",
f"Parsed rows: `{payload['parsedRows']}`",
f"Daily fact rows: `{payload['dailyRows']}`",
f"Output path: `{payload['outputPath']}`",
f"Output size bytes: `{payload['outputSizeBytes']}`",
"",
"## Source discipline",
"",
"Daily average, high and low MW are candidate facts. High and low are not additive. MWh rollups must be built separately from interval energy.",
]
text = "\n".join(lines) + "\n"
for path in (md, latest_md):
path.write_text(text, encoding="utf-8")
js_text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
for path in (js, latest_js):
path.write_text(js_text, encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--years", default="", help="Comma separated years. Empty means all staged years.")
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
years = [int(x.strip()) for x in args.years.split(",") if x.strip()] or None
buckets, meta = read_rows(years)
rows = build_spine(buckets)
out_payload = {
"schemaVersion": "0.1.0-candidate",
"generatedUTC": utc_now(),
"title": "Generation daily MW spine candidate",
"timezone": "UTC",
"status": "candidate",
"grain": "daily average high low MW per technology",
"sourceNote": "Built from staged source rows. FUELINST lineage is provisional. PVLive solar lineage is candidate embedded estimate.",
"rows": rows,
}
if args.apply:
write_json(OUT_FILE, out_payload)
payload = {
"generatedUTC": utc_now(),
"mode": "apply" if args.apply else "audit only",
"years": years or [],
"sourceFiles": meta["files"],
"rawRows": meta["rawRows"],
"parsedRows": meta["parsedRows"],
"dailyRows": len(rows),
"outputPath": OUT_FILE.relative_to(ROOT).as_posix(),
"outputSizeBytes": OUT_FILE.stat().st_size if OUT_FILE.exists() else 0,
}
write_report(payload)
return 0
if __name__ == "__main__":
raise SystemExit(main())