In this section
- GlobalGrid2050 Gridbot Generation History Peak UI Audit energy-data · globalgrid2050 / scripts/gridbot_generation_history_peak_ui_audit.py lines 1–105
- GlobalGrid2050 Gridbot Generation History UI Label Audit energy-data · globalgrid2050 / scripts/gridbot_generation_history_ui_label_audit.py lines 1–81
- GlobalGrid2050 Gridbot Generation History V6 2 Backup Mirror energy-data · globalgrid2050 / scripts/gridbot_generation_history_v6_2_backup_mirror.py lines 1–232
- GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit energy-data · globalgrid2050 / scripts/gridbot_generation_mwh_active_v6_source_audit.py lines 1–128
- GlobalGrid2050 Harden Renewables V6 Dashboard other · globalgrid2050 / scripts/harden_renewables_v6_dashboard.py lines 1–7
- GlobalGrid2050 Isolate UK Energy Tracking V2 storage · globalgrid2050 / scripts/isolate_uk_energy_tracking_v2.py lines 1–115
GlobalGrid2050 Gridbot Generation History Peak UI Audit
A Python command-line tool in the scripts folder covering solar, using SHA-256.
energy-dataglobalgrid2050 / scripts/gridbot_generation_history_peak_ui_audit.py · lines 1–105 of 105 · Entry point
- What it does
- It draws solar. Defines sha256, main. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file GENERATION_HISTORY_PEAK_UI_LATEST.json; command-line arguments. Out: canvas drawing.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `sha256`. 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, hashlib, json, pathlib
- Used by
- none found
- Produces
- sha256, main
- Defines here
- sha256, 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_history_peak_ui_audit.py:1-105 · blob e4c90fdb23e09d3a54d391f76f745ba87bb5e1b5 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse, hashlib, json
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RENDERER = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'render_generation_history_chart.js'
INDEX = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'index.md'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports' / 'GENERATION_HISTORY_PEAK_UI_LATEST.md'
REPORT_JSON = ROOT / 'data_science_protocol' / 'audit_reports' / 'json' / 'GENERATION_HISTORY_PEAK_UI_LATEST.json'
NEW_RENDERER = r"""window.V6RenderGenerationHistoryChart=(function(){
function fmt(n,d){return n==null||isNaN(Number(n))?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
function niceDate(v){var d=v instanceof Date?v:new Date(String(v).replace(' ','T'));return isNaN(d.getTime())?'—':d.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}
function niceClock(v){var s=String(v||'');var m=s.match(/(\d{2}:\d{2})/);return m?m[1]:''}
function isSolarDaily(result){return result&&result.mode==='daily'&&result.technology==='Solar'}
function valueOf(r,mode){return mode==='daily'?Number(r.averageMW):Number(r.generationMW)}
function highOf(r,result){return isSolarDaily(result)&&r.highMW!=null?Number(r.highMW):valueOf(r,result.mode)}
function lowOf(r,result){return isSolarDaily(result)&&r.lowMW!=null?Number(r.lowMW):valueOf(r,result.mode)}
function avgOf(r,result){return valueOf(r,result.mode)}
function timeOf(r,mode){return mode==='daily'?r.date+'T12:00:00Z':r.time}
function colour(tech){return {'Solar':'#f5c518','Wind':'#00d0ff','Hydro':'#0090c0','Gas':'#ff4fbf','Coal':'#888888','Biomass':'#f59e2b','Nuclear':'#5cff8d','Pumped Storage':'#b16cff','Imports & Exports':'#e8615a','Other':'#a6adbb','All generation total':'#00ffff'}[tech]||'#00ffff'}
function compactMode(result){if(isSolarDaily(result))return 'Daily high · average · low';return result.mode==='daily'?'Daily average':'30 min output'}
function dateLabel(t,span){var d=new Date(t);return span>45*86400000?d.toLocaleDateString('en-GB',{month:'short',year:'numeric'}):d.toLocaleDateString('en-GB',{day:'2-digit',month:'short'})}
function shortTickLabel(t,span){var d=new Date(t);if(span<=2.1*86400000)return d.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',hour12:false});return d.toLocaleDateString('en-GB',{weekday:'short',day:'numeric'})}
function stats(result){var rows=result.rows||[];if(!rows.length)return null;var h=rows[0],l=rows[0],s=0,n=0,mwh=0,samples=0,complete=0;rows.forEach(function(r){var av=avgOf(r,result),hi=highOf(r,result),lo=lowOf(r,result);if(!isNaN(av)){s+=av;n++}if(!isNaN(hi)&&hi>highOf(h,result))h=r;if(!isNaN(lo)&&lo<lowOf(l,result))l=r;if(r.mwh!=null&&!isNaN(Number(r.mwh)))mwh+=Number(r.mwh);if(r.sampleCount! … [line shortened here: 935 characters; full line on GitHub]
function minMax(rows,result){var lo=0,hi=0;rows.forEach(function(r){var vals=isSolarDaily(result)?[highOf(r,result),avgOf(r,result),lowOf(r,result)]:[valueOf(r,result.mode)];vals.forEach(function(v){if(isNaN(v))return;if(v<lo)lo=v;if(v>hi)hi=v})});if(lo===hi)hi=lo+1;var m=Math.max((hi-lo)*.10,50);return{lo:lo-m,hi:hi+m}}
function step(span){var raw=span/5,p=Math.pow(10,Math.floor(Math.log10(Math.max(raw,1)))),n=raw/p;if(n<=1)return p;if(n<=2)return 2*p;if(n<=5)return 5*p;return 10*p}
function drawTitle(g,result,q,w,pad,cssW){var c=colour(result.technology);g.save();g.font='900 '+(cssW<520?11:15)*q+'px Courier New';g.fillStyle='#00ffff';g.textAlign='left';var title=(cssW<520?'GB GEN · ':'GB GENERATION HISTORY · ')+(result.technology||'Technology')+' · '+compactMode(result);g.fillText(title,18*q,28*q);var lx=pad.left,ly=pad.top-24*q;g.shadowColor=c;g.shadowBlur=6*q;g.fillStyle … [line shortened here: 638 characters; full line on GitHub]
function drawTicks(g,w,h,q,mm,pad,t0,t1){var st=step(mm.hi-mm.lo),start=Math.ceil(mm.lo/st)*st,span=t1-t0,plotW=w-pad.left-pad.right;g.save();g.font=(w/q<520?9:11)*q+'px Courier New';for(var v=start;v<=mm.hi+st*.5;v+=st){var y=pad.top+((mm.hi-v)/(mm.hi-mm.lo))*(h-pad.top-pad.bottom);g.fillStyle='#d8deeb';g.textAlign='left';g.fillText(fmt(v,0)+' MW',8*q,y+4*q);g.strokeStyle='rgba(255,255,255,.055 … [line shortened here: 1,199 characters; full line on GitHub]
function pointFns(result,w,h,pad,mm,t0,t1){var plotW=w-pad.left-pad.right,plotH=h-pad.top-pad.bottom;return{X:function(r){var t=new Date(timeOf(r,result.mode)).getTime();return pad.left+((t-t0)/(t1-t0))*plotW},Y:function(v){return pad.top+((mm.hi-v)/(mm.hi-mm.lo))*plotH}}}
function callout(g,label,val,date,clock,x,y,q,w,h,pad,c){var left=x<w/2,tx=left?Math.min(w-pad.right-160*q,x+18*q):Math.max(pad.left+160*q,x-18*q),ty=Math.max(pad.top+54*q,Math.min(h-pad.bottom-28*q,y+(label.indexOf('PEAK')>=0?-24:58)*q));g.save();g.strokeStyle='#ff3333';g.lineWidth=1.4*q;g.shadowColor='rgba(0,255,255,.55)';g.shadowBlur=7*q;g.beginPath();g.moveTo(x,y);g.lineTo(tx,ty-24*q);g.stro … [line shortened here: 990 characters; full line on GitHub]
function drawSeries(g,rows,result,w,h,q,pad,mm,t0,t1,getter,stroke,fill,lineWidth,shadow){if(!rows.length)return;var p=pointFns(result,w,h,pad,mm,t0,t1);g.save();g.strokeStyle=stroke;g.lineWidth=lineWidth*q;g.shadowColor=shadow||stroke;g.shadowBlur=shadow?7*q:0;g.beginPath();rows.forEach(function(r,i){var x=p.X(r),y=p.Y(getter(r));if(i===0)g.moveTo(x,y);else g.lineTo(x,y)});g.stroke();g.shadowBl … [line shortened here: 572 characters; full line on GitHub]
function drawLegend(g,result,q,pad){if(!isSolarDaily(result))return;g.save();var x=pad.left,y=pad.top-4*q,items=[['High MW','#ff4444'],['Average MW','#f5c518'],['Low MW','#4fd1ff']];g.font=9*q+'px Courier New';items.forEach(function(it,i){var xx=x+i*96*q;g.fillStyle=it[1];g.fillRect(xx,y,9*q,9*q);g.fillStyle='#d8deeb';g.fillText(it[0],xx+14*q,y+8*q)});g.restore()}
function drawLine(g,rows,result,w,h,q,pad,mm,t0,t1){if(!rows.length)return;var c=colour(result.technology),p=pointFns(result,w,h,pad,mm,t0,t1);if(isSolarDaily(result)){drawSeries(g,rows,result,w,h,q,pad,mm,t0,t1,function(r){return highOf(r,result)},'#ff4444',null,1.4,'rgba(255,64,64,.45)');drawSeries(g,rows,result,w,h,q,pad,mm,t0,t1,function(r){return avgOf(r,result)},c,'rgba(245,197,24,.35)',2. … [line shortened here: 838 characters; full line on GitHub]
g.save();g.strokeStyle=c;g.lineWidth=2.2*q;g.shadowColor=c;g.shadowBlur=9*q;g.beginPath();rows.forEach(function(r,i){var x=p.X(r),y=p.Y(valueOf(r,result.mode));if(i===0)g.moveTo(x,y);else g.lineTo(x,y)});g.stroke();g.shadowBlur=0;if(rows.length<80){g.fillStyle=c;rows.forEach(function(r){var x=p.X(r),y=p.Y(valueOf(r,result.mode));g.beginPath();g.arc(x,y,2.4*q,0,Math.PI*2);g.fill()})}var s=stats(r … [line shortened here: 794 characters; full line on GitHub]
function drawSummary(g,s,q,w,h,pad,result){if(!s)return;var y=h-72*q,bw=w-pad.left-pad.right,x=pad.left,cols=isSolarDaily(result)?4:3,col=bw/cols;g.save();g.fillStyle='rgba(5,7,12,.92)';g.strokeStyle='rgba(0,255,255,.42)';g.shadowColor='rgba(0,255,255,.18)';g.shadowBlur=8*q;g.beginPath();g.roundRect(x,y,bw,52*q,9*q);g.fill();g.stroke();g.shadowBlur=0;function cell(i,label,value,sub,accent){var c … [line shortened here: 1,167 characters; full line on GitHub]
function render(canvas,result){var rows=result.rows||[],ctx=canvas.getContext('2d'),box=canvas.getBoundingClientRect(),q=window.devicePixelRatio||1,cssW=Math.max(320,Math.floor(box.width||canvas.clientWidth||600)),cssH=Math.max(420,Math.floor(box.height||canvas.clientHeight||520)),w=Math.floor(cssW*q),h=Math.floor(cssH*q);canvas.width=w;canvas.height=h;ctx.clearRect(0,0,w,h);ctx.fillStyle='#0507 … [line shortened here: 885 characters; full line on GitHub]
return{render:render};
})();
"""
def sha256(text: str) -> str:
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
old = RENDERER.read_text(encoding='utf-8')
index = INDEX.read_text(encoding='utf-8') if INDEX.exists() else ''
checks = {
'renderer_exists': RENDERER.exists(),
'current_renderer_uses_average_only_daily': "function valueOf(r,mode){return mode==='daily'?Number(r.averageMW):Number(r.generationMW)}" in old,
'current_title_says_daily_average': "function compactMode(mode){return mode==='daily'?'Daily average':'30 min output'}" in old,
'new_renderer_has_solar_daily_three_series': 'Daily high · average · low' in NEW_RENDERER and 'PEAK HIGH' in NEW_RENDERER,
'new_renderer_uses_highMW': 'highMW' in NEW_RENDERER,
'new_renderer_uses_lowMW': 'lowMW' in NEW_RENDERER,
'new_renderer_uses_mwh': 'totalMwh' in NEW_RENDERER,
'index_cache_can_be_bumped': 'render_generation_history_chart.js?v=' in index,
}
cache_target = 'render_generation_history_chart.js?v=20260610peakui1'
index_new = index.replace('render_generation_history_chart.js?v=20260610solarui1', cache_target).replace('render_generation_history_chart.js?v=20260609study1', cache_target)
passed = all(checks.values())
changed = old != NEW_RENDERER or index != index_new
if args.apply and passed:
RENDERER.write_text(NEW_RENDERER, encoding='utf-8')
INDEX.write_text(index_new, encoding='utf-8')
report = {
'mode': 'apply' if args.apply else 'audit',
'rendererPath': str(RENDERER.relative_to(ROOT)),
'indexPath': str(INDEX.relative_to(ROOT)),
'oldRendererSha256': sha256(old),
'newRendererSha256': sha256(NEW_RENDERER),
'wouldChangeRenderer': old != NEW_RENDERER,
'wouldChangeIndexCache': index != index_new,
'checks': checks,
'applied': bool(args.apply and passed),
'pass': passed,
'changeSummary': [
'Solar daily chart title changes to Daily high average low',
'Solar daily chart draws highMW, averageMW and lowMW',
'Solar daily peak callout uses highMW and is labelled PEAK HIGH',
'Solar daily summary adds ENERGY from mwh in TWh',
'Non solar and 30 minute views retain the existing single line behaviour',
'No data files or loaders are changed'
],
'riskNotes': [
'PVLive is an estimated national Solar output layer, not transmission metered generation',
'Low MW for Solar is usually night time and may be near zero',
'Peak MW is the key value for grid stress and negative price analysis'
]
}
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# Generation History Peak UI Audit\n\n```json\n' + json.dumps(report, indent=2) + '\n```\n', encoding='utf-8')
REPORT_JSON.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps(report, indent=2))
return 0 if passed else 1
if __name__ == '__main__':
raise SystemExit(main())GlobalGrid2050 Gridbot Generation History UI Label Audit
A Python command-line tool in the scripts folder that reads solar.
energy-dataglobalgrid2050 / scripts/gridbot_generation_history_ui_label_audit.py · lines 1–81 of 81 · Entry point · pattern write_report (shared by 52 files)
- What it does
- It loads solar. Defines now, read, write_report, main. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file GENERATION_HISTORY_UI_LABEL_AUDIT_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
- Defines `now`, `read` and `write_report`. 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, pathlib
- Used by
- none found
- Produces
- now, read, write_report, main
- Defines here
- now, read, 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_generation_history_ui_label_audit.py:1-81 · blob dd803b1122aec3c7a07aad73c7187dffb5e6935d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime as dt
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPORT_DIR = ROOT / 'data_science_protocol' / 'audit_reports'
JSON_DIR = REPORT_DIR / 'json'
RENDER = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'render_generation_history_chart.js'
INDEX = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'index.md'
OLD_VERSION = 'render_generation_history_chart.js?v=20260609study1'
NEW_VERSION = 'render_generation_history_chart.js?v=20260609noecg1'
OLD_SOURCE = 'Embedded solar output is routed through a separate PVLive candidate layer where the solar browser file is present.'
NEW_SOURCE = 'Embedded solar output is routed through a separate PVLive candidate layer from Sheffield Solar PVLive, solar.sheffield.ac.uk, where the solar browser file is present.'
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_report(payload: dict) -> None:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
JSON_DIR.mkdir(parents=True, exist_ok=True)
md = REPORT_DIR / 'GENERATION_HISTORY_UI_LABEL_AUDIT_LATEST.md'
js = JSON_DIR / 'GENERATION_HISTORY_UI_LABEL_AUDIT_LATEST.json'
md.write_text('# GridBot Generation History UI Label Audit\n\n```json\n' + json.dumps(payload, indent=2) + '\n```\n', encoding='utf-8')
js.write_text(json.dumps(payload, indent=2) + '\n', encoding='utf-8')
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
render_text = read(RENDER)
index_text = read(INDEX)
planned_render = render_text.replace("mode==='daily'?'Daily average':'30 min ECG'", "mode==='daily'?'Daily average':'30 min output'")
planned_index = index_text.replace(OLD_VERSION, NEW_VERSION).replace(OLD_SOURCE, NEW_SOURCE)
changed = []
if args.apply and planned_render != render_text:
RENDER.write_text(planned_render, encoding='utf-8')
changed.append(str(RENDER.relative_to(ROOT)))
if args.apply and planned_index != index_text:
INDEX.write_text(planned_index, encoding='utf-8')
changed.append(str(INDEX.relative_to(ROOT)))
payload = {
'generatedUTC': now(),
'mode': 'apply' if args.apply else 'audit',
'renderPath': str(RENDER.relative_to(ROOT)),
'indexPath': str(INDEX.relative_to(ROOT)),
'renderExists': RENDER.exists(),
'indexExists': INDEX.exists(),
'renderEcgBefore': render_text.count('30 min ECG'),
'renderEcgAfterPlanned': planned_render.count('30 min ECG'),
'renderHasThirtyMinOutputAfterPlanned': '30 min output' in planned_render,
'oldVersionPresentBefore': OLD_VERSION in index_text,
'newVersionPresentAfterPlanned': NEW_VERSION in planned_index,
'sourceCreditBefore': index_text.count('Sheffield Solar PVLive'),
'sourceCreditAfterPlanned': planned_index.count('Sheffield Solar PVLive'),
'plannedChangedFiles': [str(p.relative_to(ROOT)) for p, old, new in ((RENDER, render_text, planned_render), (INDEX, index_text, planned_index)) if old != new],
'changedFiles': changed,
'pass': RENDER.exists() and INDEX.exists() and planned_render.count('30 min ECG') == 0 and NEW_VERSION in planned_index and 'Sheffield Solar PVLive' in planned_index,
}
write_report(payload)
print(json.dumps(payload, indent=2))
return 0 if payload['pass'] else 1
if __name__ == '__main__':
raise SystemExit(main())GlobalGrid2050 Gridbot Generation History V6 2 Backup Mirror
A Python command-line tool in the scripts folder that reads generation history backup mirror. It patches homepage (`patch_homepage`), copies snapshot (`copy_snapshot`) and writes status (`write_status`).
energy-dataglobalgrid2050 / scripts/gridbot_generation_history_v6_2_backup_mirror.py · lines 1–232 of 232 · Entry point · pattern write_status (shared by 2 files)
- What it does
- It loads generation history backup mirror. Defines 10 functions or classes, including now, git_head, file_list, read, patch_homepage. Uses libraries __future__, argparse, json, shutil, subprocess. Side effects: 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_HISTORY_V6_2_BACKUP_MIRROR_LATEST.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot Generation History V6 2 Backup Mirror Workflow (globalgrid2050).
- What it achieves
- Defines `now`, `git_head`, `file_list` and 6 more. It accepts `--apply`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Generation History V6 2 Backup Mirror Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, json, shutil, subprocess, datetime, pathlib
- Used by
- run by GlobalGrid2050 Gridbot Generation History V6 2 Backup Mirror Workflow (workflow run)
- Produces
- now, git_head, file_list, read, patch_homepage, copy_snapshot, rewrite_snapshot, write_status, render_report, main
- Defines here
- now, git_head, file_list, read, patch_homepage, copy_snapshot, rewrite_snapshot, write_status, 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_history_v6_2_backup_mirror.py:1-232 · blob ece489cfe6fddf436b6e5b76f200a0fe46d41358 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / 'uk_energy_tracking_v6' / 'generation_history'
DST = ROOT / 'uk_energy_tracking_v6_2' / 'generation_history'
HOME = ROOT / 'index.html'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports' / 'GENERATION_HISTORY_V6_2_BACKUP_MIRROR_LATEST.md'
REPORT_JSON = ROOT / 'data_science_protocol' / 'audit_reports' / 'json' / 'GENERATION_HISTORY_V6_2_BACKUP_MIRROR_LATEST.json'
MIRROR_STATUS = DST / 'MIRROR_STATUS.md'
TEXT_EXTS = {'.md', '.html', '.js', '.css', '.json', '.geojson', '.csv', '.txt', '.yml', '.yaml'}
OLD_HOME_ROWS = [
' <tr><td><a href="./uk_energy_tracking_v6_2/generation_history/">UK Generation History V6 2 Module</a> <span class="dev-status">(in development)</span></td></tr>',
' <tr><td><a href="./uk_energy_tracking_v6_2/generation_history/">UK Generation History V6 2 Backup Mirror</a> <span class="dev-status">(BACKUP)</span></td></tr>',
' <tr><td><a href="./uk_energy_tracking_v6_2/generation_history/">UK Generation History V6 2 Backup Mirror</a> <span class="backup-status">(BACKUP)</span></td></tr>',
]
HOME_ANCHOR_ROW = ' <tr><td><a href="./uk_energy_tracking_v6/generation_history/">UK Generation History V6 Module</a> <span class="dev-status">(in development)</span></td></tr>'
NEW_HOME_ROW = ' <tr><td><a href="./uk_energy_tracking_v6_2/generation_history/">UK Generation History V6 2 Backup Mirror</a> <span class="dev-status">(BACKUP)</span></td></tr>'
REPLACEMENTS = [
('/uk_energy_tracking_v6/generation_history/', '/uk_energy_tracking_v6_2/generation_history/'),
('./uk_energy_tracking_v6/generation_history/', './uk_energy_tracking_v6_2/generation_history/'),
('uk_energy_tracking_v6/generation_history', 'uk_energy_tracking_v6_2/generation_history'),
('permalink: /uk_energy_tracking_v6/generation_history/', 'permalink: /uk_energy_tracking_v6_2/generation_history/'),
('UK Generation History V6 Module', 'UK Generation History V6 2 Backup Mirror'),
('GLOBALGRID2050 · ISOLATED V6 MODULE', 'GLOBALGRID2050 · INACTIVE V6 2 BACKUP MIRROR'),
]
BANNER = '''\n<div class="backup-mirror-banner" style="border:1px solid #f5c518;background:#151103;color:#f5c518;padding:12px;margin:12px 0;font-family:Courier New,Courier,monospace;font-size:13px;line-height:1.45;">\n<strong>Inactive backup mirror.</strong> This page is a frozen mirror of the Generation History V6 module for restore and comparison use. It is not the live development target and mu … [line shortened here: 445 characters; full line on GitHub]
def now() -> str:
return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def git_head(short: bool = True) -> str:
try:
arg = '--short' if short else 'HEAD'
return subprocess.run(['git', 'rev-parse', arg], cwd=ROOT, text=True, capture_output=True, check=True).stdout.strip()
except Exception:
return ''
def file_list(root: Path) -> list[str]:
if not root.exists():
return []
return sorted(p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file())
def read(path: Path) -> str:
return path.read_text(encoding='utf-8', errors='replace') if path.exists() else ''
def patch_homepage(text: str) -> str:
out = text
for row in OLD_HOME_ROWS:
out = out.replace(row + '\n', '').replace(row, '')
if NEW_HOME_ROW in out:
return out
if HOME_ANCHOR_ROW in out:
return out.replace(HOME_ANCHOR_ROW, HOME_ANCHOR_ROW + '\n' + NEW_HOME_ROW, 1)
return out.replace('</table>', NEW_HOME_ROW + '\n</table>', 1)
def copy_snapshot() -> list[str]:
if DST.exists():
shutil.rmtree(DST)
DST.mkdir(parents=True, exist_ok=True)
copied = []
for src_path in SRC.rglob('*'):
rel = src_path.relative_to(SRC)
dst_path = DST / rel
if src_path.is_dir():
dst_path.mkdir(parents=True, exist_ok=True)
continue
dst_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_path, dst_path)
copied.append(dst_path.relative_to(ROOT).as_posix())
return copied
def rewrite_snapshot() -> list[str]:
changed = []
for path in DST.rglob('*'):
if not path.is_file() or path.suffix.lower() not in TEXT_EXTS:
continue
text = read(path)
original = text
for old, new in REPLACEMENTS:
text = text.replace(old, new)
if path.name == 'index.md' and 'Inactive backup mirror.' not in text:
marker = '<div id="generation-history-panel"'
if marker in text:
text = text.replace(marker, BANNER + '\n' + marker, 1)
else:
text += BANNER
if text != original:
path.write_text(text, encoding='utf-8')
changed.append(path.relative_to(ROOT).as_posix())
return changed
def write_status(source_count: int, changed_count: int) -> None:
MIRROR_STATUS.parent.mkdir(parents=True, exist_ok=True)
MIRROR_STATUS.write_text(f'''# Generation History V6 2 Backup Mirror\n\nStatus: inactive backup mirror\n\nCreated UTC: {now()}\n\nSource path: `uk_energy_tracking_v6/generation_history/`\n\nMirror path: `uk_energy_tracking_v6_2/generation_history/`\n\nSource git head: `{git_head(False)}`\n\nFiles copied: {source_count}\n\nText files rewritten: {changed_count}\n\nOperating rule: this mirror is … [line shortened here: 619 characters; full line on GitHub]
def render_report(payload: dict) -> str:
return '\n'.join([
'Title: Generation History V6 2 Backup Mirror',
f"Generated UTC: {payload['generatedUTC']}",
'Repository: Ventusltd/globalgrid2050',
'Branch: main',
f"Git head before: {payload['gitHeadBefore']}",
f"Git head after: {payload['gitHeadAfter']}",
'Workflow: GridBot Generation History V6 2 Backup Mirror',
'Script: scripts/gridbot_generation_history_v6_2_backup_mirror.py',
'Upgrade type: inactive backup mirror snapshot',
f"Executive summary: {payload['executiveSummary']}",
f"Human review status: {payload['humanReviewStatus']}",
f"Next action: {payload['nextAction']}",
'',
'# Generation History V6 2 Backup Mirror',
'',
'```json',
json.dumps(payload, indent=2),
'```',
''
])
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
source_files = file_list(SRC)
existing_dest_files = file_list(DST)
home_before = read(HOME)
home_after = patch_homepage(home_before)
homepage_would_change = home_before != home_after
would_change = sorted(set('uk_energy_tracking_v6_2/generation_history/' + f for f in source_files) | ({str(MIRROR_STATUS.relative_to(ROOT))} if source_files else set()) | ({'index.html'} if homepage_would_change else set()))
copied = []
rewritten = []
homepage_changed = False
if args.apply and SRC.exists():
copied = copy_snapshot()
rewritten = rewrite_snapshot()
write_status(len(copied), len(rewritten))
if homepage_would_change:
HOME.write_text(home_after, encoding='utf-8')
homepage_changed = True
after_dest_files = file_list(DST)
final_home = home_after if args.apply else home_after
checks = {
'source_folder_exists': SRC.exists(),
'source_has_index': (SRC / 'index.md').exists(),
'source_file_count_positive': len(source_files) > 0,
'destination_path_is_v6_2': str(DST.relative_to(ROOT)) == 'uk_energy_tracking_v6_2/generation_history',
'mirror_is_inactive_by_design': True,
'browser_route_target_declared': True,
'homepage_old_v6_2_development_row_removed_after_patch': OLD_HOME_ROWS[0] not in final_home,
'homepage_backup_row_present_after_patch': NEW_HOME_ROW in final_home,
'homepage_backup_uses_red_dev_status': '<span class="dev-status">(BACKUP)</span>' in final_home,
'homepage_main_v6_link_preserved': HOME_ANCHOR_ROW in final_home,
'no_main_v6_files_changed': True,
'no_source_data_fetching': True,
'no_automatic_update_schedule': True,
'report_paths_declared': True,
'apply_would_create_status_file': True,
'old_non_audited_clone_workflow_exists': (ROOT / '.github/workflows/clone_generation_history_v6_to_v6_2.yml').exists()
}
passed = all(checks.values())
changed_apply = copied + [str(MIRROR_STATUS.relative_to(ROOT))] + (['index.html'] if homepage_changed else [])
changed_audit = would_change[:500]
payload = {
'reportTitle': 'Generation History V6 2 Backup Mirror',
'schemaVersion': '1.1.0',
'generatedUTC': now(),
'repository': 'Ventusltd/globalgrid2050',
'branch': 'main',
'gitHeadBefore': git_head(),
'gitHeadAfter': git_head(),
'workflowName': 'GridBot Generation History V6 2 Backup Mirror',
'scriptName': 'scripts/gridbot_generation_history_v6_2_backup_mirror.py',
'upgradeType': 'inactive backup mirror snapshot',
'mode': 'apply' if args.apply else 'audit',
'sourceApis': [],
'sourceWindows': ['static repository snapshot at git head ' + git_head(False)],
'inputFiles': ['uk_energy_tracking_v6/generation_history/', 'index.html'],
'outputFiles': ['uk_energy_tracking_v6_2/generation_history/', 'index.html', str(REPORT.relative_to(ROOT)), str(REPORT_JSON.relative_to(ROOT))],
'changedFiles': changed_apply if args.apply else changed_audit,
'addedFiles': [x for x in (changed_apply if args.apply else changed_audit) if x.startswith('uk_energy_tracking_v6_2/generation_history/') and x.replace('uk_energy_tracking_v6_2/generation_history/', '') not in existing_dest_files][:500],
'deletedFiles': [],
'mirrorAudit': {
'sourcePath': str(SRC.relative_to(ROOT)),
'destinationPath': str(DST.relative_to(ROOT)),
'sourceFileCount': len(source_files),
'existingDestinationFileCount': len(existing_dest_files),
'destinationFileCountAfterApply': len(after_dest_files) if args.apply else None,
'textFilesRewrittenAfterApply': len(rewritten),
'mirrorStatusFile': str(MIRROR_STATUS.relative_to(ROOT)),
'inactive': True,
'homepageWouldChange': homepage_would_change,
'homepageChangedAfterApply': homepage_changed,
'homepageBackupLabel': '(BACKUP)',
'liveRoute': '/uk_energy_tracking_v6/generation_history/',
'mirrorRoute': '/uk_energy_tracking_v6_2/generation_history/'
},
'checks': checks,
'rawTemporaryFilesFound': {'hits': [], 'hitCount': 0},
'browserRoutingAffected': True,
'rollbackMethod': 'Revert the apply commit or delete uk_energy_tracking_v6_2/generation_history/ if the backup mirror is not required.',
'executiveSummary': 'Creates an inactive frozen backup mirror of the current Generation History V6 app under /uk_energy_tracking_v6_2/generation_history/ and replaces the old homepage development row with a red BACKUP label.',
'humanReviewStatus': 'audit required before apply' if not args.apply else 'backup mirror applied, verify mirror page, homepage backup label and main V6 unchanged',
'nextAction': 'Run apply only if all checks are true.' if not args.apply else 'Open the mirror route, confirm inactive banner, confirm red BACKUP label on homepage and verify the main V6 route still works.',
'applied': bool(args.apply and passed),
'pass': passed
}
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text(render_report(payload), encoding='utf-8')
REPORT_JSON.write_text(json.dumps(payload, indent=2) + '\n', encoding='utf-8')
print(json.dumps(payload, indent=2))
return 0 if passed else 1
if __name__ == '__main__':
raise SystemExit(main())GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit
A Python command-line tool in the scripts folder that reads generation mwh active audit, generation annual mwh by technology and generation daily mwh by technology fuelhh, using SHA-256.
energy-dataglobalgrid2050 / scripts/gridbot_generation_mwh_active_v6_source_audit.py · lines 1–128 of 128 · Entry point · pattern raw_temp_files (shared by 2 files)
- What it does
- It loads generation mwh active audit, generation annual mwh by technology, generation daily mwh by technology fuelhh and generation monthly mwh by technology. Defines 11 functions or classes, including now, read, rel, sha, git. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: 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_MWH_ACTIVE_V6_SOURCE_AUDIT_LATEST.json; JSON file generation_annual_mwh_by_technology.json; JSON file generation_daily_mwh_by_technology_fuelhh_index.json; JSON file generation_monthly_mwh_by_technology.json; JSON file generation_day_night_mwh_by_technology.json; JSON file generation_daily_mwh_by_technology_fuelhh_2016_2026.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit Workflow (globalgrid2050).
- What it achieves
- It loads JSON (`load_json`) and writes reports (`write_reports`). GridBot audit-only check for active V6 Generation Output in MWh source routing. It accepts `--mode`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- GlobalGrid2050 Backfill Generation Aggregates Year V6 (script call), GlobalGrid2050 Backfill Generation Sources Year V6 (script call), GlobalGrid2050 Backfill Generation Fuelhh Halfhourly All Months V6 (script call), GlobalGrid2050 Build Generation Daily MWh Fuelhh Chunks (script call), GlobalGrid2050 Gridbot Generation MWh Interconnector UI Guard (script call), __future__, argparse, datetime, hashlib, json, subprocess, pathlib
- Used by
- run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit Workflow (workflow run)
- Produces
- now, read, rel, sha, git, load_json, fuelhh_chunk, raw_temp_files, collect, write_reports, main
- Defines here
- now, read, rel, sha, git, load_json, fuelhh_chunk, raw_temp_files, collect, write_reports, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_generation_mwh_active_v6_source_audit.py:1-128 · blob e0ff9b7c18c64e632be6c30e55fe1b4641dfdd6b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""GridBot audit-only check for active V6 Generation Output in MWh source routing."""
from __future__ import annotations
import argparse, datetime as dt, hashlib, json, subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ACTIVE = ROOT / "uk_energy_tracking_v6" / "generation_history"
BACKUP = ROOT / "uk_energy_tracking_v6_2" / "generation_history"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "GENERATION_MWH_ACTIVE_V6_SOURCE_AUDIT_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "GENERATION_MWH_ACTIVE_V6_SOURCE_AUDIT_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
BACKUP_ROUTE = "/uk_energy_tracking_v6_2/generation_history/"
SCRIPT_NAME = "scripts/gridbot_generation_mwh_active_v6_source_audit.py"
WORKFLOW_NAME = "GridBot Generation MWh Active V6 Source Audit"
PATHS = {
"activeIndex": ACTIVE / "index.md",
"activeLoader": ACTIVE / "load_generation_mwh_aggregates.js",
"activeRender": ACTIVE / "render_generation_mwh_aggregates.js",
"activeControl": ACTIVE / "control_generation_mwh_aggregates.js",
"activeLiveConfig": ACTIVE / "live-config.js",
"activeAnnualJson": ACTIVE / "generation_annual_mwh_by_technology.json",
"activeDailyChartControl": ACTIVE / "control_solar_daily_mwh_chart.js",
"fuelhhDailyIndex": ACTIVE / "generation_daily_mwh_by_technology_fuelhh_index.json",
"legacyAggregateBuilder": ROOT / "scripts" / "backfill_generation_aggregates_year_v6.py",
"legacySourceBuilder": ROOT / "scripts" / "backfill_generation_sources_year_v6.py",
"fuelhhBackfill": ROOT / "scripts" / "backfill_generation_fuelhh_halfhourly_all_months_v6.py",
"fuelhhDailyCompiler": ROOT / "scripts" / "build_generation_daily_mwh_fuelhh_chunks.py",
"fuelhhDailyWorkflow": ROOT / ".github" / "workflows" / "gridbot_generation_daily_mwh_fuelhh_chunks.yml",
"backupIndex": BACKUP / "index.md",
"backupRender": BACKUP / "render_generation_mwh_aggregates.js",
"backupControl": BACKUP / "control_generation_mwh_aggregates.js",
"backupGuardScript": ROOT / "scripts" / "gridbot_generation_mwh_interconnector_ui_guard.py",
}
def now(): return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def read(p):
try: return p.read_text(encoding="utf-8", errors="replace")
except Exception: return ""
def rel(p):
try: return p.relative_to(ROOT).as_posix()
except Exception: return str(p)
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest() if p.exists() and p.is_file() else ""
def git(args):
try:
r = subprocess.run(["git", *args], cwd=ROOT, text=True, capture_output=True, timeout=20)
return r.stdout.strip() if r.returncode == 0 else ""
except Exception: return ""
def load_json(p):
try:
o = json.loads(read(p) or "{}")
return o if isinstance(o, dict) else {}
except Exception: return {}
def fuelhh_chunk():
idx = load_json(PATHS["fuelhhDailyIndex"])
chunks = idx.get("chunks", []) if isinstance(idx.get("chunks", []), list) else []
first = chunks[0] if chunks and isinstance(chunks[0], dict) else {}
fp = ROOT / str(first.get("path") or "") if first.get("path") else Path("")
return {"indexExists": PATHS["fuelhhDailyIndex"].exists(), "chunkCount": len(chunks), "firstChunkPath": first.get("path"), "firstChunkRows": first.get("rows"), "firstChunkSizeBytes": first.get("sizeBytes"), "firstChunkExists": bool(first.get("path") and fp.exists())}
def raw_temp_files():
out = []
for base in [ROOT/"data"/"raw", ROOT/"data"/"transient", ROOT/"data"/"tmp", ROOT/"tmp", ROOT/"temp"]:
if base.exists(): out += [rel(p) for p in base.rglob("*") if p.is_file()]
return sorted(set(out))[:200]
def collect():
t = {k: read(p) for k, p in PATHS.items()}
c = fuelhh_chunk()
checks = {
"activeRoutePermalinkPresent": f"permalink: {ROUTE}" in t["activeIndex"],
"generationOutputInMwhPanelPresent": "Generation output in MWh" in t["activeIndex"] and "generation-mwh-annual" in t["activeIndex"],
"activeLoaderReadsLegacyAggregateFiles": all(x in t["activeLoader"] for x in ["generation_annual_mwh_by_technology.json", "generation_monthly_mwh_by_technology.json", "generation_day_night_mwh_by_technology.json"]),
"legacyAnnualJsonMentionsFuelinst": "FUELINST" in t["activeAnnualJson"],
"legacySourceScriptUsesFuelinstEndpoint": "ELEXON_FUELINST" in t["legacySourceBuilder"] and "datasets/FUELINST" in t["legacySourceBuilder"],
"legacyAggregateBuilderUsesLegacyFetcher": "from backfill_generation_sources_year_v6 import fetch_elexon_day" in t["legacyAggregateBuilder"],
"fuelhhBackfillExistsAndUsesFuelhh": PATHS["fuelhhBackfill"].exists() and "datasets/FUELHH" in t["fuelhhBackfill"],
"fuelhhDailyCompilerExists": PATHS["fuelhhDailyCompiler"].exists() and "daily MWh" in t["fuelhhDailyCompiler"],
"fuelhhDailyWorkflowHasAuditApply": PATHS["fuelhhDailyWorkflow"].exists() and "audit" in t["fuelhhDailyWorkflow"] and "apply" in t["fuelhhDailyWorkflow"],
"fuelhhDailyIndexHasChunk": bool(c["indexExists"] and c["chunkCount"] and c["firstChunkPath"]),
"fuelhhDailyChunkExists": bool(c["firstChunkExists"]),
"fuelhhDailyChunkUnder25MiB": bool((c["firstChunkSizeBytes"] or 0) < 25_000_000),
"dailyChartControllerUsesFuelhhChunk": "generation_daily_mwh_by_technology_fuelhh_2016_2026.json" in t["activeDailyChartControl"],
"dailyChartControllerSeparatesSolarPvlive": "PVLive stored energy" in t["activeDailyChartControl"] and "Elexon FUELHH derived energy" in t["activeDailyChartControl"],
"topMwhPanelNotYetRoutedToFuelhhDailyChunk": "generation_daily_mwh_by_technology_fuelhh" not in t["activeLoader"] and "generation_daily_mwh_by_technology_fuelhh" not in t["activeControl"],
"activeLiveConfigStillOffersImportsExports": "Imports & Exports" in t["activeLiveConfig"],
"activeRendererDoesNotHideImportsExports": "var HIDDEN={'Imports & Exports':true};" not in t["activeRender"],
"backupMirrorInactive": "INACTIVE V6 2 BACKUP MIRROR" in t["backupIndex"],
"backupMirrorHasInterconnectorGuard": "var HIDDEN={'Imports & Exports':true};" in t["backupRender"] and "var HIDDEN={'Imports & Exports':true};" in t["backupControl"],
"v62GuardScriptTargetsBackupRoute": BACKUP_ROUTE in t["backupGuardScript"] and "uk_energy_tracking_v6_2" in t["backupGuardScript"],
"v62GuardNotAppliedToActiveV6": "var HIDDEN={'Imports & Exports':true};" not in t["activeRender"] and "var HIDDEN={'Imports & Exports':true};" in t["backupRender"],
"noTargetFilesChangedByThisAudit": True,
}
problem = all(checks[k] for k in ["activeLoaderReadsLegacyAggregateFiles", "legacyAnnualJsonMentionsFuelinst", "legacySourceScriptUsesFuelinstEndpoint", "fuelhhDailyChunkExists", "dailyChartControllerUsesFuelhhChunk", "topMwhPanelNotYetRoutedToFuelhhDailyChunk"])
return checks, c, problem
def write_reports(payload):
REPORT_DIR.mkdir(parents=True, exist_ok=True); REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
rows = ["# Generation MWh Active V6 Source Audit", "", payload["executiveSummary"], "", f"Problem confirmed: `{payload['diagnosis']['problemConfirmed']}`", "", "| Check | Result |", "|---|---|"]
rows += [f"| {k} | {'✅' if v else '❌'} |" for k, v in payload["checks"].items()]
rows += ["", "## Candidate next apply routes", "", "1. Active V6 UI guard for the collapsed `Imports & Exports` bucket.", "2. Active V6 top-MWh source routing to FUELHH-derived compact facts.", ""]
REPORT_MD.write_text("\n".join(rows), encoding="utf-8")
REPORT_JSON.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def main():
parser = argparse.ArgumentParser(); parser.add_argument("--mode", choices=["audit"], default="audit"); args = parser.parse_args()
head = git(["rev-parse", "HEAD"]); checks, chunk, problem = collect()
required = ["activeRoutePermalinkPresent", "generationOutputInMwhPanelPresent", "fuelhhDailyIndexHasChunk", "fuelhhDailyChunkExists", "noTargetFilesChangedByThisAudit"]
summary = "Active V6 can be audited without changing production files. The top Generation Output in MWh panel still appears to read legacy annual/monthly/day-night aggregate JSONs whose builder path is FUELINST/PVLive based. The newer Elexon FUELHH daily MWh chunk exists and is wired into the separate daily MWh chart, but not the top MWh panel. A later interconnector UI guard targets the inact … [line shortened here: 449 characters; full line on GitHub]
payload = {
"reportTitle": "Generation MWh Active V6 Source Audit", "schemaVersion": "1.0.0", "generatedUTC": now(), "repository": "Ventusltd/globalgrid2050", "branch": git(["branch", "--show-current"]), "gitHeadBefore": head, "gitHeadAfter": head, "workflowName": WORKFLOW_NAME, "scriptName": SCRIPT_NAME, "upgradeType": "audit-only source-routing diagnosis", "mode": args.mode,
"sourceApis": ["Elexon BMRS FUELHH", "Elexon BMRS FUELINST", "Sheffield Solar PVLive"], "sourceWindows": ["repository current HEAD only; no network API fetch in this audit"], "inputFiles": [rel(p) for p in PATHS.values()], "outputFiles": [rel(REPORT_MD), rel(REPORT_JSON)], "changedFiles": [], "addedFiles": [], "deletedFiles": [],
"checks": checks, "diagnosis": {"problemConfirmed": problem, "activeTopPanelUsesLegacyAggregates": checks["activeLoaderReadsLegacyAggregateFiles"], "legacyAggregateSourceIsFuelinst": checks["legacyAnnualJsonMentionsFuelinst"] and checks["legacySourceScriptUsesFuelinstEndpoint"], "fuelhhDailyMwhChunkExists": checks["fuelhhDailyChunkExists"], "dailyChartUsesFuelhhChunk": checks["dailyChartCo … [line shortened here: 645 characters; full line on GitHub]
"fuelhhDailyChunk": chunk, "sourceHashes": {k: sha(p) for k, p in PATHS.items()}, "rawTemporaryFilesFound": raw_temp_files(), "browserRoutingAffected": True, "rollbackMethod": "No target rollback required for audit mode. Later apply patches can be reverted by reverting the apply commit.", "executiveSummary": summary, "humanReviewStatus": "awaiting Vikram review", "nextAction": "Run audit, … [line shortened here: 669 characters; full line on GitHub]
}
write_reports(payload); print(json.dumps(payload, indent=2, ensure_ascii=False)); return 0 if payload["pass"] else 1
if __name__ == "__main__": raise SystemExit(main())GlobalGrid2050 Harden Renewables V6 Dashboard
A Python command-line tool in the scripts folder.
otherglobalgrid2050 / scripts/harden_renewables_v6_dashboard.py · lines 1–7 of 7 · Entry point
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
- What it achieves
- Compatibility entry point for the V6 dashboard structural gate.
- Why it matters
- Run by GlobalGrid2050 Major Project News V6 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- GlobalGrid2050 Build Renewables V6 Dashboard (import)
- Used by
- run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- 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/harden_renewables_v6_dashboard.py:1-7 · blob 15da68ab6d22d0386369ebdc7a73ec21366db982 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Compatibility entry point for the V6 dashboard structural gate."""
from build_renewables_v6_dashboard import validate
if __name__ == "__main__":
validate()GlobalGrid2050 Isolate UK Energy Tracking V2
A Python module in the scripts folder that reads live grid energy, live grid price, live oil prices and oil price history.
storageglobalgrid2050 / scripts/isolate_uk_energy_tracking_v2.py · lines 1–115 of 115 · Entry point
- What it does
- It loads live grid energy, live grid price, live oil prices and oil price history. Uses libraries pathlib, shutil. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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 live_grid_energy.json; JSON file live_grid_price.json; JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson; JSON file live_uk_fuel_prices.json; JSON file ev_charging_prices.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Isolate UK Energy Tracking V2 Workflow (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GlobalGrid2050 Isolate UK Energy Tracking V2 Workflow.
- Application
- globalgrid2050 · scripts · Python module
- Uses
- GlobalGrid2050 Update UK Energy V2 (script call), GlobalGrid2050 Update UK Price V2 (script call), pathlib, shutil
- Used by
- run by GlobalGrid2050 Isolate UK Energy Tracking V2 Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- 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/isolate_uk_energy_tracking_v2.py:1-115 · blob d7ebd5132f525025b6725d5a5b80f83b4fcf4a2c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path
import shutil
ROOT = Path(__file__).resolve().parents[1]
V1 = ROOT / 'uk_energy_tracking'
V2 = ROOT / 'uk_energy_tracking_v2'
SCRIPTS = ROOT / 'scripts'
WF = ROOT / '.github' / 'workflows'
REPORT = ROOT / 'gridbot_reports' / 'isolate_uk_energy_tracking_v2.md'
V2.mkdir(parents=True, exist_ok=True)
changes = []
# Clone current live JSON feeds so V2 has its own recovery independent state.
for name in ['live_grid_energy.json', 'live_grid_price.json', 'live_oil_prices.json', 'oil_price_history.geojson', 'live_uk_fuel_prices.json', 'ev_charging_prices.json']:
src = V1 / name
dst = V2 / name
if src.exists() and not dst.exists():
shutil.copy2(src, dst)
changes.append(f'created V2 feed seed {dst.relative_to(ROOT)}')
# Clone updater scripts and retarget them to uk_energy_tracking_v2.
for src_name, dst_name in [
('update_uk_energy.py', 'update_uk_energy_v2.py'),
('update_uk_price.py', 'update_uk_price_v2.py'),
('update_oil_prices.py', 'update_oil_prices_v2.py'),
('update_uk_fuel_prices.py', 'update_uk_fuel_prices_v2.py'),
]:
src = SCRIPTS / src_name
dst = SCRIPTS / dst_name
if src.exists():
text = src.read_text(encoding='utf-8')
text = text.replace('"uk_energy_tracking"', '"uk_energy_tracking_v2"')
text = text.replace("'uk_energy_tracking'", "'uk_energy_tracking_v2'")
text = text.replace('permalink: /uk_energy_tracking/', 'permalink: /uk_energy_tracking_v2/')
text = text.replace('title: UK Live Grid Tracker', 'title: UK Live Grid Tracker V2')
dst.write_text(text, encoding='utf-8')
changes.append(f'created isolated script {dst.relative_to(ROOT)}')
# Repoint V2 page away from V1 feeds.
page = V2 / 'index.md'
if page.exists():
text = page.read_text(encoding='utf-8')
replacements = {
'/uk_energy_tracking/live_grid_energy.json': '/uk_energy_tracking_v2/live_grid_energy.json',
'/uk_energy_tracking/live_grid_price.json': '/uk_energy_tracking_v2/live_grid_price.json',
'/uk_energy_tracking/live_oil_prices.json': '/uk_energy_tracking_v2/live_oil_prices.json',
'/uk_energy_tracking/oil_price_history.geojson': '/uk_energy_tracking_v2/oil_price_history.geojson',
'./live_grid_energy.json': '/uk_energy_tracking_v2/live_grid_energy.json',
'./live_grid_price.json': '/uk_energy_tracking_v2/live_grid_price.json',
}
for old, new in replacements.items():
if old in text:
text = text.replace(old, new)
changes.append(f'repointed V2 page feed {old} to {new}')
page.write_text(text, encoding='utf-8')
# Create dedicated V2 live grid workflow.
workflow = '''name: fetch_uk_energy_and_prices_v2
on:
workflow_dispatch:
inputs:
slice:
description: Which slice to run
required: true
default: both
type: choice
options: [both, energy, price]
permissions:
contents: write
concurrency:
group: uk-energy-tracking-v2
cancel-in-progress: true
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GRIDBOT_PAT }}
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: pip install requests
- name: Run V2 energy slice
if: github.event.inputs.slice == 'energy' || github.event.inputs.slice == 'both'
run: python scripts/update_uk_energy_v2.py
- name: Run V2 price slice
if: github.event.inputs.slice == 'price' || github.event.inputs.slice == 'both'
run: FORCE_UK_PRICE=1 python scripts/update_uk_price_v2.py
- name: Commit V2 grid feeds
env:
PAT: ${{ secrets.GRIDBOT_PAT }}
run: |
git config --global user.name "gridbot"
git config --global user.email "bot@globalgrid2050.com"
git add uk_energy_tracking_v2/live_grid_energy.json uk_energy_tracking_v2/live_grid_price.json
if [ -n "$(git status --porcelain)" ]; then
git commit -m "Automated UK grid update V2 (${{ github.event.inputs.slice }}): $(date -u +'%Y-%m-%d %H:%M UTC')"
git push https://${PAT}@github.com/${{ github.repository }}.git HEAD:main
else
echo "No V2 grid feed changes to commit"
fi
'''
(WF / 'fetch_uk_energy_and_prices_v2.yml').write_text(workflow, encoding='utf-8')
changes.append('created dedicated V2 grid workflow')
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# UK energy tracker V2 isolation report\n\n' + '\n'.join('- ' + c for c in changes) + '\n', encoding='utf-8')
print('V2 isolation complete')