GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Patch UK Energy Oil Dashboard Interactivity and 4 more files

A Python module in the scripts folder that draws oil price history.

441 lines of Python from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 882 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 News Binder Refaware energy-data · globalgrid2050 / scripts/news_binder_refaware.py lines 701–704
  2. GlobalGrid2050 Patch UK Energy Oil Dashboard Interactivity render · globalgrid2050 / scripts/patch_uk_energy_oil_dashboard_interactivity.py lines 1–162
  3. GlobalGrid2050 Patch UK Energy Tracking V2 Oil Graph render · globalgrid2050 / scripts/patch_uk_energy_tracking_v2_oil_graph.py lines 1–45
  4. GlobalGrid2050 Patch UK Energy Tracking V2 Transport render · globalgrid2050 / scripts/patch_uk_energy_tracking_v2_transport.py lines 1–157
  5. GlobalGrid2050 Patch V3 Price Axis Table Fullscreen energy-data · globalgrid2050 / scripts/patch_v3_price_axis_table_fullscreen.py lines 1–73

GlobalGrid2050 News Binder Refaware

A Python module in the scripts folder that reads solar, the Renewable Energy Planning Database (REPD) register and battery storage (BESS), using SHA-256.

energy-dataglobalgrid2050 / scripts/news_binder_refaware.py · lines 701–704 of 704 (continued from section 881) · Entry point · pattern evaluate_candidate (shared by 2 files)

What it does
It loads solar, the REPD register and battery storage (BESS). Defines 20 functions or classes, including normalise_operator_parties, operator_party_key, raw_stem_tokens, stem_qualifier, extract_capacities. Uses libraries __future__, hashlib, json, re, sys. 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. Domain terms in the code: solar, the REPD register, battery storage (BESS).
Downstream impact
Used directly by 2 files: GlobalGrid2050 Build News Feed 2026q3 (globalgrid2050); GlobalGrid2050 Test News Binder Refaware (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It normalises operator parties (`normalise_operator_parties`), extracts capacities (`extract_capacities`) and prepares projects (`prepare_projects`). Ref-aware news-to-REPD binder (successor candidate to the V6 matcher). Its code works with 900 MW.
Why it matters
Imported by GlobalGrid2050 Build News Feed 2026q3. Checked by GlobalGrid2050 Test News Binder Refaware.
Application
globalgrid2050 · scripts · Python module
Uses
GlobalGrid2050 Major Project News V6 (import), __future__, hashlib, json, re, sys, collections, datetime, pathlib
Used by
imported by GlobalGrid2050 Build News Feed 2026q3 (import), imported by GlobalGrid2050 Test News Binder Refaware (import)
Produces
normalise_operator_parties, operator_party_key, raw_stem_tokens, stem_qualifier, extract_capacities, prepare_projects, event_v2, story_context, evaluate_candidate, resolve_story, load_universe, repd_status_change_candidates
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/news_binder_refaware.py:701-704 · blob 8f8ef07eee287862ff148dc19e094056896ea027 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
                change["corroborating_articles"].append(article["gg_article_id"])
                article.setdefault("corroborates_repd_status_change", []).append(change["gg_status_change_id"])
                linked += 1
    return linked

GlobalGrid2050 Patch UK Energy Oil Dashboard Interactivity

A Python module in the scripts folder that draws oil price history.

renderglobalgrid2050 / scripts/patch_uk_energy_oil_dashboard_interactivity.py · lines 1–162 of 162 · Entry point

What it does
It draws oil price history. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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: GeoJSON file oil_price_history.geojson; form fields (user input). Out: canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch UK Energy Oil Dashboard 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 Patch UK Energy Oil Dashboard Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Patch UK Energy Oil Dashboard 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/patch_uk_energy_oil_dashboard_interactivity.py:1-162 · blob 7e7e279e305c7e17b6a1e3eca2154f07e682c5e9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path

PAGE = Path(__file__).parent.parent / "uk_energy_tracking" / "index.md"
text = PAGE.read_text(encoding="utf-8")

# 1. Add / upgrade dashboard CSS for tooltip, stats, clearer axis units and touch line.
legacy_css = "#oil-trend-canvas { width:100%; height:260px; display:block; border:1px solid rgba(255,255,255,.05); background:#070a10; }"
new_css = """#oil-trend-canvas { width:100%; height:300px; display:block; border:1px solid rgba(255,255,255,.05); background:#070a10; touch-action:none; }
.oil-chart-wrap { position:relative; }
.oil-tooltip { position:absolute; display:none; pointer-events:none; background:rgba(5,5,5,.94); border:1px solid var(--gg-cyan); color:var(--gg-text); padding:8px 10px; border-radius:4px; font-size:12px; line-height:1.45; box-shadow:0 0 18px rgba(0,255,255,.12); z-index:5; }
.oil-stats-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:10px; margin-top:10px; }
.oil-stat { border:1px solid var(--gg-line); background:rgba(255,255,255,.03); border-radius:4px; padding:9px; }
.oil-stat-label { color:var(--gg-muted); text-transform:uppercase; letter-spacing:.12em; font-size:10px; }
.oil-stat-value { color:var(--gg-cyan); font-size:16px; font-weight:800; margin-top:4px; }
.unit-panel { border:1px solid var(--gg-line); background:rgba(255,255,255,.03); border-radius:6px; padding:10px 12px; margin-top:10px; color:var(--gg-muted); font-size:12px; line-height:1.5; }
.unit-panel strong { color:var(--gg-text); }
@media (max-width: 850px) { .oil-stats-grid { grid-template-columns:1fr 1fr; } }"""
if legacy_css in text:
    text = text.replace(legacy_css, new_css)

# 2. Replace old compact oil block if present.
old_block = """<strong style=\"color:#00ffff;letter-spacing:.12em;text-transform:uppercase;\">Oil Price Trend</strong>
        <select id=\"oil-range\"><option value=\"1\">1 year</option><option value=\"5\">5 years</option><option value=\"10\">10 years</option><option value=\"25\">25 years</option><option value=\"all\" selected>Since 1970s</option></select>
      </div>
      <canvas id=\"oil-trend-canvas\" width=\"900\" height=\"260\"></canvas>"""
new_block = """<strong style=\"color:#00ffff;letter-spacing:.12em;text-transform:uppercase;\">Oil Price Trend</strong>
        <select id=\"oil-range\">
          <option value=\"7d\">1 week</option>
          <option value=\"1m\">1 month</option>
          <option value=\"3m\">3 months</option>
          <option value=\"6m\">6 months</option>
          <option value=\"9m\">9 months</option>
          <option value=\"1y\">1 year</option>
          <option value=\"5y\">5 years</option>
          <option value=\"10y\">10 years</option>
          <option value=\"25y\">25 years</option>
          <option value=\"all\" selected>Since 1970s</option>
        </select>
      </div>
      <div class=\"unit-panel\"><strong>Unit:</strong> US dollars per barrel (USD/bbl). Touch or move across the graph to inspect date, Brent and WTI values.</div>
      <div class=\"oil-chart-wrap\"><canvas id=\"oil-trend-canvas\" width=\"900\" height=\"300\"></canvas><div id=\"oil-tooltip\" class=\"oil-tooltip\"></div></div>
      <div id=\"oil-stats\" class=\"oil-stats-grid\"></div>"""
if old_block in text:
    text = text.replace(old_block, new_block)

# 3. Replace the oil chart function with high / low labels, clearer left units and a touch guide line.
start = text.find("  var oilChartState =")
if start == -1:
    start = text.find("  function drawOilTrend(geo){")
end = text.find("  function refresh(){", start)
if start != -1 and end != -1:
    replacement = r'''  var oilChartState = { rows: [], x: null, y: null, canvas: null, activeIndex: null, min: 0, max: 0, pad: 54 };
  function rangeCutoff(range){
    if(range === "all") return null;
    var d = new Date();
    if(range === "7d") d.setDate(d.getDate()-7);
    else if(range === "1m") d.setMonth(d.getMonth()-1);
    else if(range === "3m") d.setMonth(d.getMonth()-3);
    else if(range === "6m") d.setMonth(d.getMonth()-6);
    else if(range === "9m") d.setMonth(d.getMonth()-9);
    else if(range === "1y") d.setFullYear(d.getFullYear()-1);
    else if(range === "5y") d.setFullYear(d.getFullYear()-5);
    else if(range === "10y") d.setFullYear(d.getFullYear()-10);
    else if(range === "25y") d.setFullYear(d.getFullYear()-25);
    return d;
  }
  function oilStats(rows){
    var vals=[]; rows.forEach(function(p){ if(p.brentUSDperBarrel) vals.push(p.brentUSDperBarrel); if(p.wtiUSDperBarrel) vals.push(p.wtiUSDperBarrel); });
    var el=document.getElementById("oil-stats"); if(!el) return;
    if(!vals.length){ el.innerHTML=""; return; }
    var high=Math.max.apply(null,vals), low=Math.min.apply(null,vals), avg=vals.reduce(function(a,b){return a+b;},0)/vals.length;
    var variance=vals.reduce(function(a,b){return a+Math.pow(b-avg,2);},0)/vals.length;
    var vol=avg?Math.sqrt(variance)/avg*100:0;
    el.innerHTML = [
      ["High", "$"+fmt(high,2)], ["Low", "$"+fmt(low,2)], ["Average", "$"+fmt(avg,2)], ["Volatility", fmt(vol,1)+"%"]
    ].map(function(x){return '<div class="oil-stat"><div class="oil-stat-label">'+x[0]+'</div><div class="oil-stat-value">'+x[1]+'</div></div>';}).join("");
  }
  function drawOilTrend(geo, activeIndex){
    var canvas=document.getElementById("oil-trend-canvas"); if(!canvas||!geo||!Array.isArray(geo.features)) return;
    var ctx=canvas.getContext("2d"), range=document.getElementById("oil-range").value;
    var rows=geo.features.map(function(f){return f.properties||{};}).filter(function(p){return p.date&&(p.brentUSDperBarrel||p.wtiUSDperBarrel);});
    var cutoff=rangeCutoff(range); if(cutoff) rows=rows.filter(function(p){return new Date(p.date)>=cutoff;});
    var w=canvas.width,h=canvas.height,pad=54,rightPad=28;
    ctx.clearRect(0,0,w,h); ctx.fillStyle="#070a10"; ctx.fillRect(0,0,w,h);
    if(rows.length<2) { ctx.fillStyle="#a6adbb"; ctx.font="14px Courier New"; ctx.fillText("Waiting for oil history data", pad, 42); oilStats([]); return; }
    var vals=[]; rows.forEach(function(p){ if(p.brentUSDperBarrel) vals.push(p.brentUSDperBarrel); if(p.wtiUSDperBarrel) vals.push(p.wtiUSDperBarrel); });
    var min=Math.min.apply(null,vals), max=Math.max.apply(null,vals); if(max===min){max=min+1;}
    function x(i){return pad+(i/(rows.length-1))*(w-pad-rightPad);} function y(v){return h-pad-((v-min)/(max-min))*(h-pad*1.85);}
    ctx.strokeStyle="#252b36"; ctx.lineWidth=1;
    ctx.fillStyle="#a6adbb"; ctx.font="12px Courier New";
    for(var g=0;g<5;g++){
      var value=max-(g*(max-min)/4), yy=y(value);
      ctx.beginPath();ctx.moveTo(pad,yy);ctx.lineTo(w-rightPad,yy);ctx.stroke();
      ctx.fillText("$"+fmt(value,0), 8, yy+4);
    }
    ctx.save();
    ctx.translate(14, h/2 + 70);
    ctx.rotate(-Math.PI/2);
    ctx.fillStyle="#a6adbb";
    ctx.font="11px Courier New";
    ctx.fillText("US dollars per barrel (USD/bbl)", 0, 0);
    ctx.restore();

    function line(field,colour){
      ctx.strokeStyle=colour;ctx.lineWidth=2;ctx.beginPath();var started=false;
      rows.forEach(function(p,i){var v=p[field];if(!v)return; if(!started){ctx.moveTo(x(i),y(v));started=true;}else{ctx.lineTo(x(i),y(v));}});
      ctx.stroke();
    }
    line("brentUSDperBarrel","#ff9900"); line("wtiUSDperBarrel","#00ffff");
    ctx.fillStyle="#a6adbb"; ctx.font="12px Courier New";
    ctx.fillText("Brent",pad,18); ctx.fillStyle="#ff9900"; ctx.fillRect(pad+46,10,18,4);
    ctx.fillStyle="#a6adbb"; ctx.fillText("WTI",pad+78,18); ctx.fillStyle="#00ffff"; ctx.fillRect(pad+112,10,18,4);

    var idx = Number.isFinite(activeIndex) ? Math.max(0, Math.min(rows.length-1, activeIndex)) : null;
    if(idx !== null){
      var xx=x(idx);
      ctx.strokeStyle="rgba(255,255,255,.85)";
      ctx.lineWidth=1.5;
      ctx.beginPath(); ctx.moveTo(xx, pad*0.72); ctx.lineTo(xx, h-pad); ctx.stroke();
      var p=rows[idx];
      ["brentUSDperBarrel","wtiUSDperBarrel"].forEach(function(field){
        var v=p[field]; if(!v) return;
        ctx.fillStyle = field==="brentUSDperBarrel" ? "#ff9900" : "#00ffff";
        ctx.beginPath(); ctx.arc(xx, y(v), 4, 0, Math.PI*2); ctx.fill();
      });
    }

    oilChartState={rows:rows,x:x,y:y,canvas:canvas,activeIndex:idx,min:min,max:max,pad:pad}; oilStats(rows); bindOilTooltip();
  }
  function bindOilTooltip(){
    var canvas=document.getElementById("oil-trend-canvas"), tip=document.getElementById("oil-tooltip"); if(!canvas||!tip||canvas.__oilTipBound) return;
    canvas.__oilTipBound=true;
    function show(e){
      var rect=canvas.getBoundingClientRect();
      var clientX=(e.touches&&e.touches[0]?e.touches[0].clientX:e.clientX);
      var px=(clientX-rect.left)*(canvas.width/rect.width);
      var rows=oilChartState.rows||[]; if(!rows.length) return;
      var pad=oilChartState.pad||54, rightPad=28;
      var idx=Math.max(0,Math.min(rows.length-1,Math.round((px-pad)/(canvas.width-pad-rightPad)*(rows.length-1))));
      drawOilTrend(window.__oilGeojsonCache, idx);
      var p=rows[idx];
      tip.innerHTML='<strong>'+p.date+'</strong><br>Brent: '+(p.brentUSDperBarrel?'$'+fmt(p.brentUSDperBarrel,2):'—')+' USD/bbl<br>WTI: '+(p.wtiUSDperBarrel?'$'+fmt(p.wtiUSDperBarrel,2):'—')+' USD/bbl';
      tip.style.display='block'; tip.style.left=Math.min(rect.width-190,Math.max(8,clientX-rect.left+12))+'px'; tip.style.top='42px';
    }
    function hide(){ tip.style.display='none'; drawOilTrend(window.__oilGeojsonCache, null); }
    canvas.addEventListener('mousemove',show); canvas.addEventListener('touchmove',show,{passive:true}); canvas.addEventListener('mouseleave',hide); canvas.addEventListener('touchend',hide);
  }
'''
    text = text[:start] + replacement + text[end:]

# 4. Cache oil GeoJSON for touch redraws.
text = text.replace("fetch(\"./oil_price_history.geojson?ts=\"+Date.now()).then(r=>r.json()).then(drawOilTrend).catch(()=>{});",
                    "fetch(\"./oil_price_history.geojson?ts=\"+Date.now()).then(r=>r.json()).then(function(g){ window.__oilGeojsonCache=g; drawOilTrend(g); }).catch(()=>{});")

# 5. Hide public raw JSON health diagnostics.
old_status = 's.textContent="Energy health: "+JSON.stringify(e.health||{})+" · Price health: "+JSON.stringify(p.health||{})+" · Oil health: "+JSON.stringify(oil.health||{});s.className="scada-status";'
new_status = 's.textContent="Data diagnostics recorded in JSON feeds. Energy, price, carbon and commodity source health are being tracked.";s.className="scada-status";'
if old_status in text:
    text = text.replace(old_status, new_status)

PAGE.write_text(text, encoding="utf-8")
print("Patched UK energy tracker oil chart labels, axis units and vertical touch line.")

GlobalGrid2050 Patch UK Energy Tracking V2 Oil Graph

A Python module in the scripts folder.

renderglobalgrid2050 / scripts/patch_uk_energy_tracking_v2_oil_graph.py · lines 1–45 of 45 · Entry point · pattern replace_once (shared by 21 files)

What it does
It loads data. Defines replace_once. Uses libraries pathlib. 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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch UK Energy Tracking V2 Oil Graph Workflow (globalgrid2050).
What it achieves
Defines `replace_once`.
Why it matters
Run by GlobalGrid2050 Patch UK Energy Tracking V2 Oil Graph Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Patch UK Energy Tracking V2 Oil Graph Workflow (workflow run)
Produces
replace_once
Defines here
replace_once
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/patch_uk_energy_tracking_v2_oil_graph.py:1-45 · blob 0869c58154a67dc8058e6dc3e6c4309d82cfbaeb · 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

ROOT = Path(__file__).parent.parent
TARGET = ROOT / "uk_energy_tracking_v2" / "index.md"
REPORT = ROOT / "gridbot_reports" / "patch_uk_energy_tracking_v2_oil_graph.md"

text = TARGET.read_text(encoding="utf-8")
changes = []

def replace_once(old, new, label):
    global text
    count = text.count(old)
    if count != 1:
        raise RuntimeError(f"{label}: expected 1 match, found {count}")
    text = text.replace(old, new, 1)
    changes.append(label)

replace_once(
    '<option value="25y">25 years</option>\n          <option value="all" selected>Since 1970s</option>',
    '<option value="25y" selected>25 years</option>',
    'remove misleading oil range option'
)

replace_once(
    'ctx.fillStyle="#a6adbb"; ctx.font="12px Courier New";\n    for(var g=0;g<5;g++){',
    'ctx.fillStyle="#f5f7fb"; ctx.font="16px Courier New";\n    for(var g=0;g<5;g++){',
    'make left axis values clearer'
)

replace_once(
    'ctx.beginPath();ctx.moveTo(pad,yy);ctx.lineTo(w-rightPad,yy);ctx.stroke();\n      ctx.fillText("$"+fmt(value,0), 8, yy+4);',
    'ctx.beginPath();ctx.moveTo(pad,yy);ctx.lineTo(w-rightPad,yy);ctx.stroke();\n      ctx.fillStyle="#f5f7fb"; ctx.fillText("$"+fmt(value,0), 8, yy+5); ctx.fillStyle="#f5f7fb";',
    'strengthen left axis label colour'
)

replace_once(
    'ctx.beginPath(); ctx.moveTo(xx, pad*0.72); ctx.lineTo(xx, h-pad); ctx.stroke();\n      var p=rows[idx];',
    'ctx.beginPath(); ctx.moveTo(xx, pad*0.72); ctx.lineTo(xx, h-pad); ctx.stroke();\n      var p=rows[idx];\n      ctx.setLineDash([5,5]);\n      ["brentUSDperBarrel","wtiUSDperBarrel"].forEach(function(field){ var v=p[field]; if(!v) return; var yy=y(v); ctx.strokeStyle = field==="brentUSDperBarrel" ? "rgba(255,153,0,.75)" : "rgba(0,255,255,.75)"; ctx.beginPath(); ctx.moveTo(pad, yy); ctx.lineTo(  … [line shortened here: 464 characters; full line on GitHub]
    'add horizontal guide line for active point'
)

TARGET.write_text(text, encoding="utf-8")
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# UK energy tracking V2 oil graph patch\n\n' + '\n'.join('- ' + c for c in changes) + '\n', encoding='utf-8')
print('Patched UK energy tracking V2 oil graph')

GlobalGrid2050 Patch UK Energy Tracking V2 Transport

A Python module in the scripts folder that draws live UK fuel prices, EV charging prices, live grid energy and live grid price.

renderglobalgrid2050 / scripts/patch_uk_energy_tracking_v2_transport.py · lines 1–157 of 157 · Entry point

What it does
It draws live UK fuel prices, EV charging prices, live grid energy and live grid price. Uses libraries pathlib, json, shutil. Side effects: changes the web page (DOM); 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_uk_fuel_prices.json; JSON file ev_charging_prices.json; JSON file live_grid_energy.json; JSON file live_grid_price.json; JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch UK Energy Tracking V2 Transport 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 Patch UK Energy Tracking V2 Transport Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib, json, shutil
Used by
run by GlobalGrid2050 Patch UK Energy Tracking V2 Transport 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/patch_uk_energy_tracking_v2_transport.py:1-157 · blob c68b6bb2d13fa73c7f123780d0463be7eb165311 · 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
from pathlib import Path
import json
import shutil

ROOT = Path(__file__).resolve().parents[1]
V1 = ROOT / 'uk_energy_tracking'
V2 = ROOT / 'uk_energy_tracking_v2'
PAGE = V2 / 'index.md'
REPORT = ROOT / 'gridbot_reports' / 'patch_uk_energy_tracking_v2_transport.md'

changes = []
V2.mkdir(parents=True, exist_ok=True)

# Seed isolated V2 data files from V1 where possible.
for name in ['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'seeded {dst.relative_to(ROOT)} from V1')

# Create an EV tariff placeholder if no curated file exists yet.
ev_file = V2 / 'ev_charging_prices.json'
if not ev_file.exists():
    ev_file.write_text(json.dumps({
        'updated': None,
        'unit': 'pence per kilowatt hour',
        'note': 'Curated EV charging tariff table for V2 transport energy comparison.',
        'operators': [
            {'operator': 'Gridserve', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://www.gridserve.com/electric-highway/', 'lastChecked': None},
            {'operator': 'Instavolt', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://instavolt.co.uk/', 'lastChecked': None},
            {'operator': 'BP Pulse', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://www.bppulse.co.uk/', 'lastChecked': None},
            {'operator': 'Shell Recharge', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://shellrecharge.com/', 'lastChecked': None},
            {'operator': 'Tesla Supercharger', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://www.tesla.com/en_gb/supercharger', 'lastChecked': None},
            {'operator': 'IONITY', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://ionity.eu/', 'lastChecked': None},
            {'operator': 'Osprey', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://ospreycharging.co.uk/', 'lastChecked': None},
            {'operator': 'Fastned', 'rapidPencePerKWh': None, 'ultraRapidPencePerKWh': None, 'membershipPencePerKWh': None, 'sourceUrl': 'https://fastnedcharging.com/', 'lastChecked': None}
        ]
    }, indent=2), encoding='utf-8')
    changes.append('created V2 EV charging tariff placeholder')

text = PAGE.read_text(encoding='utf-8')

css_marker = '@media (max-width: 850px) { .oil-stats-grid'
css_add = '''.fuel-logic-panel, .ev-panel { border:1px solid var(--gg-line); background:rgba(255,255,255,.03); border-radius:6px; padding:14px; margin-top:14px; color:var(--gg-muted); font-size:13px; line-height:1.55; }
.fuel-logic-panel strong, .ev-panel strong { color:var(--gg-text); }
.fuel-source-links { display:flex; flex-wrap:wrap; gap:10px; margin-top:10px; }
.fuel-source-links a { border:1px solid var(--gg-line); border-radius:4px; padding:7px 9px; color:#7fdfff; }
.ev-card-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:10px; margin-top:10px; }
.ev-card { border:1px solid var(--gg-line); background:var(--gg-panel); border-radius:6px; padding:12px; }
.ev-card-value { color:var(--gg-green); font-size:22px; font-weight:800; margin-top:6px; }
.ev-map-frame { width:100%; height:360px; border:1px solid var(--gg-line); border-radius:6px; margin-top:12px; background:#050505; }
@media (max-width: 850px) { .ev-card-grid { grid-template-columns:1fr; } .ev-map-frame { height:300px; } }
'''
if css_add.strip() not in text and css_marker in text:
    text = text.replace(css_marker, css_add + css_marker, 1)
    changes.append('inserted V2 transport CSS')

text = text.replace('This page uses V1 live feeds until V2 data pipelines are approved.', 'This page uses isolated V2 feeds for development and transport energy testing.')

var_old = 'var ENERGY="/uk_energy_tracking/live_grid_energy.json", PRICE="/uk_energy_tracking/live_grid_price.json", OIL="/uk_energy_tracking/live_oil_prices.json", OIL_HISTORY="/uk_energy_tracking/oil_price_history.geojson", POLL=5*60*1000;'
var_new = 'var ENERGY="/uk_energy_tracking_v2/live_grid_energy.json", PRICE="/uk_energy_tracking_v2/live_grid_price.json", OIL="/uk_energy_tracking_v2/live_oil_prices.json", OIL_HISTORY="/uk_energy_tracking_v2/oil_price_history.geojson", FUEL="/uk_energy_tracking_v2/live_uk_fuel_prices.json", EV_PRICES="/uk_energy_tracking_v2/ev_charging_prices.json", POLL=5*60*1000;'
if var_old in text:
    text = text.replace(var_old, var_new, 1)
    changes.append('repointed V2 dashboard to isolated V2 feeds')

old_section = '''  <section>
    <h2 class="section-title" style="font-size:18px;color:#a6adbb;">UK Pump Prices</h2>
    <div class="pump-grid">
      <div class="pump-card"><div class="pump-label">Petrol</div><div class="pump-value" id="petrol-price">—</div><div class="commodity-unit">Pence per litre</div></div>
      <div class="pump-card"><div class="pump-label">Diesel</div><div class="pump-value" id="diesel-price">—</div><div class="commodity-unit">Pence per litre</div></div>
    </div>
  </section>'''
new_section = '''  <section>
    <h2 class="section-title" style="font-size:18px;color:#a6adbb;">Road Fuel & EV Charging</h2>
    <div class="pump-grid">
      <div class="pump-card"><div class="pump-label">Petrol</div><div class="pump-value" id="petrol-price">—</div><div class="commodity-unit">DESNZ weekly average, pence per litre</div></div>
      <div class="pump-card"><div class="pump-label">Diesel</div><div class="pump-value" id="diesel-price">—</div><div class="commodity-unit">DESNZ weekly average, pence per litre</div></div>
    </div>
    <div class="fuel-logic-panel">
      <strong>Road fuel price logic:</strong> Brent crude is quoted in US dollars per barrel. A rough product cost proxy converts USD per barrel into GBP per litre by applying an FX assumption and dividing by about 159 litres per barrel. UK pump prices then add refining spread, wholesale margin, logistics, retail margin, fuel duty and VAT.
      <div id="fuel-breakdown" style="margin-top:10px;">Awaiting DESNZ fuel price feed.</div>
      <div class="fuel-source-links">
        <a href="https://www.gov.uk/government/statistics/weekly-road-fuel-prices" target="_blank" rel="noopener noreferrer">DESNZ weekly road fuel prices</a>
        <a href="https://www.gov.uk/tax-on-shopping/fuel-duty" target="_blank" rel="noopener noreferrer">GOV.UK fuel duty</a>
        <a href="https://www.gov.uk/vat-rates" target="_blank" rel="noopener noreferrer">GOV.UK VAT rates</a>
      </div>
    </div>
    <div class="ev-panel">
      <strong>EV charging comparison placeholder:</strong> Public EV tariffs will be compared with petrol, diesel, wholesale electricity and operator tariff data. The Atlas V8 reference is embedded below while the exact EV charging layer path is verified.
      <div class="ev-card-grid">
        <div class="ev-card"><div class="pump-label">Rapid EV</div><div class="ev-card-value" id="ev-rapid-price">Tariff table pending</div><div class="commodity-unit">Pence per kilowatt hour</div></div>
        <div class="ev-card"><div class="pump-label">Ultra rapid EV</div><div class="ev-card-value" id="ev-ultra-price">Tariff table pending</div><div class="commodity-unit">Pence per kilowatt hour</div></div>
        <div class="ev-card"><div class="pump-label">Atlas EV layer</div><div class="ev-card-value">Reference</div><div class="commodity-unit">Copy after exact Atlas V8 path is verified</div></div>
      </div>
      <iframe class="ev-map-frame" src="/repd_grid_atlasv8/" loading="lazy" title="Atlas V8 reference map"></iframe>
    </div>
  </section>'''
if old_section in text:
    text = text.replace(old_section, new_section, 1)
    changes.append('replaced pump section with V2 road fuel and EV section')

old_render = '''  function renderCommodities(oil){
    oil=oil||{};
    setText("brent-price", oil.brentUSDperBarrel==null?"—":"$"+fmt(oil.brentUSDperBarrel,2));
    setText("wti-price", oil.wtiUSDperBarrel==null?"—":"$"+fmt(oil.wtiUSDperBarrel,2));
    var pump=oil.ukPumpPrices||{};
    setText("petrol-price", pump.petrolPencePerLitre==null?"—":fmt(pump.petrolPencePerLitre,2)+"p");
    setText("diesel-price", pump.dieselPencePerLitre==null?"—":fmt(pump.dieselPencePerLitre,2)+"p");
  }'''
new_render = '''  function renderCommodities(oil,fuel){
    oil=oil||{}; fuel=fuel||{};
    setText("brent-price", oil.brentUSDperBarrel==null?"—":"$"+fmt(oil.brentUSDperBarrel,2));
    setText("wti-price", oil.wtiUSDperBarrel==null?"—":"$"+fmt(oil.wtiUSDperBarrel,2));
    var latest=fuel.latest||{};
    setText("petrol-price", latest.petrolPencePerLitre==null?"—":fmt(latest.petrolPencePerLitre,2)+"p");
    setText("diesel-price", latest.dieselPencePerLitre==null?"—":fmt(latest.dieselPencePerLitre,2)+"p");
    renderFuelBreakdown(oil, latest);
  }
  function renderFuelBreakdown(oil, latest){
    var el=document.getElementById("fuel-breakdown"); if(!el) return;
    var brent=oil&&oil.brentUSDperBarrel, petrol=latest&&latest.petrolPencePerLitre;
    if(brent==null || petrol==null){ el.textContent="Awaiting Brent crude and DESNZ fuel price feed."; return; }
    var gbpUsd=1.27, litresPerBarrel=158.987, duty=52.95, vatRate=0.20;
    var crudePpl=(Number(brent)/gbpUsd/litresPerBarrel)*100;
    var preVat=Number(petrol)/(1+vatRate);
    var vat=Number(petrol)-preVat;
    var spread=preVat-duty-crudePpl;
    el.innerHTML="Brent proxy: $"+fmt(brent,2)+"/bbl divided by FX "+gbpUsd+" and 159 litres equals about "+fmt(crudePpl,1)+"p/l crude input. Petrol pump: "+fmt(petrol,2)+"p/l. VAT at 20%: "+fmt(vat,1)+"p/l. Fuel duty assumption: "+fmt(duty,2)+"p/l. Implied refining, logistics, wholesale and retail spread: "+fmt(spread,1)+"p/l. Week: "+(latest.week||"not stated")+".";
  }'''
if old_render in text:
    text = text.replace(old_render, new_render, 1)
    changes.append('wired DESNZ fuel feed into V2 pump cards')

old_refresh = 'Promise.all([getJSON(ENERGY),getJSON(PRICE),getJSON(OIL),getJSON(OIL_HISTORY)]).then(function(res){\n      var e=res[0]||{}, p=res[1]||{}, oil=res[2]||{}, hist=res[3];\n      renderGauge("demand", e.demandGW); renderGauge("price", p.priceGBPperMWh); renderGauge("carbon", carbonValue(p));\n      if(e.mix) renderMix(e.mix); renderCommodities(oil); if(hist) drawOilTrend(hist);'
new_refresh = 'Promise.all([getJSON(ENERGY),getJSON(PRICE),getJSON(OIL),getJSON(OIL_HISTORY),getJSON(FUEL),getJSON(EV_PRICES)]).then(function(res){\n      var e=res[0]||{}, p=res[1]||{}, oil=res[2]||{}, hist=res[3], fuel=res[4]||{}, ev=res[5]||{};\n      renderGauge("demand", e.demandGW); renderGauge("price", p.priceGBPperMWh); renderGauge("carbon", carbonValue(p));\n      if(e.mix) renderMix(e.mi  … [line shortened here: 482 characters; full line on GitHub]
if old_refresh in text:
    text = text.replace(old_refresh, new_refresh, 1)
    changes.append('added V2 fuel and EV JSON to refresh loop')

insert_marker = '  function refresh(){'
insert_code = '''  function renderEvPrices(ev){
    var ops=(ev&&ev.operators)||[];
    var rapid=[], ultra=[];
    ops.forEach(function(o){ if(o.rapidPencePerKWh!=null) rapid.push(Number(o.rapidPencePerKWh)); if(o.ultraRapidPencePerKWh!=null) ultra.push(Number(o.ultraRapidPencePerKWh)); });
    if(rapid.length){ setText("ev-rapid-price", fmt(rapid.reduce(function(a,b){return a+b;},0)/rapid.length,1)+"p"); }
    if(ultra.length){ setText("ev-ultra-price", fmt(ultra.reduce(function(a,b){return a+b;},0)/ultra.length,1)+"p"); }
  }
'''
if 'function renderEvPrices' not in text and insert_marker in text:
    text = text.replace(insert_marker, insert_code + insert_marker, 1)
    changes.append('added V2 EV tariff renderer')

PAGE.write_text(text, encoding='utf-8')
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# UK energy tracking V2 transport patch\n\n' + '\n'.join('- ' + c for c in changes) + '\n', encoding='utf-8')
print('V2 transport patch complete')

GlobalGrid2050 Patch V3 Price Axis Table Fullscreen

A Python command-line tool in the scripts folder that patches page (`patch_page`) and CSS (`patch_css`) and patches diary (`patch_diary`), covering electricity price history and Elexon system prices half hourly.

energy-dataglobalgrid2050 / scripts/patch_v3_price_axis_table_fullscreen.py · lines 1–73 of 73 · Entry point · pattern patch_diary (shared by 6 files)

What it does
It draws electricity price history and Elexon system prices half hourly. Defines patch_page, patch_css, patch_diary, main. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file electricity_price_history.json; CSV file elexon_system_prices_half_hourly.csv. Out: canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch V3 Price Axis Table Fullscreen Workflow (globalgrid2050).
What it achieves
Defines `patch_page`, `patch_css` and `patch_diary`.
Why it matters
Run by GlobalGrid2050 Patch V3 Price Axis Table Fullscreen Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib
Used by
run by GlobalGrid2050 Patch V3 Price Axis Table Fullscreen Workflow (workflow run)
Produces
patch_page, patch_css, patch_diary, main
Defines here
patch_page, patch_css, patch_diary, 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/patch_v3_price_axis_table_fullscreen.py:1-73 · blob 72eeae3a0aed94e737061bd6e6b358cf2ffe990b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
from pathlib import Path

PAGE=Path('uk_energy_tracking_v3/index.md')
CSS=Path('uk_energy_tracking_v3/price-history-ui.css')
JS=Path('uk_energy_tracking_v3/price-history-ui.js')
FS=Path('uk_energy_tracking_v3/price-history-fullscreen.js')
DIARY=Path('uk_energy_tracking_v3/WORK_DIARY.md')

MAIN_JS=r'''(function(){
var JSON_URL='/uk_energy_tracking_v3/electricity_price_history.json',CSV_URL='/data/electricity/elexon_system_prices_half_hourly.csv';
var STATE={all:[],visible:[],meta:null};window.__v3PriceHistoryState=STATE;
function $(id){return document.getElementById(id)}
function fmt(n,d){return n==null||isNaN(n)?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
function dlab(t){return new Date(t).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'})}
function tlab(t){return new Date(t).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}
function set(id,v){var e=$(id);if(e)e.textContent=v}
function csvLine(l){var o=[],v='',q=false;for(var i=0;i<l.length;i++){var c=l[i];if(c==='"'){if(q&&l[i+1]==='"'){v+='"';i++}else q=!q}else if(c===','&&!q){o.push(v);v=''}else v+=c}o.push(v);return o}
function parseCsv(t){t=(t||'').trim();if(!t)return[];var lines=t.split(/\r?\n/),h=csvLine(lines[0]).map(x=>x.trim());return lines.slice(1).map(function(line){var c=csvLine(line),r={};h.forEach((x,i)=>r[x]=(c[i]||'').trim());var p=r.systemBuyPriceGBPperMWh||r.systemSellPriceGBPperMWh||r.priceGBPperMWh||'';return{source:r.source||'Elexon BMRS System Prices',priceTimeUTC:r.periodStartUTC||r.priceTime  … [line shortened here: 836 characters; full line on GitHub]
function loadJson(){return fetch(JSON_URL+'?t='+Date.now(),{cache:'no-store'}).then(r=>r.ok?r.json():{rows:[]}).then(d=>d.rows||[]).catch(()=>[])}
function loadCsv(){return fetch(CSV_URL+'?t='+Date.now(),{cache:'no-store'}).then(r=>r.ok?r.text():'').then(parseCsv).catch(()=>[])}
function norm(rows){var seen={};return(rows||[]).filter(r=>r.priceTimeUTC&&r.priceGBPperMWh!==''&&!isNaN(Number(r.priceGBPperMWh))).map(function(r){var o=Object.assign({},r);o.priceGBPperMWh=Number(o.priceGBPperMWh);return o}).sort((a,b)=>new Date(a.priceTimeUTC)-new Date(b.priceTimeUTC)).filter(function(r){var k=r.priceTimeUTC+'|'+r.priceGBPperMWh;if(seen[k])return false;seen[k]=1;return true})}
function merge(sys,cap){var m={};sys.forEach(r=>{m[r.priceTimeUTC]=Object.assign({},r,{source:'Elexon BMRS System Prices',priceHealth:r.priceHealth||'historical system price'})});cap.forEach(r=>{m[r.priceTimeUTC]=Object.assign({},r,{source:r.source||'V3 captured Elexon Market Index Price'})});return Object.keys(m).sort((a,b)=>new Date(a)-new Date(b)).map(k=>m[k])}
function customWindow(){var f=$('price-history-from'),t=$('price-history-to');if(!f||!t||!f.value||!t.value)return null;var a=new Date(f.value+'T00:00:00Z'),b=new Date(t.value+'T23:59:59Z');if(isNaN(a)||isNaN(b)||b<a)return null;var max=60*86400000;if(b-a>max)b=new Date(a.getTime()+max);return{start:a,end:b,label:f.value+' to '+b.toISOString().slice(0,10),custom:true}}
function rangeWindow(range,all){var cw=customWindow();if(cw)return cw;var now=new Date(),days={"24h":1,"7d":7,"30d":30,"3m":92,"6m":183,"12m":366,"10y":3650}[range];if(range==='all'||!days){var s=all.length?new Date(all[0].priceTimeUTC):now,e=all.length?new Date(all[all.length-1].priceTimeUTC):now;return{start:s,end:e,label:'all available data',custom:false}}return{start:new Date(now.getTime()-day  … [line shortened here: 446 characters; full line on GitHub]
function health(r){if(r.priceHealth&&r.priceHealth!=='ok')return 'price: '+r.priceHealth;if(r.carbonHealth&&r.carbonHealth!=='ok')return 'carbon: '+r.carbonHealth;if(r.carbonGperKWh!==''&&r.carbonGperKWh!=null)return r.carbonGperKWh+' g/kWh';if(r.carbonIndex)return String(r.carbonIndex);return '—'}
function minMax(v){var lo=v[0],hi=v[0];v.forEach(x=>{if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=(hi-lo)*.1;return{lo:lo-m,hi:hi+m}}
function draw(rows,meta){var c=$('price-history-canvas');if(!c)return;var q=devicePixelRatio||1,r=c.getBoundingClientRect();if(r.width){c.width=Math.max(320,Math.floor(r.width*q));c.height=Math.max(190,Math.floor((r.height||240)*q))}var g=c.getContext('2d'),w=c.width,h=c.height,p=62*q,rp=22*q;g.clearRect(0,0,w,h);g.fillStyle='#05070c';g.fillRect(0,0,w,h);g.font=12*q+'px Courier New';var t0=meta?me  … [line shortened here: 1,558 characters; full line on GitHub]
function table(rows,meta){var b=$('price-history-table-body');if(!b)return;if(!rows.length){b.innerHTML='<tr><td colspan="5">No records available for selected range: '+meta.label+'. Check data source or run Elexon backfill.</td></tr>';return}b.innerHTML=rows.slice().reverse().map(r=>'<tr class="'+((r.priceHealth&&r.priceHealth!=='ok')?'price-warning':'')+'"><td>'+dlab(r.priceTimeUTC)+' '+tlab(r.pr  … [line shortened here: 600 characters; full line on GitHub]
function status(meta,all,rows){var s=$('price-history-range-status');if(!s)return;var av=all.length?dlab(all[0].priceTimeUTC)+' to '+dlab(all[all.length-1].priceTimeUTC):'no source data';s.textContent='Selected range: '+dlab(meta.start)+' to '+dlab(meta.end)+' | Available source data: '+av+' | Visible records: '+rows.length}
function load(){var rangeEl=$('price-history-range'),range=rangeEl?rangeEl.value:'7d';Promise.all([loadJson(),loadCsv()]).then(function(p){var all=merge(norm(p[1]),norm(p[0])),meta=rangeWindow(range,all);var rows=all.filter(r=>{var t=new Date(r.priceTimeUTC);return t>=meta.start&&t<=meta.end});STATE.all=all;STATE.visible=rows;STATE.meta=meta;var latest=all.length?all[all.length-1]:null;set('ph-lat  … [line shortened here: 868 characters; full line on GitHub]
document.addEventListener('DOMContentLoaded',function(){var r=$('price-history-range'),f=$('price-history-from'),t=$('price-history-to'),cl=$('price-history-clear-dates');if(r)r.addEventListener('change',load);if(f)f.addEventListener('change',load);if(t)t.addEventListener('change',load);if(cl)cl.addEventListener('click',function(){if(f)f.value='';if(t)t.value='';load()});load();setInterval(load,5*  … [line shortened here: 502 characters; full line on GitHub]
})();'''

FULLSCREEN_JS=r'''(function(){
var S={rows:[],meta:null};function $(id){return document.getElementById(id)}function dlab(t){return new Date(t).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'})}function fmt(n,d){return Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
function mm(v){var lo=v[0],hi=v[0];v.forEach(x=>{if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=(hi-lo)*.1;return{lo:lo-m,hi:hi+m}}
function draw(){var c=$('price-history-fullscreen-canvas');if(!c)return;var q=devicePixelRatio||1,r=c.getBoundingClientRect();c.width=Math.max(400,Math.floor(r.width*q));c.height=Math.max(260,Math.floor(r.height*q));var g=c.getContext('2d'),w=c.width,h=c.height,p=74*q,rp=28*q;g.fillStyle='#05070c';g.fillRect(0,0,w,h);g.font=12*q+'px Courier New';var rows=S.rows,meta=S.meta;if(!meta){meta={start:ne  … [line shortened here: 1,513 characters; full line on GitHub]
function open(){var o=$('price-history-fullscreen-overlay'),st=window.__v3PriceHistoryState;if(!o)return;o.classList.add('open');S.rows=(st&&st.visible)||[];S.meta=(st&&st.meta)||null;var m=$('price-history-fullscreen-meta');if(m&&S.meta)m.textContent='Selected range: '+dlab(S.meta.start)+' to '+dlab(S.meta.end)+' | visible records: '+S.rows.length+' of '+((st&&st.all&&st.all.length)||S.rows.lengt  … [line shortened here: 428 characters; full line on GitHub]
function close(){var o=$('price-history-fullscreen-overlay');if(o)o.classList.remove('open')}
document.addEventListener('DOMContentLoaded',function(){var b=$('price-history-fullscreen-btn'),c=$('price-history-fullscreen-close'),r=$('price-history-zoom-reset');if(b)b.onclick=open;if(c)c.onclick=close;if(r)r.onclick=draw;document.addEventListener('keydown',e=>{if(e.key==='Escape')close()});window.addEventListener('resize',draw)});
})();'''

CSS_ADD='''
#electricity-price-history-panel .price-history-range-status{width:100%;color:#9aa3b6;font-size:11px;line-height:1.45;border:1px solid #252b36;border-radius:4px;padding:7px 9px;background:#070a10;}
#electricity-price-history-panel table.price-history-table tr.price-warning td{background:#20160b!important;color:#ffd28a!important}
#electricity-price-history-panel table.price-history-table tr.price-warning td:nth-child(2){color:#ffcc66!important}
'''

def patch_page():
    t=PAGE.read_text(encoding='utf-8')
    t=t.replace('<button type="button" id="price-history-zoom-out">Zoom out</button>\n        <button type="button" id="price-history-zoom-in">Zoom in</button>\n        <button type="button" id="price-history-zoom-reset">Reset</button>\n        <button type="button" id="price-history-fullscreen-close">Close</button>','<button type="button" id="price-history-zoom-reset">Redraw</button>\n        <bu  … [line shortened here: 471 characters; full line on GitHub]
    t=t.replace('<div class="price-history-fullscreen-note">Wheel to zoom. Drag to pan. Esc closes the chart.</div>','<div class="price-history-fullscreen-note">Full screen uses the selected inline date range. Esc closes the chart.</div>')
    if 'price-history-range-status' not in t:
        t=t.replace('</div>\n      <div class="unit-panel"><strong>Unit:</strong>', '</div>\n      <div id="price-history-range-status" class="price-history-range-status">Selected range will appear here.</div>\n      <div class="unit-panel"><strong>Unit:</strong>',1)
    t=t.replace("<script src='/uk_energy_tracking_v3/price-history-ui.js'></script>","<script src='/uk_energy_tracking_v3/price-history-ui.js?v=20260526d'></script>")
    t=t.replace("<script src='/uk_energy_tracking_v3/price-history-fullscreen.js'></script>","<script src='/uk_energy_tracking_v3/price-history-fullscreen.js?v=20260526d'></script>")
    PAGE.write_text(t,encoding='utf-8')

def patch_css():
    t=CSS.read_text(encoding='utf-8')
    if 'price-history-range-status' not in t:t=t.rstrip()+"\n"+CSS_ADD
    CSS.write_text(t,encoding='utf-8')

def patch_diary():
    t=DIARY.read_text(encoding='utf-8')
    marker='## Diary entry: 2026-05-26 V3 selected range axis and fullscreen simplification patch'
    if marker not in t:
        t+='\n\n'+marker+'\n\nThis patch makes the selected date window govern the x axis rather than allowing the chart to collapse to only the earliest and latest available rows. It adds a visible selected range and available source data status line, makes the table use the same selected range, removes broken zoom in and zoom out controls from full screen mode and makes full screen reuse the alr  … [line shortened here: 588 characters; full line on GitHub]
    DIARY.write_text(t,encoding='utf-8')

def main():
    patch_page();patch_css();JS.write_text(MAIN_JS,encoding='utf-8');FS.write_text(FULLSCREEN_JS,encoding='utf-8');patch_diary();print('patched V3 selected range axis, table status and fullscreen simplification')
if __name__=='__main__':main()