GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Gridbot Interconnector Bar UI Match and 3 more files

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

571 lines of Python from globalgrid2050, in 4 files. Topic: Grid network and substations. Section 336 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 Interconnector Bar UI Match energy-data · globalgrid2050 / scripts/gridbot_interconnector_bar_ui_match.py lines 1–185
  2. GlobalGrid2050 Gridbot Interconnector Mobile UI Repair energy-data · globalgrid2050 / scripts/gridbot_interconnector_mobile_ui_repair.py lines 1–175
  3. GlobalGrid2050 Remove Benchmark Block from V6 V7 GIS Single-Line Diagram (SLD) electrical · globalgrid2050 / scripts/remove_benchmark_block_from_v6_v7_gis_sld.py lines 1–116
  4. GlobalGrid2050 Remove Project X from V6 V7 GIS Single-Line Diagram (SLD) electrical · globalgrid2050 / scripts/remove_project_x_from_v6_v7_gis_sld.py lines 1–95

GlobalGrid2050 Gridbot Interconnector Bar UI Match

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

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

What it does
It draws interconnectors, solar and wind. Defines 8 functions or classes, including now, rel, read, write, node_check. Uses libraries __future__, argparse, datetime, json, subprocess. 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_MATCH_LATEST.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It 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
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, subprocess, tempfile, pathlib, typing
Used by
none found
Produces
now, rel, read, write, node_check, checks, write_report, main
Defines here
now, rel, read, write, 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_match.py:1-185 · blob 06ffdc7aca5eae2ce091e752013d1a89691ae0c1 · 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 Interconnector Bar UI Match.

Target route:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  Repair the interconnector UI so it matches the existing annual MWh bar style used by
  the other generation technologies. This is a UI-only repair. It does not change the
  granular interconnector JSON data, the generation aggregate JSON data, or any source data.

Audit mode:
  Build the proposed renderer/controller replacement in memory and write reports only.

Apply mode:
  Write only the renderer, controller and report files.
"""
from __future__ import annotations

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

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
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_MATCH_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "INTERCONNECTOR_BAR_UI_MATCH_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
SCRIPT_NAME = "scripts/gridbot_interconnector_bar_ui_match.py"
WORKFLOW_NAME = "GridBot Interconnector Bar UI Match"

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 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 generationRows=clean(rows.filter(function(r){return Number(r.year)===y})).sort(function(a,b){return(ord[a.technology]||999)-(ord[b.technology]||999)});
    var generationTotal=generationRows.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; interconnectors split below</span></div><div class="mwh-bars">';
    generationRows.forEach(function(r){
      var v=Number(r.totalMWh||0),p=generationTotal?Math.max(0,v)/generationTotal*100:0,c=colours[r.technology]||'#00ffff';
      h+='<div class="mwh-row"><div class="mwh-label">'+r.technology+'</div><div class="mwh-track"><i style="width:'+p+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(v/1000000,2)+' TWh</div></div>';
    });
    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-interconnector-head"><strong>Interconnectors</strong><span>same bar style - net MWh shown</span></div><div class="mwh-bars mwh-interconnector-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';
        var label=r.country+' - '+r.bmrsCode;
        var title=r.label+' | import '+fmt(imp/1000000,2)+' TWh | export '+fmt(exp/1000000,2)+' TWh | net '+fmt(net/1000000,2)+' TWh';
        h+='<div class="mwh-row mwh-interconnector-row" title="'+title+'"><div class="mwh-label">'+label+'</div><div class="mwh-track"><i style="width:'+p+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(net/1000000,2)+' TWh</div></div>';
      });
      h+='</div><div class="mwh-note-line">Interconnector bars use net MWh. Imports are positive. Exports are negative. Tap/hover rows for import/export detail.</div>';
    }else{
      h+='<div class="mwh-note-line">Interconnector split awaiting signed raw-code source rows.</div>';
    }

    var total=(totals||[]).filter(function(r){return Number(r.year)===y})[0];
    if(total){
      h+='<div class="mwh-aggregate-head mwh-total-head"><strong>Total electricity check</strong><span>for reconciliation</span></div><div class="mwh-total-rows">';
      h+='<div class="mwh-row mwh-total-row"><div class="mwh-label">Generation shown</div><div class="mwh-track"></div><div class="mwh-value">'+fmt(total.generationShownMWh/1000000,2)+' TWh</div></div>';
      h+='<div class="mwh-row mwh-total-row"><div class="mwh-label">Imports</div><div class="mwh-track"></div><div class="mwh-value">'+fmt(total.totalImportMWh/1000000,2)+' TWh</div></div>';
      h+='<div class="mwh-row mwh-total-row"><div class="mwh-label">Exports</div><div class="mwh-track"></div><div class="mwh-value">'+fmt(total.totalExportMWh/1000000,2)+' TWh</div></div>';
      h+='<div class="mwh-row mwh-total-row"><div class="mwh-label">Net interconnector</div><div class="mwh-track"></div><div class="mwh-value">'+fmt(total.netInterconnectorMWh/1000000,2)+' TWh</div></div>';
      h+='<div class="mwh-row mwh-total-row"><div class="mwh-label">Supply proxy</div><div class="mwh-track"></div><div class="mwh-value">'+fmt(total.supplyProxyMWh/1000000,2)+' TWh</div></div>';
      h+='</div>';
    }
    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})),sample=rows.slice(-24);
    var h='<div class="mwh-aggregate-head"><strong>Monthly MWh trend</strong><span>'+(technology||'All generation technologies')+'</span></div><div class="mwh-mini-chart">';
    sample.forEach(function(r){var p=mx?Math.max(2,Number(r.totalMWh)/mx*100):2;h+='<div class="mwh-col" title="'+r.year+'-'+String(r.month).padStart(2,'0')+' '+r.technology+' '+fmt(r.totalMWh/1000000,2)+' TWh"><i style="height:'+p+'%;background:'+(colours[r.technology]||'#00ffff')+'"></i></div>'});
    el.innerHTML=h+'</div>';
  }
  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){day+=Number(r.dayMWh||0);night+=Number(r.nightMWh||0)});
    var t=day+night,dp=t?day/t*100:0,np=t?night/t*100:0;
    el.innerHTML='<div class="mwh-aggregate-head"><strong>Day versus night MWh</strong><span>'+y+' - '+(technology||'All generation 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: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: 815 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 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():
    r=node_check(RENDER_JS,'render_generation_mwh_aggregates')
    c=node_check(CONTROL_JS,'control_generation_mwh_aggregates')
    render_text=RENDER_JS
    control_text=CONTROL_JS
    return {
        'renderer_syntax_ok': bool(r['ok']),
        'control_syntax_ok': bool(c['ok']),
        'interconnector_rows_use_mwh_row_bar_layout': 'mwh-row mwh-interconnector-row' in render_text and 'mwh-track' in render_text,
        'interconnector_rows_not_collapsed_into_details': '<details' not in render_text and 'mwh-interconnector-details' not in render_text,
        'interconnector_labels_shortened_for_mobile': "var label=r.country+' - '+r.bmrsCode" in render_text,
        'values_show_net_twh_like_generation_rows': 'fmt(net/1000000,2)+\' TWh\'' in render_text,
        'total_check_uses_same_mwh_row_layout': 'mwh-row mwh-total-row' in render_text,
        'status_line_shortened': 'Loaded - generation rows' in control_text,
        'generation_jsons_not_touched': True,
    }, {'render': r, 'control': c}


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 Match','',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'
    ch, js=checks()
    planned=[]
    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(RENDER, RENDER_JS); write(CONTROL, CONTROL_JS)
    report={'reportTitle':'Interconnector Bar UI Match','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: 887 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())

GlobalGrid2050 Gridbot Interconnector Mobile UI Repair

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

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

What it does
It draws interconnectors, solar and wind. Defines 8 functions or classes, including now, rel, read, write, node_check. 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_MOBILE_UI_REPAIR_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Interconnector Mobile UI Repair 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 Mobile UI Repair Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, re, subprocess, tempfile, pathlib
Used by
run by GlobalGrid2050 Gridbot Interconnector Mobile UI Repair Workflow (workflow run)
Produces
now, rel, read, write, node_check, checks, write_report, main
Defines here
now, rel, read, write, 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_mobile_ui_repair.py:1-175 · blob ac718f324eeb9889fc4360a5021ac2000199870a · 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 Interconnector Mobile UI Repair.

Target:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  The first granular interconnector split passed the data audit but produced a bad mobile UI.
  This repair keeps the granular JSON outputs untouched and changes only the renderer/status
  layout so the annual MWh card remains readable on phone screens.

Audit mode:
  Builds the proposed JS patch in memory and writes reports only.

Apply mode:
  Writes only the renderer, controller and report files.
"""
from __future__ import annotations

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

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
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_MOBILE_UI_REPAIR_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "INTERCONNECTOR_MOBILE_UI_REPAIR_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
SCRIPT_NAME = "scripts/gridbot_interconnector_mobile_ui_repair.py"
WORKFLOW_NAME = "GridBot Interconnector Mobile UI Repair"

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 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 rs=clean(rows.filter(function(r){return Number(r.year)===y})).sort(function(a,b){return(ord[a.technology]||999)-(ord[b.technology]||999)});
    var generationTotal=rs.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; interconnectors below</span></div><div class="mwh-bars">';
    rs.forEach(function(r){
      var v=Number(r.totalMWh||0),p=generationTotal?Math.max(0,v)/generationTotal*100:0,c=colours[r.technology]||'#00ffff';
      h+='<div class="mwh-row"><div class="mwh-label">'+r.technology+'</div><div class="mwh-track"><i style="width:'+p+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(v/1000000,2)+' TWh</div></div>';
    });
    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){
      h+='<details class="mwh-interconnector-details"><summary>Interconnectors · imports positive · exports negative</summary><div class="mwh-interconnector-list">';
      links.forEach(function(r){
        var imp=Number(r.importMWh||0), exp=Number(r.exportMWh||0), net=Number(r.netMWh||0);
        h+='<div class="mwh-ic-item"><div class="mwh-ic-name">'+r.label+'</div><div class="mwh-ic-values"><span>Import '+fmt(imp/1000000,2)+' TWh</span><span>Export '+fmt(exp/1000000,2)+' TWh</span><span>Net '+fmt(net/1000000,2)+' TWh</span></div></div>';
      });
      h+='</div></details>';
    }else{
      h+='<div class="mwh-note-line">Interconnector split awaiting signed raw-code source rows.</div>';
    }

    var total=(totals||[]).filter(function(r){return Number(r.year)===y})[0];
    if(total){
      h+='<div class="mwh-total-check"><strong>Total electricity check</strong><div class="mwh-total-grid"><span>Generation</span><b>'+fmt(total.generationShownMWh/1000000,2)+' TWh</b><span>Imports</span><b>'+fmt(total.totalImportMWh/1000000,2)+' TWh</b><span>Exports</span><b>'+fmt(total.totalExportMWh/1000000,2)+' TWh</b><span>Net interconnector</span><b>'+fmt(total.netInterconnectorMWh/1000000,2  … [line shortened here: 500 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})),sample=rows.slice(-24);
    var h='<div class="mwh-aggregate-head"><strong>Monthly MWh trend</strong><span>'+(technology||'All generation technologies')+'</span></div><div class="mwh-mini-chart">';
    sample.forEach(function(r){var p=mx?Math.max(2,Number(r.totalMWh)/mx*100):2;h+='<div class="mwh-col" title="'+r.year+'-'+String(r.month).padStart(2,'0')+' '+r.technology+' '+fmt(r.totalMWh/1000000,2)+' TWh"><i style="height:'+p+'%;background:'+(colours[r.technology]||'#00ffff')+'"></i></div>'});
    el.innerHTML=h+'</div>';
  }
  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){day+=Number(r.dayMWh||0);night+=Number(r.nightMWh||0)});
    var t=day+night,dp=t?day/t*100:0,np=t?night/t*100:0;
    el.innerHTML='<div class="mwh-aggregate-head"><strong>Day versus night MWh</strong><span>'+y+' - '+(technology||'All generation 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: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: 815 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 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():
    r=node_check(RENDER_JS,'render_generation_mwh_aggregates')
    c=node_check(CONTROL_JS,'control_generation_mwh_aggregates')
    render_text=RENDER_JS
    control_text=CONTROL_JS
    return {
        'renderer_syntax_ok': bool(r['ok']),
        'control_syntax_ok': bool(c['ok']),
        'interconnectors_collapsed_into_details': 'mwh-interconnector-details' in render_text and '<summary>Interconnectors' in render_text,
        'total_check_reformatted_as_grid': 'mwh-total-grid' in render_text,
        'long_interconnector_rows_removed_from_main_bar_layout': 'mwh-interconnector-row' not in render_text,
        'status_line_shortened': 'Loaded · generation rows' in control_text,
        'generation_jsons_not_touched': True,
    }, {'render': r, 'control': c}


def write_report(report):
    REPORT_DIR.mkdir(parents=True, exist_ok=True); REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines=['# Interconnector Mobile UI Repair','',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'
    ch, js=checks()
    planned=[]
    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(RENDER, RENDER_JS); write(CONTROL, CONTROL_JS)
    report={'reportTitle':'Interconnector Mobile UI Repair','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.   … [line shortened here: 850 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())

GlobalGrid2050 Remove Benchmark Block from V6 V7 GIS Single-Line Diagram (SLD)

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

electricalglobalgrid2050 / scripts/remove_benchmark_block_from_v6_v7_gis_sld.py · lines 1–116 of 116 · Entry point

What it does
It loads solar and battery storage (BESS). Defines read, write, remove_block, main. Uses libraries __future__, datetime, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): 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, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Remove Benchmark Block from V6 V7 GIS Single-Line Diagram (SLD) Workflow (globalgrid2050).
What it achieves
It removes block (`remove_block`) and is built from the read step (`read`) and the write step (`write`). Remove the entire optional/reference benchmark block from V6 and V7 GIS SLD.
Why it matters
Run by GlobalGrid2050 Remove Benchmark Block from V6 V7 GIS Single-Line Diagram (SLD) Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, pathlib
Used by
run by GlobalGrid2050 Remove Benchmark Block from V6 V7 GIS Single-Line Diagram (SLD) Workflow (workflow run)
Produces
read, write, remove_block, main
Defines here
read, write, remove_block, 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/remove_benchmark_block_from_v6_v7_gis_sld.py:1-116 · blob 5c23c47199b05b2a93fb80866f29cc80b2478d98 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Remove the entire optional/reference benchmark block from V6 and V7 GIS SLD.

Purpose:
- Remove benchmark UI from the main GIS SLD workflow.
- Remove irrelevant benchmark text from screen and print output.
- Preserve technical quantity summary, grid connection length, drawing, export and report sections.
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "remove_benchmark_block_from_v6_v7_gis_sld.md"

TARGETS = [
    ROOT / "solar-bess-topology-v6" / "gis-sld-financial-sandbox" / "index.html",
    ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox" / "index.html",
]

START_TOKENS = [
    '    <div class="benchmark-box">\n',
    '<div class="benchmark-box">\n',
]
END_TOKEN = '    <button class="btn draw-btn" id="btn_draw">⌖ DRAW NEAT GRID</button>'


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def write(path: Path, text: str) -> None:
    path.write_text(text, encoding="utf-8")


def remove_block(text: str) -> tuple[str, bool]:
    start = -1
    for token in START_TOKENS:
        start = text.find(token)
        if start != -1:
            break

    if start == -1:
        return text, False

    end = text.find(END_TOKEN, start)
    if end == -1:
        raise SystemExit("Benchmark block found but draw button end marker was not found")

    # Preserve the draw button and following content.
    new_text = text[:start].rstrip() + "\n\n" + text[end:]
    return new_text, True


def main() -> int:
    actions: list[str] = []

    for path in TARGETS:
        if not path.exists():
            raise SystemExit(f"Missing target: {path.relative_to(ROOT)}")

        text = read(path)
        new_text, changed = remove_block(text)

        # Final clean up in case a previous rename left benchmark wording elsewhere.
        for phrase in [
            "Custom Project X",
            "Optional Reference Benchmark",
            "Custom Reference Benchmark",
            "Reference Project",
            "Benchmark Name",
            "Reference Capacity (MW)",
            "Reference Module Count",
            "Implied Benchmark",
            "Optional benchmark",
        ]:
            if phrase in new_text:
                raise SystemExit(f"Refusing to leave benchmark phrase in {path.relative_to(ROOT)}: {phrase}")

        if changed:
            write(path, new_text)
            actions.append(f"removed benchmark block from {path.relative_to(ROOT)}")
        else:
            actions.append(f"benchmark block already absent from {path.relative_to(ROOT)}")

    REPORTS.mkdir(parents=True, exist_ok=True)
    timestamp = dt.datetime.now(dt.timezone.utc).isoformat()
    report = "\n".join([
        "# Remove Benchmark Block From V6 And V7 GIS SLD",
        "",
        f"UTC created: {timestamp}",
        "",
        "## Purpose",
        "",
        "Remove the whole benchmark section from the V6 and V7 GIS SLD Financial Sandbox because it was not useful in the main workflow and looked like placeholder content.",
        "",
        "## Actions",
        "",
        *[f"- {action}" for action in actions],
        "",
        "## Expected user facing change",
        "",
        "The benchmark card is gone. The interface now moves directly from Technical Quantity Summary to drawing/export and grid connection workflow content.",
        "",
    ])
    write(REPORT, report)
    print(f"Removed benchmark block. Report: {REPORT.relative_to(ROOT)}")
    return 0


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

GlobalGrid2050 Remove Project X from V6 V7 GIS Single-Line Diagram (SLD)

A Python command-line tool in the scripts folder that reads solar and battery storage (BESS). It is built from the read step (`read`) and the write step (`write`).

electricalglobalgrid2050 / scripts/remove_project_x_from_v6_v7_gis_sld.py · lines 1–95 of 95 · Entry point

What it does
It loads solar and battery storage (BESS). Defines read, write, main. Uses libraries __future__, datetime, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): 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, battery storage (BESS).
Inputs & outputs
In: form fields (user input).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Remove Project X from V6 V7 GIS Single-Line Diagram (SLD) Workflow (globalgrid2050).
What it achieves
Remove placeholder Project X wording from V6 and V7 GIS SLD benchmark block.
Why it matters
Run by GlobalGrid2050 Remove Project X from V6 V7 GIS Single-Line Diagram (SLD) Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, pathlib
Used by
run by GlobalGrid2050 Remove Project X from V6 V7 GIS Single-Line Diagram (SLD) Workflow (workflow run)
Produces
read, write, main
Defines here
read, write, 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/remove_project_x_from_v6_v7_gis_sld.py:1-95 · blob dea88d626e329b16f7e2a83d32bec7bea80677a4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Remove placeholder Project X wording from V6 and V7 GIS SLD benchmark block.

Purpose:
- Replace demo style wording with professional optional benchmark wording.
- Keep the benchmark feature available.
- Avoid printing random placeholder names in PDF output.
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "remove_project_x_from_v6_v7_gis_sld.md"

TARGETS = [
    ROOT / "solar-bess-topology-v6" / "gis-sld-financial-sandbox" / "index.html",
    ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox" / "index.html",
]

REPLACEMENTS = {
    "Custom Reference Benchmark": "Optional Reference Benchmark",
    "Reference Project</label><input type=\"text\" id=\"ref_name\" value=\"Custom Project X\" style=\"width: 140px; text-align: left;\"/>": "Benchmark Name</label><input type=\"text\" id=\"ref_name\" value=\"\" placeholder=\"Optional benchmark\" style=\"width: 140px; text-align: left;\"/>",
    "Reference Project Custom Project X": "Benchmark Name Optional benchmark",
}


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def write(path: Path, text: str) -> None:
    path.write_text(text, encoding="utf-8")


def main() -> int:
    actions: list[str] = []

    for path in TARGETS:
        if not path.exists():
            raise SystemExit(f"Missing target: {path.relative_to(ROOT)}")

        text = read(path)
        original = text
        count = 0

        for old, new in REPLACEMENTS.items():
            occurrences = text.count(old)
            if occurrences:
                text = text.replace(old, new)
                count += occurrences

        if "Custom Project X" in text:
            text = text.replace("Custom Project X", "")
            count += 1

        if text != original:
            write(path, text)
            actions.append(f"patched {count} benchmark placeholder reference(s) in {path.relative_to(ROOT)}")
        else:
            actions.append(f"no benchmark placeholder changes required in {path.relative_to(ROOT)}")

    REPORTS.mkdir(parents=True, exist_ok=True)
    timestamp = dt.datetime.now(dt.timezone.utc).isoformat()
    report = "\n".join([
        "# Remove Project X From V6 And V7 GIS SLD",
        "",
        f"UTC created: {timestamp}",
        "",
        "## Purpose",
        "",
        "Remove the demo style `Custom Project X` default from the GIS SLD benchmark block and replace it with professional optional benchmark wording.",
        "",
        "## Actions",
        "",
        *[f"- {action}" for action in actions],
        "",
        "## Expected user facing change",
        "",
        "- `Custom Reference Benchmark` becomes `Optional Reference Benchmark`.",
        "- `Reference Project` becomes `Benchmark Name`.",
        "- The default project name is blank with placeholder text `Optional benchmark`.",
        "",
    ])
    write(REPORT, report)
    print(f"Removed Project X placeholder. Report: {REPORT.relative_to(ROOT)}")
    return 0


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