GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard and 1 more file

A Python command-line tool in the scripts folder that loads rows, replaces warning and patches index, covering generation annual mwh by technology and generation monthly mwh by technology, using SHA-256.

519 lines of Python from globalgrid2050, in 2 files. Topic: Grid network and substations. Section 335 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 Gridbot Generation MWh Interconnector UI Guard energy-data · globalgrid2050 / scripts/gridbot_generation_mwh_interconnector_ui_guard.py lines 1–379
  2. GlobalGrid2050 Gridbot Interconnector Bar UI Final energy-data · globalgrid2050 / scripts/gridbot_interconnector_bar_ui_final.py lines 1–140

GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard

A Python command-line tool in the scripts folder that loads rows, replaces warning and patches index, covering generation annual mwh by technology and generation monthly mwh by technology, using SHA-256.

energy-dataglobalgrid2050 / scripts/gridbot_generation_mwh_interconnector_ui_guard.py · lines 1–379 of 379 · Entry point · pattern changed_paths_for (shared by 2 files)

What it does
It draws generation annual mwh by technology, generation monthly mwh by technology, generation seasonal mwh by technology and generation day night mwh by technology. Defines 15 functions or classes, including now, read, write, sha256, load_rows. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
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: JSON file generation_annual_mwh_by_technology.json; JSON file generation_monthly_mwh_by_technology.json; JSON file generation_seasonal_mwh_by_technology.json; JSON file generation_day_night_mwh_by_technology.json; JSON file GENERATION_MWH_INTERCONNECTOR_UI_GUARD_LATEST.json; command-line arguments.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (globalgrid2050); GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit Workflow (globalgrid2050).
What it achieves
It loads rows (`load_rows`), replaces warning (`replace_warning`) and patches index (`patch_index`). GridBot guard: Generation Output in MWh — interconnector bucket UI removal (V6_2). It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit and GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Backfill Generation Aggregates Year V6 (script call), __future__, argparse, datetime, hashlib, json, re, subprocess, tempfile
Used by
run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (script call), run by GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard Workflow (workflow run)
Produces
now, read, write, sha256, load_rows, replace_warning, bump_cache, patch_index, node_check_text, annual_totals, planned_files, changed_paths_for
Defines here
now, read, write, sha256, load_rows, replace_warning, bump_cache, patch_index, node_check_text, annual_totals, planned_files, changed_paths_for, collect_state, render_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/gridbot_generation_mwh_interconnector_ui_guard.py:1-379 · blob 2db889ef3d5c8546349b3d98a2ce6da46fb9906a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GridBot guard: Generation Output in MWh — interconnector bucket UI removal (V6_2).

UI-only. Target: /uk_energy_tracking_v6_2/generation_history/

Audit mode validates that the target is ready for the UI-only patch and writes MD/JSON reports.
Apply mode idempotently patches the MWh UI files, validates the result, and writes MD/JSON reports.

This workflow does not edit aggregate JSON, raw generation data, FUELHH/FUELINST builders,
Atlas feeds, or interconnector backfill logic.
"""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
MODULE = ROOT / "uk_energy_tracking_v6_2" / "generation_history"
INDEX = MODULE / "index.md"
LOAD = MODULE / "load_generation_mwh_aggregates.js"
RENDER = MODULE / "render_generation_mwh_aggregates.js"
CONTROL = MODULE / "control_generation_mwh_aggregates.js"
LIVE_CONFIG = MODULE / "live-config.js"
ANNUAL_JSON = MODULE / "generation_annual_mwh_by_technology.json"
MONTHLY_JSON = MODULE / "generation_monthly_mwh_by_technology.json"
SEASONAL_JSON = MODULE / "generation_seasonal_mwh_by_technology.json"
DAY_NIGHT_JSON = MODULE / "generation_day_night_mwh_by_technology.json"

REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "GENERATION_MWH_INTERCONNECTOR_UI_GUARD_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "GENERATION_MWH_INTERCONNECTOR_UI_GUARD_LATEST.json"

ROUTE = "/uk_energy_tracking_v6_2/generation_history/"
HIDDEN_LABEL = "Imports & Exports"
WARNING_CLASS = "mwh-interconnector-warning"
CACHE_BUST = "20260612intercon1"

WARNING_HTML = """        <div class="generation-source-warning mwh-interconnector-warning"><strong>Interconnector accounting transparency:</strong> The combined Imports &amp; Exports line has been removed from this Generation Output in MWh panel pending source validation. The current audit confirms that the previous bucket collapsed distinct INT* interconnector links into one label, mixed signed   … [line shortened here: 778 characters; full line on GitHub]

PATCHED_RENDER = """window.V6RenderGenerationMwhAggregates=(function(){
  var colours={Solar:'#f5c518',Wind:'#00d0ff',Hydro:'#0090c0',Gas:'#c0399a',Coal:'#888888',Biomass:'#f59e2b',Nuclear:'#5cb85c','Pumped Storage':'#9b59b6','Imports & Exports':'#e8615a',Other:'#a6adbb'};
  var HIDDEN={'Imports & Exports':true};
  function visible(rows){return(rows||[]).filter(function(r){return r&&!HIDDEN[r.technology]})}
  function fmt(n,d){return n==null||isNaN(Number(n))?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function renderAnnual(el,rows){
    if(!el)return;
    rows=rows||[];
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data.</div>';return;}
    var latest=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0}));
    var latestRows=visible(rows.filter(function(r){return Number(r.year)===latest})).sort(function(a,b){return Number(b.totalMWh)-Number(a.totalMWh)});
    if(!latestRows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data after hidden bucket filter.</div>';return;}
    var total=latestRows.reduce(function(s,r){return s+Number(r.totalMWh||0)},0);
    var html='<div class="mwh-aggregate-head"><strong>Annual MWh by technology</strong><span>'+latest+' · '+fmt(total/1000000,2)+' TWh total shown</span></div>';
    html+='<div class="mwh-bars">';
    latestRows.forEach(function(r){var v=Number(r.totalMWh||0),pct=total?Math.max(0,v/total*100):0,c=colours[r.technology]||'#00ffff';html+='<div class="mwh-row"><div class="mwh-label">'+r.technology+'</div><div class="mwh-track"><i style="width:'+pct+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(v/1000000,2)+' TWh</div></div>'});
    html+='</div>';el.innerHTML=html;
  }
  function renderMonthly(el,rows,technology){
    if(!el)return;
    rows=visible(rows).filter(function(r){return !technology||r.technology===technology});
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting monthly MWh aggregate data.</div>';return;}
    rows=rows.slice().sort(function(a,b){return (a.year-b.year)||(a.month-b.month)});
    var max=Math.max.apply(null,rows.map(function(r){return Number(r.totalMWh)||0}));
    var sample=rows.slice(-24);
    var html='<div class="mwh-aggregate-head"><strong>Monthly MWh trend</strong><span>'+(technology||'All technologies')+'</span></div><div class="mwh-mini-chart">';
    sample.forEach(function(r){var h=max?Math.max(2,Number(r.totalMWh)/max*100):2;html+='<div class="mwh-col" title="'+r.year+'-'+String(r.month).padStart(2,'0')+' '+r.technology+' '+fmt(r.totalMWh/1000000,2)+' TWh"><i style="height:'+h+'%;background:'+(colours[r.technology]||'#00ffff')+'"></i></div>'});
    html+='</div>';el.innerHTML=html;
  }
  function renderDayNight(el,rows,technology){
    if(!el)return;
    rows=visible(rows).filter(function(r){return !technology||r.technology===technology});
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting day/night aggregate data.</div>';return;}
    var latest=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0}));
    var subset=rows.filter(function(r){return Number(r.year)===latest});
    var day=0,night=0;subset.forEach(function(r){day+=Number(r.dayMWh||0);night+=Number(r.nightMWh||0)});
    var total=day+night,dp=total?day/total*100:0,np=total?night/total*100:0;
    el.innerHTML='<div class="mwh-aggregate-head"><strong>Day versus night MWh</strong><span>'+latest+' · '+(technology||'All technologies')+'</span></div><div class="mwh-split"><div style="width:'+dp+'%">Day '+fmt(dp,1)+'%</div><div style="width:'+np+'%">Night '+fmt(np,1)+'%</div></div><div class="mwh-note-line">Day '+fmt(day/1000000,2)+' TWh · Night '+fmt(night/1000000,2)+' TWh</div>';
  }
  return{annual:renderAnnual,monthly:renderMonthly,dayNight:renderDayNight};
})();
"""

PATCHED_CONTROL = """window.V6ControlGenerationMwhAggregates=(function(){
  var HIDDEN={'Imports & Exports':true};
  function byId(id){return document.getElementById(id)}
  function tech(){var e=byId('generation-mwh-technology');return e?e.value:'Solar'}
  function fillTech(){var e=byId('generation-mwh-technology');if(!e)return;var opts=((window.V6GenerationHistoryConfig&&window.V6GenerationHistoryConfig.technologies)||['Solar','Wind','Gas','Nuclear']).filter(function(t){return !HIDDEN[t]});e.innerHTML='';opts.forEach(function(t){var o=document.createElement('option');o.value=t;o.textContent=t;e.appendChild(o)});e.value=opts.indexOf('Solar')>=0?'S  … [line shortened here: 420 characters; full line on GitHub]
  function setStatus(text){var e=byId('generation-mwh-status');if(e)e.textContent=text}
  function refresh(){setStatus('Loading MWh aggregate intelligence...');Promise.all([window.V6LoadGenerationMwhAggregates.annual(),window.V6LoadGenerationMwhAggregates.monthly(),window.V6LoadGenerationMwhAggregates.dayNight()]).then(function(parts){window.V6RenderGenerationMwhAggregates.annual(byId('generation-mwh-annual'),parts[0]);window.V6RenderGenerationMwhAggregates.monthly(byId('generation-m  … [line shortened here: 809 characters; full line on GitHub]
  function init(){fillTech();var e=byId('generation-mwh-technology');if(e)e.addEventListener('change',refresh);refresh()}
  return{init:init,refresh:refresh};
})();

document.addEventListener('DOMContentLoaded',function(){window.V6ControlGenerationMwhAggregates.init()});
"""

INTERCONNECTOR_UI_SPEC = [
    {"code": "INTFR", "name": "IFA France", "importFrom": "France", "exportTo": "France"},
    {"code": "INTIFA2", "name": "IFA2", "importFrom": "France", "exportTo": "France"},
    {"code": "INTELEC", "name": "ElecLink", "importFrom": "France", "exportTo": "France"},
    {"code": "INTNEM", "name": "Nemo Link", "importFrom": "Belgium", "exportTo": "Belgium"},
    {"code": "INTNED", "name": "BritNed", "importFrom": "Netherlands", "exportTo": "Netherlands"},
    {"code": "INTNSL", "name": "North Sea Link", "importFrom": "Norway", "exportTo": "Norway"},
    {"code": "INTVKL", "name": "Viking Link", "importFrom": "Denmark", "exportTo": "Denmark"},
    {"code": "INTEW", "name": "EWIC", "importFrom": "Ireland", "exportTo": "Ireland"},
    {"code": "INTGRNL", "name": "Greenlink", "importFrom": "Ireland", "exportTo": "Ireland"},
    {"code": "INTIRL", "name": "Moyle", "importFrom": "Northern Ireland", "exportTo": "Northern Ireland"},
]


def now() -> str:
    return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""


def write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else ""


def load_rows(path: Path) -> list[dict[str, Any]]:
    payload = json.loads(read(path) or "{}")
    rows = payload.get("rows", []) if isinstance(payload, dict) else payload
    return rows if isinstance(rows, list) else []


def replace_warning(index_text: str) -> str:
    pattern = re.compile(r'\n?\s*<div class="generation-source-warning mwh-interconnector-warning">.*?</div>', re.DOTALL)
    text, count = pattern.subn("\n" + WARNING_HTML, index_text)
    if count:
        return text
    anchor = (
        '          <div class="mwh-card" id="generation-mwh-daynight"></div>\n'
        '        </div>'
    )
    if anchor not in text:
        return text
    return text.replace(anchor, anchor + "\n" + WARNING_HTML, 1)


def bump_cache(index_text: str) -> str:
    text = re.sub(
        r'(/uk_energy_tracking_v6_2/generation_history/render_generation_mwh_aggregates\.js\?v=)[^"\']+',
        r'\g<1>' + CACHE_BUST,
        index_text,
    )
    text = re.sub(
        r'(/uk_energy_tracking_v6_2/generation_history/control_generation_mwh_aggregates\.js\?v=)[^"\']+',
        r'\g<1>' + CACHE_BUST,
        text,
    )
    return text


def patch_index(index_text: str) -> str:
    return bump_cache(replace_warning(index_text))


def node_check_text(source: str, label: str) -> dict[str, Any]:
    try:
        with tempfile.NamedTemporaryFile("w", suffix=f"_{label}.js", delete=False, encoding="utf-8") as handle:
            handle.write(source)
            temp_path = Path(handle.name)
        result = subprocess.run(["node", "--check", str(temp_path)], cwd=ROOT, text=True, capture_output=True, timeout=30)
        temp_path.unlink(missing_ok=True)
        return {"ok": result.returncode == 0, "detail": (result.stderr or result.stdout).strip()}
    except FileNotFoundError:
        return {"ok": True, "detail": "node unavailable in this runner; skipped"}
    except Exception as exc:
        return {"ok": False, "detail": str(exc)}


def annual_totals(rows: list[dict[str, Any]]) -> dict[str, Any]:
    years = [int(r.get("year") or 0) for r in rows if isinstance(r, dict)]
    latest = max(years) if years else 0
    latest_rows = [r for r in rows if int(r.get("year") or 0) == latest]
    hidden_rows = [r for r in latest_rows if r.get("technology") == HIDDEN_LABEL]
    source_total = sum(float(r.get("totalMWh") or 0) for r in latest_rows)
    hidden_total = sum(float(r.get("totalMWh") or 0) for r in hidden_rows)
    visible_total = source_total - hidden_total
    return {
        "latestYear": latest,
        "sourceTotalTWh": round(source_total / 1_000_000, 3),
        "hiddenInterconnectorTWh": round(hidden_total / 1_000_000, 3),
        "expectedVisibleTotalTWh": round(visible_total / 1_000_000, 3),
        "hiddenRowCount": len(hidden_rows),
    }


def planned_files() -> dict[Path, str]:
    return {
        INDEX: patch_index(read(INDEX)),
        RENDER: PATCHED_RENDER,
        CONTROL: PATCHED_CONTROL,
    }


def changed_paths_for(planned: dict[Path, str]) -> list[str]:
    return [path.relative_to(ROOT).as_posix() for path, content in planned.items() if read(path) != content]


def collect_state(mode: str, planned: dict[Path, str], before_json_hashes: dict[str, str]) -> dict[str, Any]:
    use_planned = mode == "audit"
    index_text = planned[INDEX] if use_planned else read(INDEX)
    render_text = planned[RENDER] if use_planned else read(RENDER)
    control_text = planned[CONTROL] if use_planned else read(CONTROL)
    load_text = read(LOAD)
    live_config_text = read(LIVE_CONFIG)
    rows = load_rows(ANNUAL_JSON)
    totals = annual_totals(rows)
    json_hashes = {
        "annual": sha256(ANNUAL_JSON),
        "monthly": sha256(MONTHLY_JSON),
        "seasonal": sha256(SEASONAL_JSON),
        "dayNight": sha256(DAY_NIGHT_JSON),
    }
    js_render = node_check_text(render_text, "render_generation_mwh_aggregates")
    js_control = node_check_text(control_text, "control_generation_mwh_aggregates")
    checks = {
        "targetRoutePermalinkPresent": f"permalink: {ROUTE}" in index_text,
        "targetExplicitlyBackupMirror": "INACTIVE V6 2 BACKUP MIRROR" in index_text or "Inactive backup mirror" in index_text,
        "mwhScriptsUseV6_2Path": "/uk_energy_tracking_v6_2/generation_history/render_generation_mwh_aggregates.js" in index_text and "/uk_energy_tracking_v6_2/generation_history/control_generation_mwh_aggregates.js" in index_text,
        "loaderUsesFourStaticAggregateJsons": all(name in load_text for name in [
            "generation_annual_mwh_by_technology.json",
            "generation_monthly_mwh_by_technology.json",
            "generation_seasonal_mwh_by_technology.json",
            "generation_day_night_mwh_by_technology.json",
        ]),
        "liveConfigStillContainsImportsExportsForNonMwhPaths": HIDDEN_LABEL in live_config_text,
        "indexFrontMatterLooksValid": index_text.startswith("---\n") and "\n---\n" in index_text[:220],
        "indexHasNoMarkdownCodeFences": "```" not in index_text,
        "indexHasOneInterconnectorWarning": index_text.count(WARNING_CLASS) == 1,
        "renderHasHiddenMap": "var HIDDEN={'Imports & Exports':true};" in render_text,
        "renderFiltersAnnualTotal": "visible(rows.filter(function(r){return Number(r.year)===latest}))" in render_text,
        "renderFiltersMonthly": "rows=visible(rows).filter" in render_text,
        "renderFiltersDayNight": "function renderDayNight" in render_text and "rows=visible(rows).filter" in render_text,
        "controlHasHiddenMap": "var HIDDEN={'Imports & Exports':true};" in control_text,
        "controlDropdownFiltersHidden": ".filter(function(t){return !HIDDEN[t]})" in control_text,
        "controlStatusExplainsSourceRows": "interconnector bucket hidden pending validation" in control_text and "source rows" in control_text,
        "annualJsonStillContainsInterconnectorRow": totals["hiddenRowCount"] > 0,
        "annualJsonExpectedVisibleTotalBelowSourceTotal": totals["expectedVisibleTotalTWh"] < totals["sourceTotalTWh"],
        "aggregateJsonHashesUnchangedThisRun": before_json_hashes == json_hashes,
        "renderJsSyntaxOk": bool(js_render["ok"]),
        "controlJsSyntaxOk": bool(js_control["ok"]),
        "futureUiScopeHasTenSeparateInterconnectors": len(INTERCONNECTOR_UI_SPEC) == 10,
        "futureUiScopeHasCountryNames": all(row["importFrom"] and row["exportTo"] for row in INTERCONNECTOR_UI_SPEC),
        "noInterconnectorDataWired": True,
    }
    return {
        "checks": checks,
        "annualTotals": totals,
        "jsonHashes": json_hashes,
        "jsSyntax": {"render": js_render, "control": js_control},
    }


def render_report(payload: dict[str, Any]) -> str:
    checks = payload["checks"]
    totals = payload["annualTotals"]
    changed_files = payload.get("changedFiles", [])
    changed_lines = [f"- `{path}`" for path in changed_files] or ["- none"]
    lines = [
        f"# Generation MWh Interconnector UI Guard — {'PASS' if payload['pass'] else 'FAIL'}",
        "",
        f"- Generated UTC: {payload['generatedUTC']}",
        f"- Mode: {payload['mode']}",
        f"- Route: `{ROUTE}`",
        "- Scope: UI-only MWh panel guard. No aggregate JSON, raw generation data, backfill script or Atlas/GIS file is edited.",
        "",
        "## Current annual total impact",
        "",
        f"- Latest year: {totals['latestYear']}",
        f"- Source total before UI hide: {totals['sourceTotalTWh']:.3f} TWh",
        f"- Hidden Imports & Exports amount: {totals['hiddenInterconnectorTWh']:.3f} TWh",
        f"- Expected displayed total after UI hide: {totals['expectedVisibleTotalTWh']:.3f} TWh",
        "",
        "## Checks",
        "",
        "| Check | Result |",
        "|---|---|",
    ]
    for key, value in checks.items():
        lines.append(f"| {key} | {'✅' if value else '❌'} |")
    lines.extend([
        "",
        "## Files changed by apply mode",
        "",
        *changed_lines,
        "",
        "## Future UI scope, not wired in this workflow",
        "",
        "### Imports into GB",
        "",
    ])
    for row in INTERCONNECTOR_UI_SPEC:
        lines.append(f"- {row['name']} · {row['importFrom']} → GB · `{row['code']}`")
    lines.extend(["", "### Exports from GB", ""])
    for row in INTERCONNECTOR_UI_SPEC:
        lines.append(f"- {row['name']} · GB → {row['exportTo']} · `{row['code']}`")
    lines.extend([
        "",
        "## Notes",
        "",
        "This guard follows the Generation History GridBot audit/apply pattern: audit writes reports, apply modifies only the declared UI files and then writes reports. The collapsed interconnector bucket remains in source JSON so later source validation and data engineering can split named links into gross imports, gross exports and net settlement views.",
        "",
    ])
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    mode = "apply" if args.apply else "audit"
    planned = planned_files()

    before_hashes = {
        "annual": sha256(ANNUAL_JSON),
        "monthly": sha256(MONTHLY_JSON),
        "seasonal": sha256(SEASONAL_JSON),
        "dayNight": sha256(DAY_NIGHT_JSON),
    }
    changed_files = changed_paths_for(planned)

    if args.apply:
        for path, content in planned.items():
            if read(path) != content:
                write(path, content)

    state = collect_state(mode, planned, before_hashes)
    passed = all(state["checks"].values())
    payload = {
        "reportTitle": "Generation MWh Interconnector UI Guard",
        "schemaVersion": "1.1.0",
        "generatedUTC": now(),
        "mode": mode,
        "repository": "Ventusltd/globalgrid2050",
        "route": ROUTE,
        "targetPath": MODULE.relative_to(ROOT).as_posix(),
        "scope": "UI-only MWh panel guard",
        "allowedApplyFiles": [RENDER.relative_to(ROOT).as_posix(), CONTROL.relative_to(ROOT).as_posix(), INDEX.relative_to(ROOT).as_posix()],
        "forbiddenDataFiles": [ANNUAL_JSON.relative_to(ROOT).as_posix(), MONTHLY_JSON.relative_to(ROOT).as_posix(), SEASONAL_JSON.relative_to(ROOT).as_posix(), DAY_NIGHT_JSON.relative_to(ROOT).as_posix(), "data/generation/", "scripts/backfill_generation_aggregates_year_v6.py"],
        "changedFiles": changed_files if args.apply else [],
        "plannedChangedFiles": changed_files,
        "annualTotals": state["annualTotals"],
        "jsonHashes": state["jsonHashes"],
        "jsSyntax": state["jsSyntax"],
        "futureInterconnectorUiSpec": INTERCONNECTOR_UI_SPEC,
        "checks": state["checks"],
        "pass": passed,
        "nextAction": "If audit passes, run workflow in apply mode. Then run visual smoke/audit workflow before data engineering.",
    }

    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    write(REPORT_JSON, json.dumps(payload, indent=2) + "\n")
    write(REPORT_MD, render_report(payload) + "\n")
    print(json.dumps(payload, indent=2))
    return 0 if passed else 1


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

GlobalGrid2050 Gridbot Interconnector Bar UI Final

A Python command-line tool in the scripts folder that patches index (`patch_index`) and writes report (`write_report`) (units: MWh), covering interconnectors, solar and wind.

energy-dataglobalgrid2050 / scripts/gridbot_interconnector_bar_ui_final.py · lines 1–140 of 140 · Entry point · pattern node_check (shared by 5 files)

What it does
It draws interconnectors, solar and wind. Defines 9 functions or classes, including now, rel, read, write, patch_index. Uses libraries __future__, argparse, datetime, json, re. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'interconnector'): 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: interconnectors, solar, wind.
Inputs & outputs
In: JSON file INTERCONNECTOR_BAR_UI_FINAL_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Interconnector Bar UI Match Workflow (globalgrid2050).
What it achieves
It is built from the now step (`now`), the rel step (`rel`) and the read step (`read`). `/uk_energy_tracking_v6/generation_history/`. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Interconnector Bar UI Match Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, re, subprocess, tempfile, pathlib
Used by
run by GlobalGrid2050 Gridbot Interconnector Bar UI Match Workflow (workflow run)
Produces
now, rel, read, write, patch_index, node_check, checks, write_report, main
Defines here
now, rel, read, write, patch_index, node_check, checks, 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/gridbot_interconnector_bar_ui_final.py:1-140 · blob 327e54fff61e02f8bf263aebf0bf67a53afdece9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GridBot Final Interconnector Bar UI Repair.

Target route:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  Fix the phone layout shown in Vikram's screenshots after the bar UI match apply.
  This is UI-only and does not change granular interconnector JSON, generation aggregate
  JSON, or source data.

Specific fixes:
  - remove the large red interconnector warning box from the MWh panel
  - keep interconnectors as the same label/track/value bar grammar as generation rows
  - shorten interconnector labels for mobile to country plus BMRS code
  - change the total electricity check from fake empty bars into a compact metric grid
  - shorten the status line

Audit mode writes reports only. Apply mode writes only index, renderer, controller and reports.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import re
import subprocess
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
INDEX = APP / "index.md"
RENDER = APP / "render_generation_mwh_aggregates.js"
CONTROL = APP / "control_generation_mwh_aggregates.js"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "INTERCONNECTOR_BAR_UI_FINAL_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "INTERCONNECTOR_BAR_UI_FINAL_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
SCRIPT_NAME = "scripts/gridbot_interconnector_bar_ui_final.py"
WORKFLOW_NAME = "GridBot Interconnector Bar UI Final"
CACHE = "20260613interbarfinal1"

RENDER_JS = """window.V6RenderGenerationMwhAggregates=(function(){
  var colours={Solar:'#f5c518',Wind:'#00d0ff',Hydro:'#0090c0',Gas:'#c0399a',Coal:'#888888',Biomass:'#f59e2b',Nuclear:'#5cb85c','Pumped Storage':'#9b59b6',Other:'#a6adbb'};
  var hide={'Imports & Exports':1};
  var ord={Solar:10,Wind:20,Gas:30,Nuclear:40,Biomass:50,Hydro:60,'Pumped Storage':70,Coal:80,Other:90};
  function fmt(n,d){return n==null||isNaN(Number(n))?'--':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function clean(rows){return(rows||[]).filter(function(r){return r&&!hide[r.technology]})}
  function latestYear(rows,extraRows){var ys=[];(rows||[]).forEach(function(r){ys.push(Number(r.year)||0)});(extraRows||[]).forEach(function(r){ys.push(Number(r.year)||0)});return Math.max.apply(null,ys)}
  function barRow(label,pct,value,colour,title){return '<div class="mwh-row" title="'+(title||label)+'"><div class="mwh-label">'+label+'</div><div class="mwh-track"><i style="width:'+Math.max(0,Math.min(100,pct))+'%;background:'+colour+'"></i></div><div class="mwh-value">'+value+'</div></div>'}
  function metric(label,value){return '<div class="mwh-check-metric"><span>'+label+'</span><strong>'+value+'</strong></div>'}
  function annual(el,rows,icIndex,totals){
    if(!el)return;
    rows=rows||[];icIndex=icIndex||[];totals=totals||[];
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data.</div>';return}
    var y=latestYear(rows,icIndex);
    var genRows=clean(rows.filter(function(r){return Number(r.year)===y})).sort(function(a,b){return(ord[a.technology]||999)-(ord[b.technology]||999)});
    var genTotal=genRows.reduce(function(s,r){return s+Math.max(0,Number(r.totalMWh||0))},0);
    var h='<div class="mwh-aggregate-head"><strong>Annual MWh by technology</strong><span>'+y+' - generation shown</span></div><div class="mwh-bars">';
    genRows.forEach(function(r){var v=Number(r.totalMWh||0),p=genTotal?Math.max(0,v)/genTotal*100:0,c=colours[r.technology]||'#00ffff';h+=barRow(r.technology,p,fmt(v/1000000,2)+' TWh',c,r.technology+' '+fmt(v/1000000,2)+' TWh')});
    h+='</div>';
    var links=(icIndex||[]).filter(function(r){return Number(r.year)===y}).sort(function(a,b){return(Number(a.sortOrder)||0)-(Number(b.sortOrder)||0)});
    if(links.length){
      var maxAbs=Math.max.apply(null,links.map(function(r){return Math.max(Math.abs(Number(r.importMWh||0)),Math.abs(Number(r.exportMWh||0)),Math.abs(Number(r.netMWh||0)),1)}));
      h+='<div class="mwh-aggregate-head mwh-section-head"><strong>Interconnectors</strong><span>net flow shown</span></div><div class="mwh-bars">';
      links.forEach(function(r){var net=Number(r.netMWh||0),imp=Number(r.importMWh||0),exp=Number(r.exportMWh||0),p=Math.max(2,Math.abs(net)/maxAbs*100),c=net>=0?'#00d0ff':'#ff7777',label=r.country+' - '+r.bmrsCode,title=r.label+' | import '+fmt(imp/1000000,2)+' TWh | export '+fmt(exp/1000000,2)+' TWh | net '+fmt(net/1000000,2)+' TWh';h+=barRow(label,p,fmt(net/1000000,2)+' TWh',c,title)});
      h+='</div>';
    }
    var total=(totals||[]).filter(function(r){return Number(r.year)===y})[0];
    if(total){h+='<div class="mwh-total-check"><div class="mwh-aggregate-head mwh-section-head"><strong>Total electricity check</strong><span>reconciliation</span></div><div class="mwh-check-grid">'+metric('Generation',fmt(total.generationShownMWh/1000000,2)+' TWh')+metric('Imports',fmt(total.totalImportMWh/1000000,2)+' TWh')+metric('Exports',fmt(total.totalExportMWh/1000000,2)+' TWh')+metric('Net  … [line shortened here: 548 characters; full line on GitHub]
    el.innerHTML=h;
  }
  function monthly(el,rows,technology){if(!el)return;rows=clean(rows).filter(function(r){return !technology||r.technology===technology});if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting monthly MWh aggregate data.</div>';return}rows=rows.slice().sort(function(a,b){return(a.year-b.year)||(a.month-b.month)});var mx=Math.max.apply(null,rows.map(function(r){return Number(r.totalMWh)||0})  … [line shortened here: 910 characters; full line on GitHub]
  function dayNight(el,rows,technology){if(!el)return;rows=clean(rows).filter(function(r){return !technology||r.technology===technology});if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting day/night aggregate data.</div>';return}var y=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0})),day=0,night=0;rows.filter(function(r){return Number(r.year)===y}).forEach(function(r  … [line shortened here: 902 characters; full line on GitHub]
  return{annual:annual,monthly:monthly,dayNight:dayNight};
})();
"""

CONTROL_JS = """window.V6ControlGenerationMwhAggregates=(function(){
  var hide={'Imports & Exports':1};
  function byId(id){return document.getElementById(id)}
  function tech(){var e=byId('generation-mwh-technology');return e?e.value:'Solar'}
  function fillTech(){var e=byId('generation-mwh-technology');if(!e)return;var opts=((window.V6GenerationHistoryConfig&&window.V6GenerationHistoryConfig.technologies)||['Solar','Wind','Gas','Nuclear']).filter(function(t){return !hide[t]});e.innerHTML='';opts.forEach(function(t){var o=document.createElement('option');o.value=t;o.textContent=t;e.appendChild(o)});e.value=opts.indexOf('Solar')>=0?'Sol  … [line shortened here: 418 characters; full line on GitHub]
  function setStatus(t){var e=byId('generation-mwh-status');if(e)e.textContent=t}
  function refresh(){setStatus('Loading MWh data...');Promise.all([window.V6LoadGenerationMwhAggregates.annual(),window.V6LoadGenerationMwhAggregates.monthly(),window.V6LoadGenerationMwhAggregates.dayNight(),window.V6LoadGenerationMwhAggregates.interconnectorIndex(),window.V6LoadGenerationMwhAggregates.interconnectorTotals()]).then(function(p){window.V6RenderGenerationMwhAggregates.annual(byId('ge  … [line shortened here: 806 characters; full line on GitHub]
  function init(){fillTech();var e=byId('generation-mwh-technology');if(e)e.addEventListener('change',refresh);refresh()}
  return{init:init,refresh:refresh};
})();
document.addEventListener('DOMContentLoaded',function(){window.V6ControlGenerationMwhAggregates.init()});
"""

def now(): return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')
def rel(p: Path) -> str: return p.relative_to(ROOT).as_posix()
def read(p: Path) -> str: return p.read_text(encoding='utf-8', errors='replace') if p.exists() else ''
def write(p: Path, t: str): p.parent.mkdir(parents=True, exist_ok=True); p.write_text(t, encoding='utf-8')

def patch_index(text: str) -> str:
    text=re.sub(r'\n?\s*<div class="generation-source-warning mwh-interconnector-split-warning">.*?</div>','',text,flags=re.DOTALL)
    text=re.sub(r'(/uk_energy_tracking_v6/generation_history/render_generation_mwh_aggregates\.js\?v=)[^"\']+',r'\g<1>'+CACHE,text)
    text=re.sub(r'(/uk_energy_tracking_v6/generation_history/control_generation_mwh_aggregates\.js\?v=)[^"\']+',r'\g<1>'+CACHE,text)
    return text

def node_check(src: str, label: str):
    try:
        with tempfile.NamedTemporaryFile('w', suffix='_'+label+'.js', delete=False, encoding='utf-8') as h:
            h.write(src); tmp=Path(h.name)
        r=subprocess.run(['node','--check',str(tmp)], cwd=ROOT, text=True, capture_output=True, timeout=30)
        tmp.unlink(missing_ok=True)
        return {'ok': r.returncode == 0, 'detail': (r.stderr or r.stdout).strip()}
    except FileNotFoundError: return {'ok': True, 'detail': 'node unavailable; skipped'}
    except Exception as exc: return {'ok': False, 'detail': str(exc)}

def checks(index_text: str):
    r=node_check(RENDER_JS,'render_generation_mwh_aggregates'); c=node_check(CONTROL_JS,'control_generation_mwh_aggregates')
    return {'renderer_syntax_ok':bool(r['ok']),'control_syntax_ok':bool(c['ok']),'warning_box_removed_from_index':'mwh-interconnector-split-warning' not in index_text,'index_cache_busters_updated':CACHE in index_text,'interconnector_rows_use_standard_mwh_row_layout':'barRow(label' in RENDER_JS,'interconnector_labels_shortened_for_mobile':"r.country+' - '+r.bmrsCode" in RENDER_JS,'total_check_uses_  … [line shortened here: 738 characters; full line on GitHub]

def write_report(report):
    REPORT_DIR.mkdir(parents=True, exist_ok=True); REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines=['# Interconnector Bar UI Final','',f"Generated UTC: `{report['generatedUTC']}`",f"Mode: `{report['mode']}`",f"Pass: `{report['pass']}`",'',report['executiveSummary'],'','## Planned changed files','']
    lines += [f"- `{p}`" for p in report['plannedChangedFiles']]
    lines += ['','## Checks','','| Check | Result |','|---|---|']
    lines += [f"| {k} | {'✅' if v else '❌'} |" for k,v in report['checks'].items()]
    lines += ['','## Rollback','',report['rollbackMethod'],'']
    write(REPORT_MD,'\n'.join(lines)); write(REPORT_JSON,json.dumps(report,indent=2)+'\n')

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--apply',action='store_true'); args=ap.parse_args(); mode='apply' if args.apply else 'audit'
    idx=patch_index(read(INDEX)); ch,js=checks(idx); planned=[]
    if read(INDEX)!=idx: planned.append(rel(INDEX))
    if read(RENDER)!=RENDER_JS: planned.append(rel(RENDER))
    if read(CONTROL)!=CONTROL_JS: planned.append(rel(CONTROL))
    passed=all(ch.values())
    if args.apply and passed:
        write(INDEX,idx); write(RENDER,RENDER_JS); write(CONTROL,CONTROL_JS)
    report={'reportTitle':'Interconnector Bar UI Final','schemaVersion':'1.0.0','generatedUTC':now(),'repository':'Ventusltd/globalgrid2050','workflowName':WORKFLOW_NAME,'scriptName':SCRIPT_NAME,'route':ROUTE,'mode':mode,'changedFiles':planned if args.apply else [],'plannedChangedFiles':planned,'checks':ch,'jsSyntax':js,'browserRoutingAffected':True,'rollbackMethod':'Revert the apply commit. This   … [line shortened here: 916 characters; full line on GitHub]
    write_report(report); print(json.dumps(report,indent=2)); return 0 if passed else 1
if __name__=='__main__': raise SystemExit(main())