GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / scripts

GlobalGrid2050 Create V8 Battery Energy Storage System (BESS) Pcs Standalone and 2 more files

A Python command-line tool in the scripts folder that reads battery storage (BESS), solar and cables, using IEC 60287.

681 lines of Python from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 64 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 Create V8 Battery Energy Storage System (BESS) Pcs Standalone interaction · globalgrid2050 / scripts/create_v8_bess_pcs_standalone.py lines 1–267
  2. GlobalGrid2050 Download Pvlive Solar History energy-data · globalgrid2050 / scripts/download_pvlive_solar_history.py lines 1–200
  3. GlobalGrid2050 Fetch Pvlive Solar Candidate V6 energy-data · globalgrid2050 / scripts/fetch_pvlive_solar_candidate_v6.py lines 1–214

GlobalGrid2050 Create V8 Battery Energy Storage System (BESS) Pcs Standalone

A Python command-line tool in the scripts folder that reads battery storage (BESS), solar and cables, using IEC 60287.

interactionglobalgrid2050 / scripts/create_v8_bess_pcs_standalone.py · lines 1–267 of 267 · Entry point · pattern patch_index (shared by 15 files)

What it does
It loads battery storage (BESS), solar and cables. Defines 6 functions or classes, including ensure_source, copy_app, patch_index, write_v8_launcher, write_report. Uses libraries __future__, datetime, shutil, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: battery storage (BESS), solar, cables.
Inputs & outputs
In: form fields (user input).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Create V8 Battery Energy Storage System (BESS) Pcs Standalone Workflow (globalgrid2050).
What it achieves
It copies app (`copy_app`), patches index (`patch_index`) and writes v8 launcher (`write_v8_launcher`). Create V8 BESS PCS standalone study app from stable V7 GIS single-line diagram (SLD) sandbox.
Why it matters
Run by GlobalGrid2050 Create V8 Battery Energy Storage System (BESS) Pcs Standalone Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, shutil, pathlib
Used by
run by GlobalGrid2050 Create V8 Battery Energy Storage System (BESS) Pcs Standalone Workflow (workflow run)
Produces
ensure_source, copy_app, patch_index, write_v8_launcher, write_report, main
Defines here
ensure_source, copy_app, patch_index, write_v8_launcher, 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/create_v8_bess_pcs_standalone.py:1-267 · blob 496f9b6f72bc6eb62892c25d01e89f3bfb873791 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Create V8 BESS PCS standalone study app from stable V7 GIS SLD sandbox.

This script is intentionally conservative:
- It does not modify V7.
- It copies the V7 GIS SLD sandbox into a new V8 BESS folder.
- It renames the copied app and adds a simple BESS to PCS screening panel.
- It writes a V8 launcher, README and GridBot report.
"""

from __future__ import annotations

import datetime as dt
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox"
V8 = ROOT / "solar-bess-topology-v8"
DEST = V8 / "bess-pcs-standalone"
REPORT = ROOT / "gridbot_reports" / "create_v8_bess_pcs_standalone.md"

REQUIRED = [
    "index.html",
    "gis-sld-v5.css",
    "gis-sld-v5-config.js",
    "gis-sld-v5-helpers.js",
    "gis-sld-v5-state.js",
    "gis-sld-v5-substations.js",
    "gis-sld-v5-map.js",
    "gis-sld-v5-calculations.js",
    "gis-sld-v5-finance.js",
    "gis-sld-v5-ui-core.js",
    "gis-sld-v5-drawing.js",
    "gis-sld-v5-export.js",
    "gis-sld-v5-ui.js",
]


def ensure_source() -> None:
    missing = [name for name in REQUIRED if not (SRC / name).exists()]
    if missing:
        raise SystemExit("Missing V7 source files: " + ", ".join(missing))


def copy_app() -> None:
    DEST.mkdir(parents=True, exist_ok=True)
    for name in REQUIRED:
        shutil.copy2(SRC / name, DEST / name)


def patch_index() -> None:
    index = DEST / "index.html"
    text = index.read_text(encoding="utf-8")

    text = text.replace(
        "<title>GIS SLD Financial Sandbox V7</title>",
        "<title>BESS PCS Standalone V8</title>",
    )
    text = text.replace(
        "Solar Photovoltaic (PV) Development, Engineering, Procurement and Construction (EPC) and Grid Analysis",
        "BESS PCS Standalone Study V8",
        1,
    )

    bess_panel = """

    <div class="stat-box" id="bess_pcs_study_box">
        <h3>BESS to PCS Screening</h3>
        <div class="ux-note">Standalone V8 study panel for the DC link between a battery energy storage system and power conversion system. This is a screening tool only. Formal cable sizing requires project specific thermal study, installation data and protection review.</div>
        <div class="input-group"><label>BESS Power (MW)</label><input type="number" id="bess_power_mw" value="50" step="1" min="0" /></div>
        <div class="input-group"><label>DC Voltage (V)</label><input type="number" id="bess_dc_voltage" value="1500" step="50" min="1" /></div>
        <div class="input-group"><label>Parallel DC Cable Sets</label><input type="number" id="bess_parallel_sets" value="10" step="1" min="1" /></div>
        <div class="input-group"><label>Route Length (m)</label><input type="number" id="bess_route_length_m" value="30" step="1" min="0" /></div>
        <div class="input-group"><label>Conductor Size (mm2)</label><input type="number" id="bess_conductor_mm2" value="300" step="1" min="1" /></div>
        <div class="input-group">
            <label>Installation Basis</label>
            <select id="bess_installation_basis">
                <option value="buried">Direct buried or ducted underground</option>
                <option value="trench">Open trench or trough</option>
                <option value="ladder">Ladder or free air section</option>
                <option value="unknown">Unknown, study required</option>
            </select>
        </div>
        <div class="stat-row"><span>Total DC Current:</span><span class="stat-val cyan" id="bess_out_total_current">0 A</span></div>
        <div class="stat-row"><span>Current per Cable Set:</span><span class="stat-val cyan" id="bess_out_set_current">0 A</span></div>
        <div class="stat-row"><span>Study Flag:</span><span class="stat-val orange" id="bess_out_study_flag">Formal thermal study required</span></div>
    </div>
"""

    marker = "    <div class=\"tab-container\">"
    if bess_panel not in text:
        if marker not in text:
            raise SystemExit("Could not find tab container marker in copied V8 index.html")
        text = text.replace(marker, bess_panel + "\n" + marker, 1)

    bess_script = """
<script>
function updateBessPcsStudy() {
    const powerMw = parseFloat(document.getElementById('bess_power_mw')?.value || '0');
    const voltage = parseFloat(document.getElementById('bess_dc_voltage')?.value || '0');
    const sets = Math.max(1, parseFloat(document.getElementById('bess_parallel_sets')?.value || '1'));
    const lengthM = parseFloat(document.getElementById('bess_route_length_m')?.value || '0');
    const installation = document.getElementById('bess_installation_basis')?.value || 'unknown';
    const totalCurrent = voltage > 0 ? (powerMw * 1000000) / voltage : 0;
    const setCurrent = totalCurrent / sets;
    const totalOut = document.getElementById('bess_out_total_current');
    const setOut = document.getElementById('bess_out_set_current');
    const flagOut = document.getElementById('bess_out_study_flag');
    if (totalOut) totalOut.textContent = Math.round(totalCurrent).toLocaleString() + ' A';
    if (setOut) setOut.textContent = Math.round(setCurrent).toLocaleString() + ' A';
    if (flagOut) {
        if (!powerMw || !voltage || installation === 'unknown') {
            flagOut.textContent = 'Input or installation assumption incomplete';
        } else if (setCurrent > 300 || lengthM > 100) {
            flagOut.textContent = 'Formal IEC 60287 or equivalent thermal study required';
        } else {
            flagOut.textContent = 'Screening only, engineering review still required';
        }
    }
}
['bess_power_mw','bess_dc_voltage','bess_parallel_sets','bess_route_length_m','bess_conductor_mm2','bess_installation_basis'].forEach(function(id) {
    document.addEventListener('input', function(event) {
        if (event.target && event.target.id === id) updateBessPcsStudy();
    });
    document.addEventListener('change', function(event) {
        if (event.target && event.target.id === id) updateBessPcsStudy();
    });
});
document.addEventListener('DOMContentLoaded', updateBessPcsStudy);
</script>
"""

    if "function updateBessPcsStudy" not in text:
        text = text.replace("\n</body>", "\n" + bess_script + "\n</body>", 1)

    index.write_text(text, encoding="utf-8")


def write_v8_launcher() -> None:
    V8.mkdir(parents=True, exist_ok=True)
    (V8 / "index.html").write_text("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GlobalGrid2050 V8</title>
<style>
:root { --bg:#050505; --panel:#0b0e14; --line:#2f343d; --text:#fff; --muted:#a6adbb; --accent:#00ffff; --ok:#00ff88; --danger:#ff3333; }
* { box-sizing:border-box; }
body { margin:0; padding:28px; background:var(--bg); color:var(--text); font-family:"Courier New", monospace; }
header, main { max-width:1180px; margin:0 auto 24px auto; }
header { border:1px solid var(--line); background:rgba(10,10,10,.96); padding:22px; border-radius:14px; }
.kicker { color:var(--accent); text-transform:uppercase; letter-spacing:.14em; font-size:12px; }
h1 { margin:8px 0 10px 0; font-size:28px; }
p { color:var(--muted); line-height:1.55; }
.card { display:block; border:1px solid var(--line); background:var(--panel); border-radius:14px; padding:20px; text-decoration:none; color:var(--text); max-width:460px; }
.card:hover { border-color:var(--accent); }
.card h2 { color:var(--accent); margin:0 0 10px 0; }
.card span { color:var(--ok); font-weight:bold; }
.warning { margin-top:14px; padding:14px; border:1px solid var(--danger); border-radius:10px; color:var(--danger); background:rgba(255,51,51,.08); font-weight:bold; }
</style>
</head>
<body>
<header>
<div class="kicker">GlobalGrid2050 V8</div>
<h1>BESS Standalone Study Workspace</h1>
<p>V8 starts as a standalone BESS to PCS study workspace. V7 is left as the stable solar and BESS GIS SLD release for now.</p>
<div class="warning">STATUS: TESTING AND DEVELOPMENT. Screening only. Formal cable, protection, thermal and grid studies remain required.</div>
</header>
<main>
<a class="card" href="./bess-pcs-standalone/index.html">
<h2>BESS PCS Standalone</h2>
<p>Standalone BESS to PCS DC link screening app copied from the V7 GIS SLD base for controlled study.</p>
<span>Open app</span>
</a>
</main>
</body>
</html>
""", encoding="utf-8")

    (V8 / "README.md").write_text("""# GlobalGrid2050 V8

V8 is the standalone BESS to PCS study workspace.

V7 is to remain stable for the combined solar and BESS GIS SLD release. V8 is where standalone BESS logic can be tested safely before any future V9 merge back into a unified Solar plus BESS UI.

## Current app

```text
solar-bess-topology-v8/bess-pcs-standalone/
```

## Doctrine

Geometry first.
Assumptions second.
Screening third.
Formal design only when verified.

## Scope

V8 starts with the BESS to PCS DC link only:

```text
BESS DC terminals -> parallel DC cable sets -> PCS DC input
```

The first screening logic converts BESS MW and DC voltage into total DC current, then divides that current by the number of parallel DC cable sets.

Formal IEC 60287 or equivalent thermal study remains required for real projects.

## V9 intention

V9 may merge solar and BESS into one UI after the standalone BESS logic is stable.
""", encoding="utf-8")


def write_report() -> None:
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text("""# Create V8 BESS PCS Standalone

Created a standalone V8 BESS to PCS study workspace.

## Source

Copied from:

```text
solar-bess-topology-v7/gis-sld-financial-sandbox/
```

## Destination

```text
solar-bess-topology-v8/bess-pcs-standalone/
```

## Purpose

Leave V7 stable and create a separate V8 app for BESS to PCS logic.

## First logic added

```text
BESS power MW / DC voltage = total DC current
Total DC current / parallel cable sets = current per cable set
```

## Next safe step

Test V8 standalone in the browser before removing any inherited solar UI sections.
""", encoding="utf-8")


def main() -> int:
    ensure_source()
    copy_app()
    patch_index()
    write_v8_launcher()
    write_report()
    print("Created V8 BESS PCS standalone workspace.")
    return 0


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

GlobalGrid2050 Download Pvlive Solar History

A Python command-line tool in the scripts folder that fetches Elexon generation sources half hourly and solar. It loads existing (`load_existing`) and writes CSV (`write_csv`).

energy-dataglobalgrid2050 / scripts/download_pvlive_solar_history.py · lines 1–200 of 200 · Entry point · pattern fetch_window (shared by 3 files)

What it does
It fetches Elexon generation sources half hourly and solar. Defines 12 functions or classes, including utc_now, iso_z, normalise_mw, load_existing, write_csv. Uses libraries csv, datetime, json, os, urllib.parse. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
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 `utc_now`, `iso_z`, `normalise_mw` and 8 more.
Why it matters
Run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, datetime, json, os, urllib.parse, urllib.request, pathlib
Used by
run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow (workflow run)
Produces
utc_now, iso_z, normalise_mw, load_existing, write_csv, http_json, extract_rows, parse_row, candidate_urls, fetch_window, write_report, main
Defines here
utc_now, iso_z, normalise_mw, load_existing, write_csv, http_json, extract_rows, parse_row, candidate_urls, fetch_window, 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/download_pvlive_solar_history.py:1-200 · blob d35fac569c34b5e9ed64f3649ec13ffa88b708ef · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
import csv
import datetime as dt
import json
import os
import urllib.parse
import urllib.request
from pathlib import Path

PVLIVE_URL = "https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0"
OUT_DIR = Path("data/generation")
OUT_FILE = OUT_DIR / "elexon_generation_sources_half_hourly.csv"
REPORT_DIR = Path("uk_energy_tracking_v6/generation_history")
REPORT = REPORT_DIR / "PVLIVE_SOLAR_HISTORY_REPORT.md"
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 normalise_mw(value):
    if value in (None, ""):
        return None
    try:
        return f"{float(value):.3f}"
    except Exception:
        return None


def load_existing():
    if not OUT_FILE.exists():
        return {}
    rows = {}
    with OUT_FILE.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_csv(rows_by_key):
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    rows = [rows_by_key[key] for key in sorted(rows_by_key, key=lambda x: (x[0], x[1]))]
    with OUT_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    return len(rows)


def http_json(url):
    req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
    with urllib.request.urlopen(req, timeout=45) 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 parse_row(row, fetched_at):
    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
    period_start = iso_z(timestamp)
    generation_mw = normalise_mw(generation)
    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_at,
    }


def 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_URL + "?" + urllib.parse.urlencode(params) for params in candidates]


def fetch_window(start_dt, end_dt):
    errors = []
    for url in candidate_urls(start_dt, end_dt):
        try:
            payload = http_json(url)
            parsed = []
            fetched_at = utc_now()
            for row in extract_rows(payload):
                item = parse_row(row, fetched_at)
                if item:
                    parsed.append(item)
            if parsed:
                return parsed, url, None
        except Exception as exc:
            errors.append(f"{url} :: {exc}")
    return [], "", "; ".join(errors[-3:])


def write_report(status, days, fetched_rows, total_rows, working_url, detail):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT.write_text("\n".join([
        "# PVLive Solar History Report",
        "",
        f"Updated UTC: {utc_now()}",
        f"Status: {status}",
        f"Backfill days requested: {days}",
        f"Fetched solar rows this run: {fetched_rows}",
        f"Total master rows after solar merge: {total_rows}",
        f"Working URL pattern: {working_url or 'not confirmed'}",
        f"Detail: {detail}",
        "Source: Sheffield Solar PVLive",
        "Output fuelType: SOLAR",
        "Module: uk_energy_tracking_v6/generation_history",
    ]) + "\n", encoding="utf-8")


def main():
    days = int(os.getenv("BACKFILL_DAYS", "14"))
    today = dt.datetime.now(dt.timezone.utc).date()
    start_day = today - dt.timedelta(days=max(days, 1))
    end_day = today - dt.timedelta(days=1)
    existing = load_existing()
    fetched_count = 0
    working_url = ""
    last_error = ""
    day = start_day
    while day <= end_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)
        rows, url, err = fetch_window(start_dt, end_dt)
        if url and not working_url:
            working_url = url.split("?")[0] + "?" + urllib.parse.urlencode({k: v for k, v in urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query)})
        if err:
            last_error = err
            print(f"Warning: PVLive failed {day}: {err}")
        print(f"Fetched {len(rows)} PVLive solar rows for {day}")
        fetched_count += len(rows)
        for row in rows:
            key = (row["periodStartUTC"], row["fuelType"])
            existing[key] = row
        day += dt.timedelta(days=1)
    total = write_csv(existing) if existing else 0
    status = "ok" if fetched_count > 0 else "no solar rows fetched"
    detail = "PVLive solar rows merged into generation master CSV" if fetched_count > 0 else last_error or "PVLive returned no parseable solar rows"
    write_report(status, days, fetched_count, total, working_url, detail)
    if fetched_count == 0:
        print("::warning::No PVLive solar rows fetched; report written and workflow continues")


if __name__ == "__main__":
    main()

GlobalGrid2050 Fetch Pvlive Solar Candidate V6

A Python command-line tool in the scripts folder that fetches pvlive solar daily candidate, using SHA-256. It extracts rows (`extract_rows`), parses power (`parse_power`) and parses pvlive row (`parse_pvlive_row`).

energy-dataglobalgrid2050 / scripts/fetch_pvlive_solar_candidate_v6.py · lines 1–214 of 214 · Entry point · pattern fetch_day (shared by 3 files)

What it does
It fetches pvlive solar daily candidate. Defines 12 functions or classes, including utc_now, iso_z, http_json, extract_rows, parse_power. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file pvlive_solar_daily_candidate.json; JSON file PVLIVE_SOLAR_CANDIDATE_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Step1 Fetch Pvlive Solar Candidate V6 Workflow (globalgrid2050).
What it achieves
Defines `utc_now`, `iso_z`, `http_json` and 8 more. It accepts `--days`.
Why it matters
Run by GlobalGrid2050 Step1 Fetch Pvlive Solar Candidate V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, urllib.parse, urllib.request, pathlib
Used by
run by GlobalGrid2050 Step1 Fetch Pvlive Solar Candidate V6 Workflow (workflow run)
Produces
utc_now, iso_z, http_json, extract_rows, parse_power, parse_pvlive_row, candidate_urls, fetch_day, load_existing, write_json, write_report, main
Defines here
utc_now, iso_z, http_json, extract_rows, parse_power, parse_pvlive_row, candidate_urls, fetch_day, load_existing, 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/fetch_pvlive_solar_candidate_v6.py:1-214 · blob 3dea779bb40a72193c06e1d83f76f91737ac3f4b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "data" / "confirmed" / "pvlive_solar_daily_candidate.json"
REPORT_MD = ROOT / "data_science_protocol" / "audit_reports" / "PVLIVE_SOLAR_CANDIDATE_LATEST.md"
REPORT_JSON = ROOT / "data_science_protocol" / "audit_reports" / "json" / "PVLIVE_SOLAR_CANDIDATE_LATEST.json"
PVLIVE_URL = "https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0"


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")


def iso_z(value: Any) -> str:
    if value in (None, ""):
        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 ""


def http_json(url: str) -> Any:
    req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
    with urllib.request.urlopen(req, timeout=45) as response:
        return json.loads(response.read().decode("utf-8"))


def extract_rows(payload: Any) -> list[Any]:
    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 parse_power(value: Any) -> float | None:
    try:
        out = float(value)
        if out == out:
            return out
    except Exception:
        return None
    return None


def parse_pvlive_row(row: Any) -> tuple[str, float] | None:
    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
    t = iso_z(timestamp)
    mw = parse_power(generation)
    if not t or mw is None:
        return None
    return t, mw


def candidate_urls(start: dt.datetime, end: dt.datetime) -> list[str]:
    start_iso = start.isoformat().replace("+00:00", "Z")
    end_iso = end.isoformat().replace("+00:00", "Z")
    start_plain = start.strftime("%Y-%m-%dT%H:%M:%SZ")
    end_plain = end.strftime("%Y-%m-%dT%H:%M:%SZ")
    start_date = start.date().isoformat()
    end_date = end.date().isoformat()
    params = [
        {"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_URL + "?" + urllib.parse.urlencode(p) for p in params]


def fetch_day(day: dt.date) -> tuple[list[float], str, str]:
    start = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
    end = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
    errors: list[str] = []
    for url in candidate_urls(start, end):
        try:
            values: list[float] = []
            for row in extract_rows(http_json(url)):
                parsed = parse_pvlive_row(row)
                if parsed:
                    values.append(parsed[1])
            if values:
                return values, url, ""
        except Exception as exc:
            errors.append(str(exc))
    return [], "", "; ".join(errors[-3:])


def load_existing() -> dict[str, Any]:
    if not OUT.exists():
        return {}
    try:
        payload = json.loads(OUT.read_text(encoding="utf-8"))
        return {row["date"]: row for row in payload.get("rows", []) if row.get("date")}
    except Exception:
        return {}


def write_json(path: Path, payload: Any) -> str:
    path.parent.mkdir(parents=True, exist_ok=True)
    text = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
    path.write_text(text, encoding="utf-8")
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def write_report(report: dict[str, Any]) -> None:
    REPORT_MD.parent.mkdir(parents=True, exist_ok=True)
    REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
    REPORT_JSON.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    REPORT_MD.write_text("\n".join([
        "# PVLive Solar Candidate Fetch Audit",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Status: `{report['status']}`",
        f"Days requested: `{report['daysRequested']}`",
        f"Days with rows: `{report['daysWithRows']}`",
        f"Output path: `{report['outputPath']}`",
        f"Output rows: `{report['outputRows']}`",
        f"Output size bytes: `{report['outputSizeBytes']}`",
        f"SHA 256: `{report['sha256']}`",
        "",
        "Source: Sheffield Solar PVLive. Method state: PVLIVE EMBEDDED ESTIMATE.",
        "This is a solar output layer. It does not replace confirmed Elexon FUELHH for transmission metered fuels.",
    ]) + "\n", encoding="utf-8")


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--days", type=int, default=30)
    args = ap.parse_args()
    today = dt.datetime.now(dt.timezone.utc).date()
    start_day = today - dt.timedelta(days=max(1, args.days))
    existing = load_existing()
    working_url = ""
    failures: list[dict[str, str]] = []
    days_with_rows = 0
    for offset in range(max(1, args.days)):
        day = start_day + dt.timedelta(days=offset)
        values, url, err = fetch_day(day)
        if values:
            days_with_rows += 1
            if not working_url:
                working_url = url
            existing[day.isoformat()] = {
                "date": day.isoformat(),
                "technology": "Solar",
                "averageMW": round(sum(values) / len(values), 3),
                "highMW": round(max(values), 3),
                "lowMW": round(min(values), 3),
                "sampleCount": len(values),
                "source": "Sheffield Solar PVLive",
                "methodState": "PVLIVE EMBEDDED ESTIMATE",
                "status": "candidate",
            }
        else:
            failures.append({"date": day.isoformat(), "error": err or "no rows"})
    rows = [existing[k] for k in sorted(existing)]
    payload = {
        "schemaVersion": "0.1.0-pvlive-solar-daily-candidate",
        "generatedUTC": utc_now(),
        "title": "PVLive solar daily MW candidate",
        "timezone": "UTC",
        "source": "Sheffield Solar PVLive",
        "methodState": "PVLIVE EMBEDDED ESTIMATE",
        "rows": rows,
    }
    sha = write_json(OUT, payload)
    report = {
        "generatedUTC": utc_now(),
        "status": "ok" if days_with_rows else "no rows fetched",
        "daysRequested": args.days,
        "daysWithRows": days_with_rows,
        "failures": failures[-10:],
        "workingUrl": working_url,
        "outputPath": str(OUT.relative_to(ROOT)),
        "outputRows": len(rows),
        "outputSizeBytes": OUT.stat().st_size,
        "sha256": sha,
    }
    write_report(report)
    if days_with_rows == 0:
        raise SystemExit("No PVLive solar rows fetched")
    return 0


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