GLOBALGRID2050 / EXPLORE CODE

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

Make Decade Summary and 17 more files

A Python command-line tool in the derived folder of GlobalGrid2050 covering electricity price history daily decade and pvlive solar daily browser.

698 lines of JavaScript and Python from globalgrid2050, in 18 files. Topic: Electricity markets and data pipelines. Section 918 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. Make Decade Summary ingest · globalgrid2050 / uk_energy_tracking_v6/derived/make_decade_summary.py lines 1–181
  2. Frequency History UI render · globalgrid2050 / uk_energy_tracking_v6/frequency_history/frequency-history-ui.js lines 1–143
  3. Control Generation History energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/control_generation_history.js lines 1–19
  4. Control Generation MWh Aggregates energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/control_generation_mwh_aggregates.js lines 1–11
  5. Live Config render · globalgrid2050 / uk_energy_tracking_v6/generation_history/live-config.js lines 1–12
  6. Load Generation History Data energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/load_generation_history_data.js lines 1–30
  7. Load Generation MWh Aggregates energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/load_generation_mwh_aggregates.js lines 1–16
  8. Render Generation History Chart energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/render_generation_history_chart.js lines 1–22
  9. Render Generation MWh Aggregates energy-data · globalgrid2050 / uk_energy_tracking_v6/generation_history/render_generation_mwh_aggregates.js lines 1–34
  10. Live Config render · globalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/live-config.js lines 1–14
  11. Load JSON render · globalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/load_json/load_json.js lines 1–4
  12. Render Generation Mix energy-data · globalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/render_generation_mix/render_generation_mix.js lines 1–20
  13. Render Live Snapshot render · globalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/render_live_snapshot/render_live_snapshot.js lines 1–29
  14. Control Price History energy-data · globalgrid2050 / uk_energy_tracking_v6/price_history_chart/control_price_history/control_price_history.js lines 1–33
  15. Fullscreen Period Menu render · globalgrid2050 / uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js lines 1–45
  16. Load Price History Data energy-data · globalgrid2050 / uk_energy_tracking_v6/price_history_chart/load_price_history_data/load_price_history_data.js lines 1–29
  17. Render Price Chart Box Overlay energy-data · globalgrid2050 / uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_box_overlay.js lines 1–25
  18. Render Price Chart V6 Clean Boxes energy-data · globalgrid2050 / uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_v6_clean_boxes.js lines 1–31

Make Decade Summary

A Python command-line tool in the derived folder of GlobalGrid2050 covering electricity price history daily decade and pvlive solar daily browser.

ingestglobalgrid2050 / uk_energy_tracking_v6/derived/make_decade_summary.py · lines 1–181 of 181 · Entry point

What it does
Defines read, mean, main. Uses libraries io, json, os, collections.
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 electricity_price_history_daily_decade.json; JSON file pvlive_solar_daily_browser.json; JSON file decade-summary.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the read step (`read`) and the mean step (`mean`). Derive a compact decade summary from the tracker's own official series.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · uk_energy_tracking_v6/derived · Python CLI
Uses
io, json, os, collections
Used by
none found
Produces
read, mean, main
Defines here
read, mean, 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 uk_energy_tracking_v6/derived/make_decade_summary.py:1-181 · blob 1debf36fdb012ed07b4e0b8663aa60ce13e6d2b9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Derive a compact decade summary from the tracker's own official series.

WHY THIS EXISTS
---------------
The tracker holds a decade of GB daily system prices from Elexon and a decade
of daily solar from Sheffield Solar PVLive. Together they are about 1.9 MB.
That is the right size for a dashboard someone has chosen to open on a desktop
and the wrong size for a panel inside a map on a phone, which is where most
readers arrive from a shared link.

So this reduces them, once, to yearly aggregates: roughly five kilobytes that
answer the questions a map of generation projects actually raises. What has a
megawatt hour been worth. How often was it worth less than nothing. What does
GB solar do across a year.

WHAT IT DOES NOT DO
-------------------
It does not resample, smooth, model or forecast. Every figure is an arithmetic
aggregate of days that are already in the published series, and the count of
days behind each one is carried with it, so a partial year is visible as a
partial year rather than quietly averaged in with the rest.

The daily series remain the source of truth and the tracker remains the place
the analysis lives. This is an index card, not a replacement.

    python make_decade_summary.py
"""

import io
import json
import os
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.dirname(HERE)

PRICE = os.path.join(APP, "electricity_price_history_daily_decade.json")
SOLAR = os.path.join(APP, "generation_history", "pvlive_solar_daily_browser.json")


def read(path):
    return json.loads(io.open(path, encoding="utf-8").read())


def mean(values):
    return sum(values) / len(values) if values else None


def main():
    price = read(PRICE)
    solar = read(SOLAR)

    # ---- price, by calendar year ----------------------------------------
    by_year = defaultdict(list)
    negative_days = defaultdict(int)
    lowest = None
    highest = None
    for row in price.get("rows", []):
        date = row.get("date") or ""
        avg = row.get("average")
        if len(date) < 4 or not isinstance(avg, (int, float)):
            continue
        year = date[:4]
        by_year[year].append(float(avg))
        # A day whose LOW went below zero is a day the system paid to be
        # relieved of energy. For a solar developer that is the export
        # limitation and curtailment question, so it is counted separately
        # from the daily average, which can hide it entirely.
        low = row.get("low")
        if isinstance(low, (int, float)) and float(low) < 0:
            negative_days[year] += 1
        if lowest is None or (isinstance(low, (int, float)) and float(low) < lowest["value"]):
            if isinstance(low, (int, float)):
                lowest = {"value": float(low), "date": date, "at": row.get("lowAt")}
        high = row.get("high")
        if isinstance(high, (int, float)) and (highest is None or float(high) > highest["value"]):
            highest = {"value": float(high), "date": date, "at": row.get("highAt")}

    price_years = []
    for year in sorted(by_year):
        values = by_year[year]
        price_years.append({
            "year": year,
            "days": len(values),
            "mean_gbp_per_mwh": round(mean(values), 2),
            "min_daily_mean": round(min(values), 2),
            "max_daily_mean": round(max(values), 2),
            "days_with_a_negative_half_hour": negative_days.get(year, 0),
        })

    # ---- solar, by calendar year and by month ---------------------------
    solar_year = defaultdict(list)
    solar_month = defaultdict(list)
    for row in solar.get("rows", []):
        date = row.get("date") or ""
        avg = row.get("averageMW")
        if len(date) < 7 or not isinstance(avg, (int, float)):
            continue
        solar_year[date[:4]].append(float(avg))
        solar_month[date[5:7]].append(float(avg))

    solar_years = [{
        "year": year,
        "days": len(values),
        "mean_mw": round(mean(values), 1),
        "max_daily_mean_mw": round(max(values), 1),
    } for year, values in sorted(solar_year.items())]

    # The seasonal shape is the single most useful thing a solar developer can
    # read off a decade: it is why a nameplate figure and a yield are different
    # conversations.
    solar_months = [{
        "month": month,
        "days": len(values),
        "mean_mw": round(mean(values), 1),
    } for month, values in sorted(solar_month.items())]

    all_price = [v for values in by_year.values() for v in values]
    all_solar = [v for values in solar_year.values() for v in values]

    summary = {
        "schema": "globalgrid2050.decade-summary.v1",
        "what_this_is": (
            "Yearly aggregates derived from the tracker's own daily series, so "
            "that a map can carry the decade without carrying 1.9 MB. No "
            "resampling, smoothing, modelling or forecasting: every figure is "
            "an arithmetic aggregate of published days, and the day count "
            "behind each one is stated so a partial year reads as one."),
        "not_a_forecast": (
            "Historic system conditions. Nothing here is a projection, a price "
            "expectation, or a statement about the economics of any project."),
        "derived_from": {
            "price": {
                "file": "electricity_price_history_daily_decade.json",
                "source": price.get("source"),
                "generated_utc": price.get("generated_utc"),
                "schema": price.get("schema"),
                "days": len(all_price),
            },
            "solar": {
                "file": "generation_history/pvlive_solar_daily_browser.json",
                "source": solar.get("source"),
                "attribution": solar.get("sourceAttribution"),
                "note": solar.get("sourceNote"),
                "generated_utc": solar.get("generatedUTC"),
                "days": len(all_solar),
            },
        },
        "price": {
            "unit": "GBP per MWh, GB system price, daily mean of half hours",
            "span": [price_years[0]["year"], price_years[-1]["year"]] if price_years else None,
            "decade_mean": round(mean(all_price), 2) if all_price else None,
            "lowest_half_hour": lowest,
            "highest_half_hour": highest,
            "by_year": price_years,
        },
        "solar": {
            "unit": "MW, GB solar generation estimated by Sheffield Solar PVLive",
            "estimated_not_metered": True,
            "decade_mean_mw": round(mean(all_solar), 1) if all_solar else None,
            "by_year": solar_years,
            "by_month": solar_months,
        },
    }

    out = os.path.join(HERE, "decade-summary.json")
    io.open(out, "w", encoding="utf-8", newline="\n").write(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
    size = os.path.getsize(out)
    print("wrote %s (%.1f kB)" % (os.path.relpath(out, APP), size / 1024.0))
    print("  price  %s-%s, %d days, decade mean %.2f GBP/MWh"
          % (price_years[0]["year"], price_years[-1]["year"], len(all_price),
             mean(all_price)))
    print("  solar  %d days, decade mean %.1f MW" % (len(all_solar), mean(all_solar)))
    neg = sum(y["days_with_a_negative_half_hour"] for y in price_years)
    print("  %d days had at least one half hour below zero" % neg)
    return 0


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

Frequency History UI

A JavaScript file in GlobalGrid2050 that draws grid frequency history and live grid frequency weekly health. It parses CSV (`parseCsv`), gets text (`getText`) and gets JSON (`getJson`).

renderglobalgrid2050 / uk_energy_tracking_v6/frequency_history/frequency-history-ui.js · lines 1–143 of 143 · Not reached from any entry point (candidate for review) · pattern canvasSetup (shared by 2 files)

What it does
It draws grid frequency history and live grid frequency weekly health. Defines 13 functions or classes, including $, txt, css, install, parseCsv. Side effects: changes the web page (DOM); 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: CSV file grid_frequency_history.csv; JSON file live_grid_frequency.json; JSON file live_grid_frequency_weekly_health.json; CSV file grid_frequency_weekly_health.csv. Out: canvas drawing.
What it achieves
GlobalGrid2050 V6 frequency chart. Inserts itself below the Elexon price chart. Its code works with 50 Hz. It responds to resize events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/frequency_history · script
Uses
none found
Used by
none found
Produces
$, txt, css, install, parseCsv, timeLabel, weekLabel, getText, getJson, canvasSetup, draw, drawWeekly
Defines here
$, txt, css, install, parseCsv, timeLabel, weekLabel, getText, getJson, canvasSetup, draw, drawWeekly, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/frequency_history/frequency-history-ui.js:1-143 · blob e975257b2fafa060315396655fb9597b9ccfadbf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// GlobalGrid2050 V6 frequency chart. Inserts itself below the Elexon price chart.
(function(){
  var CSV_URL = "/uk_energy_tracking_v6/grid_frequency_history.csv";
  var LIVE_URL = "/uk_energy_tracking_v6/live_grid_frequency.json";
  var WEEKLY_URL = "/uk_energy_tracking_v6/live_grid_frequency_weekly_health.json";
  var REFRESH_MS = 120000;
  var installed = false;

  function $(id){ return document.getElementById(id); }
  function txt(id, value){ var el=$(id); if(el) el.textContent=value; }
  function css(){
    if($("gg-frequency-style")) return;
    var s=document.createElement("style");
    s.id="gg-frequency-style";
    s.textContent="\n#grid-frequency-panel .frequency-shell{background:var(--gg-panel,#0b0f17);border:1px solid var(--gg-line,#252b36);border-radius:6px;padding:14px;margin-top:18px}\n#grid-frequency-panel .frequency-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:10px}\n#grid-frequency-panel .frequency-actions strong{color:var(--gg-cyan,#00ffff);letter-spacing:.12em;  … [line shortened here: 1,891 characters; full line on GitHub]
    document.head.appendChild(s);
  }
  function install(){
    if(installed || $("grid-frequency-panel")) return true;
    var price=$("electricity-price-history-panel");
    if(!price || !price.parentNode) return false;
    css();
    var section=document.createElement("section");
    section.id="grid-frequency-panel";
    section.innerHTML="<h2 class='section-title'>Grid Frequency 24 Hour Trace</h2>"+
      "<div class='frequency-shell'>"+
      "<div class='frequency-actions'><strong>UK grid frequency from Elexon</strong><a href='/uk_energy_tracking_v6/grid_frequency_history.csv' download>Download frequency CSV</a><a href='/uk_energy_tracking_v6/grid_frequency_weekly_health.csv' download>Download weekly health CSV</a></div>"+
      "<div class='frequency-note'><b>Grid stability signal:</b> frequency shows the live balance between generation and demand. The 50 Hz reference line exposes stress, recovery and control behaviour over the last rolling 24 hours.</div>"+
      "<canvas id='frequency-history-canvas' width='900' height='340'></canvas>"+
      "<div class='frequency-mini-grid'>"+
      "<div class='frequency-mini'><span>Latest</span><strong><b id='frequency-latest'>—</b> Hz</strong></div>"+
      "<div class='frequency-mini'><span>Records</span><strong id='frequency-records'>—</strong></div>"+
      "<div class='frequency-mini'><span>Window</span><strong id='frequency-window'>24 hours</strong></div>"+
      "<div class='frequency-mini'><span>Min to max</span><strong id='frequency-minmax'>—</strong></div>"+
      "</div><div class='scada-credit' id='frequency-updated' style='margin-top:10px;'>Awaiting frequency update.</div>"+
      "<div class='frequency-subtitle'>Weekly grid health trend</div>"+
      "<div class='frequency-note'><b>Health proxy:</b> weekly average frequency and largest deviation from 50 Hz. Historic depth depends on what the public Elexon frequency endpoint returns during backfill.</div>"+
      "<canvas id='frequency-weekly-canvas' width='900' height='300'></canvas>"+
      "<div class='frequency-mini-grid'>"+
      "<div class='frequency-mini'><span>Weeks</span><strong id='frequency-weekly-count'>—</strong></div>"+
      "<div class='frequency-mini'><span>Latest avg</span><strong id='frequency-weekly-avg'>—</strong></div>"+
      "<div class='frequency-mini'><span>Largest dev</span><strong id='frequency-weekly-dev'>—</strong></div>"+
      "<div class='frequency-mini'><span>Weekly health</span><strong id='frequency-weekly-health'>—</strong></div>"+
      "</div></div>";
    price.parentNode.insertBefore(section, price.nextSibling);
    installed=true;
    return true;
  }
  function parseCsv(text){
    text=(text||"").trim();
    if(!text) return [];
    return text.split(/\r?\n/).slice(1).map(function(line){
      var p=line.split(",");
      if(p.length<2) return null;
      var hz=parseFloat(p[1]);
      if(!isFinite(hz)) return null;
      return {t:p[0], hz:hz};
    }).filter(Boolean);
  }
  function timeLabel(iso){
    if(!iso) return "—";
    var d=new Date(iso);
    if(isNaN(d.getTime())) return iso;
    return d.toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit",second:"2-digit"});
  }
  function weekLabel(iso){
    if(!iso) return "—";
    var d=new Date(iso);
    if(isNaN(d.getTime())) return iso;
    return d.toLocaleDateString("en-GB",{day:"2-digit",month:"short"});
  }
  function getText(url){return fetch(url+"?t="+Date.now(),{cache:"no-store"}).then(function(r){if(!r.ok) throw new Error(String(r.status)); return r.text();});}
  function getJson(url){return fetch(url+"?t="+Date.now(),{cache:"no-store"}).then(function(r){if(!r.ok) throw new Error(String(r.status)); return r.json();});}
  function canvasSetup(id, minH){
    var c=$(id); if(!c) return null;
    var ctx=c.getContext("2d"), rect=c.getBoundingClientRect(), dpr=window.devicePixelRatio||1;
    var w=Math.max(340,Math.floor(rect.width*dpr)), h=Math.max(minH||260,Math.floor(rect.height*dpr));
    c.width=w; c.height=h; ctx.fillStyle="#070a10"; ctx.fillRect(0,0,w,h);
    return {c:c,ctx:ctx,dpr:dpr,w:w,h:h,L:58*dpr,R:18*dpr,T:24*dpr,B:44*dpr};
  }
  function draw(rows){
    var g=canvasSetup("frequency-history-canvas",260); if(!g) return;
    var ctx=g.ctx,dpr=g.dpr,L=g.L,R=g.R,T=g.T,B=g.B,w=g.w,h=g.h,pw=w-L-R,ph=h-T-B;
    ctx.strokeStyle="rgba(255,255,255,.12)"; ctx.lineWidth=1*dpr; ctx.strokeRect(L,T,pw,ph);
    [49.8,49.9,50.0,50.1,50.2].forEach(function(v){
      var y=T+(50.2-v)/0.4*ph;
      ctx.beginPath(); ctx.moveTo(L,y); ctx.lineTo(L+pw,y); ctx.stroke();
      ctx.fillStyle=v===50?"#00ffff":"#9aa3b6"; ctx.font=(11*dpr)+"px Courier New"; ctx.fillText(v.toFixed(1),8*dpr,y+4*dpr);
    });
    if(!rows.length){ctx.fillStyle="#9aa3b6"; ctx.font=(14*dpr)+"px Courier New"; ctx.fillText("Awaiting frequency records",L+18*dpr,T+42*dpr); return;}
    var vals=rows.map(function(r){return r.hz;});
    var min=Math.min.apply(null,vals.concat([49.8])), max=Math.max.apply(null,vals.concat([50.2]));
    var span=Math.max(0.2,max-min); min-=span*0.08; max+=span*0.08;
    var y50=T+(max-50)/(max-min)*ph;
    ctx.strokeStyle="rgba(0,255,255,.60)"; ctx.setLineDash([6*dpr,6*dpr]); ctx.beginPath(); ctx.moveTo(L,y50); ctx.lineTo(L+pw,y50); ctx.stroke(); ctx.setLineDash([]);
    ctx.shadowColor="rgba(0,255,136,.45)"; ctx.shadowBlur=12*dpr; ctx.strokeStyle="#00ff88"; ctx.lineWidth=2*dpr; ctx.beginPath();
    rows.forEach(function(r,i){var x=L+(rows.length===1?0.5:i/(rows.length-1))*pw; var y=T+(max-r.hz)/(max-min)*ph; if(i===0)ctx.moveTo(x,y); else ctx.lineTo(x,y);});
    ctx.stroke(); ctx.shadowBlur=0;
    ctx.fillStyle="#9aa3b6"; ctx.font=(11*dpr)+"px Courier New";
    ctx.fillText(timeLabel(rows[0].t),L,T+ph+26*dpr);
    ctx.fillText(timeLabel(rows[rows.length-1].t),Math.max(L,L+pw-150*dpr),T+ph+26*dpr);
  }
  function drawWeekly(rows){
    var g=canvasSetup("frequency-weekly-canvas",240); if(!g) return;
    var ctx=g.ctx,dpr=g.dpr,L=g.L,R=g.R,T=g.T,B=g.B,w=g.w,h=g.h,pw=w-L-R,ph=h-T-B;
    ctx.strokeStyle="rgba(255,255,255,.12)"; ctx.lineWidth=1*dpr; ctx.strokeRect(L,T,pw,ph);
    [49.95,50.0,50.05].forEach(function(v){
      var y=T+(50.05-v)/0.10*ph;
      ctx.beginPath(); ctx.moveTo(L,y); ctx.lineTo(L+pw,y); ctx.stroke();
      ctx.fillStyle=v===50?"#00ffff":"#9aa3b6"; ctx.font=(11*dpr)+"px Courier New"; ctx.fillText(v.toFixed(2),6*dpr,y+4*dpr);
    });
    if(!rows.length){ctx.fillStyle="#9aa3b6"; ctx.font=(14*dpr)+"px Courier New"; ctx.fillText("Awaiting weekly health rows",L+18*dpr,T+42*dpr); return;}
    var vals=rows.map(function(r){return Number(r.avg_hz);}).filter(function(v){return isFinite(v);});
    var min=Math.min.apply(null,vals.concat([49.95])), max=Math.max.apply(null,vals.concat([50.05]));
    var span=Math.max(0.05,max-min); min-=span*0.1; max+=span*0.1;
    var y50=T+(max-50)/(max-min)*ph;
    ctx.strokeStyle="rgba(0,255,255,.60)"; ctx.setLineDash([6*dpr,6*dpr]); ctx.beginPath(); ctx.moveTo(L,y50); ctx.lineTo(L+pw,y50); ctx.stroke(); ctx.setLineDash([]);
    ctx.shadowColor="rgba(255,204,0,.35)"; ctx.shadowBlur=10*dpr; ctx.strokeStyle="#ffcc00"; ctx.lineWidth=2*dpr; ctx.beginPath();
    rows.forEach(function(r,i){var x=L+(rows.length===1?0.5:i/(rows.length-1))*pw; var y=T+(max-Number(r.avg_hz))/(max-min)*ph; if(i===0)ctx.moveTo(x,y); else ctx.lineTo(x,y);});
    ctx.stroke(); ctx.shadowBlur=0;
    ctx.fillStyle="#9aa3b6"; ctx.font=(11*dpr)+"px Courier New";
    ctx.fillText(weekLabel(rows[0].week_start_utc),L,T+ph+26*dpr);
    ctx.fillText(weekLabel(rows[rows.length-1].week_start_utc),Math.max(L,L+pw-90*dpr),T+ph+26*dpr);
  }
  function refresh(){
    if(!install()) return;
    Promise.all([getText(CSV_URL).catch(function(){return "";}),getJson(LIVE_URL).catch(function(){return null;}),getJson(WEEKLY_URL).catch(function(){return null;})]).then(function(res){
      var rows=parseCsv(res[0]), live=res[1]||{}, weekly=res[2]||{}, latest=live.latest||{}, weeklyRows=weekly.rows||[], latestWeek=weekly.latest_week||weeklyRows[weeklyRows.length-1]||{};
      draw(rows); drawWeekly(weeklyRows);
      txt("frequency-latest", latest.frequency_hz!=null?Number(latest.frequency_hz).toFixed(3):rows.length?Number(rows[rows.length-1].hz).toFixed(3):"—");
      txt("frequency-records", String(live.record_count||rows.length||0));
      txt("frequency-window", (live.window_hours||24)+" hours");
      txt("frequency-minmax", live.min_hz!=null&&live.max_hz!=null?Number(live.min_hz).toFixed(3)+" to "+Number(live.max_hz).toFixed(3)+" Hz":"—");
      txt("frequency-updated", live.updated_utc?"Updated: "+timeLabel(live.updated_utc):"Awaiting frequency update.");
      txt("frequency-weekly-count", String(weekly.record_count||weeklyRows.length||0));
      txt("frequency-weekly-avg", latestWeek.avg_hz!=null?Number(latestWeek.avg_hz).toFixed(4)+" Hz":"—");
      txt("frequency-weekly-dev", latestWeek.largest_deviation_hz!=null?Number(latestWeek.largest_deviation_hz).toFixed(4)+" Hz":"—");
      txt("frequency-weekly-health", latestWeek.data_health||weekly.health||"—");
    });
  }
  window.addEventListener("resize", refresh);
  refresh(); setInterval(refresh, REFRESH_MS);
})();

Control Generation History

A JavaScript file in GlobalGrid2050 that sets start period (`setStartForPeriod`) and start year (`setStartForYear`) and sets status (`setStatus`), covering wind.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/control_generation_history.js · lines 1–19 of 19 · Not reached from any entry point (candidate for review) · pattern fillTech (shared by 2 files)

What it does
It draws wind. Defines 11 functions or classes, including byId, ymd, daysForPeriod, isRecentPeriod, fillYears. Side effects: changes the web page (DOM).
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: wind.
What it achieves
It sets start period (`setStartForPeriod`), sets start year (`setStartForYear`) and sets status (`setStatus`). Defines `byId`, `ymd`, `daysForPeriod` and 8 more. It responds to change, resize and DOMContentLoaded events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
byId, ymd, daysForPeriod, isRecentPeriod, fillYears, fillTech, setStartForPeriod, setStartForYear, state, setStatus, drawCached
Defines here
byId, ymd, daysForPeriod, isRecentPeriod, fillYears, fillTech, setStartForPeriod, setStartForYear, state, setStatus, drawCached
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/control_generation_history.js:1-19 · blob 6871c39a98a4ec31fc9d923b7152e2c0d9528256 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6ControlGenerationHistory=(function(){
  var lastResult=null;
  function byId(id){return document.getElementById(id)}
  function ymd(d){return d.toISOString().slice(0,10)}
  function daysForPeriod(p){return {'12hday':1,'12hnight':1,'24h':1,'48h':2,'7d':7,'30d':30,'3m':92,'6m':183,'12m':366,'5y':1827,'10y':3653}[p]||7}
  function isRecentPeriod(p){return ['12hday','12hnight','24h','48h','7d','30d'].indexOf(p)>=0}
  function fillYears(){var sel=byId('generation-history-year');if(!sel)return;var now=new Date().getUTCFullYear(),first=(window.V6GenerationHistoryConfig.firstYear||2016);sel.innerHTML='';for(var y=now;y>=first;y--){var o=document.createElement('option');o.value=String(y);o.textContent=String(y);sel.appendChild(o)}}
  function fillTech(){var sel=byId('generation-history-technology');if(!sel)return;sel.innerHTML='';(window.V6GenerationHistoryConfig.technologies||['Wind']).forEach(function(t){var o=document.createElement('option');o.value=t;o.textContent=t;sel.appendChild(o)});sel.value=(window.V6GenerationHistoryConfig.defaultTechnology||'Wind')}
  function setStartForPeriod(){var start=byId('generation-history-start'),period=byId('generation-history-period');if(!start||!period)return;var p=period.value,d=new Date();d.setUTCDate(d.getUTCDate()-daysForPeriod(p)+1);start.value=ymd(d)}
  function setStartForYear(){var year=byId('generation-history-year'),start=byId('generation-history-start');if(year&&start)start.value=String(year.value)+'-01-01'}
  function state(){var year=byId('generation-history-year'),start=byId('generation-history-start'),period=byId('generation-history-period'),tech=byId('generation-history-technology');return{year:year?year.value:String(new Date().getUTCFullYear()),start:start?start.value:'',period:period?period.value:'12m',technology:tech?tech.value:(window.V6GenerationHistoryConfig.defaultTechnology||'Wind')}}
  function setStatus(text){var e=byId('generation-history-range-status');if(e)e.textContent=text}
  function drawCached(){var canvas=byId('generation-history-canvas');if(canvas&&lastResult)window.V6RenderGenerationHistoryChart.render(canvas,lastResult)}
  function refresh(){var s=state(),start=s.start?new Date(s.start+'T00:00:00Z'):new Date(Date.UTC(Number(s.year),0,1));setStatus('Loading '+s.technology+' generation data...');window.V6LoadGenerationHistoryData.loadWindow(start,s.period,s.technology,'all').then(function(result){lastResult=result;drawCached();setStatus(window.V6LoadGenerationHistoryData.periodLabel(s.period)+' · '+s.technology+' ·   … [line shortened here: 626 characters; full line on GitHub]
  function init(){fillYears();fillTech();var period=byId('generation-history-period');if(period)period.value='12m';setStartForPeriod();var year=byId('generation-history-year');if(year)year.addEventListener('change',function(){setStartForYear();refresh()});if(period)period.addEventListener('change',function(){setStartForPeriod();refresh()});['generation-history-start','generation-history-technology  … [line shortened here: 622 characters; full line on GitHub]
  return{init:init,refresh:refresh};
})();

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

Control Generation MWh Aggregates

A JavaScript file in the generation history folder of GlobalGrid2050 that sets status (`setStatus`) (units: MWh), covering solar.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/control_generation_mwh_aggregates.js · lines 1–11 of 11 · Not reached from any entry point (candidate for review) · pattern setStatus (shared by 4 files)

What it does
It draws solar. Defines byId, tech, setStatus, init. Side effects: changes the web page (DOM).
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.
What it achieves
It sets status (`setStatus`) and is built from the by id helper (`byId`) and the init step (`init`). Defines `byId`, `tech`, `setStatus` and 1 more. It responds to change and DOMContentLoaded events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
byId, tech, setStatus, init
Defines here
byId, tech, setStatus, init
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/control_generation_mwh_aggregates.js:1-11 · blob bb7f1396a9da29d43426221d782081e60b00fa0d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6ControlGenerationMwhAggregates=(function(){
  var hide={'Imports & Exports':1};
  function byId(id){return document.getElementById(id)}
  function tech(){var e=byId('generation-mwh-technology');return e?e.value:'Solar'}
  function fillTech(){var e=byId('generation-mwh-technology');if(!e)return;var opts=((window.V6GenerationHistoryConfig&&window.V6GenerationHistoryConfig.technologies)||['Solar','Wind','Gas','Nuclear']).filter(function(t){return !hide[t]});e.innerHTML='';opts.forEach(function(t){var o=document.createElement('option');o.value=t;o.textContent=t;e.appendChild(o)});e.value=opts.indexOf('Solar')>=0?'Sol  … [line shortened here: 418 characters; full line on GitHub]
  function setStatus(t){var e=byId('generation-mwh-status');if(e)e.textContent=t}
  function refresh(){setStatus('Loading MWh data...');Promise.all([window.V6LoadGenerationMwhAggregates.annual(),window.V6LoadGenerationMwhAggregates.monthly(),window.V6LoadGenerationMwhAggregates.dayNight(),window.V6LoadGenerationMwhAggregates.interconnectorIndex(),window.V6LoadGenerationMwhAggregates.interconnectorTotals()]).then(function(p){window.V6RenderGenerationMwhAggregates.annual(byId('ge  … [line shortened here: 806 characters; full line on GitHub]
  function init(){fillTech();var e=byId('generation-mwh-technology');if(e)e.addEventListener('change',refresh);refresh()}
  return{init:init,refresh:refresh};
})();
document.addEventListener('DOMContentLoaded',function(){window.V6ControlGenerationMwhAggregates.init()});

Live Config

A JavaScript file in the generation history folder of GlobalGrid2050 covering generation daily mw spine fuelhh candidate, Elexon generation sources and pvlive solar daily browser.

renderglobalgrid2050 / uk_energy_tracking_v6/generation_history/live-config.js · lines 1–12 of 12 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
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_daily_mw_spine_fuelhh_candidate.json; JSON file elexon_generation_sources_2016.json; JSON file pvlive_solar_daily_browser.json; JSON file pvlive_solar_recent_30d_30min_browser.json; JSON file generation_recent_30d_30min.json; JSON file generation_ecg_all_technologies_30d_30min_candidate.json.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
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 uk_energy_tracking_v6/generation_history/live-config.js:1-12 · blob c19f2fec4af4c46a7a4cc6ebb6d12f5c4b74d5b9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6GenerationHistoryConfig={
  dailyHistory:'/data/confirmed/generation_daily_mw_spine_fuelhh_candidate.json',
  dailyHistoryFallback:'/data/generation/elexon_generation_sources_2016.json',
  solarDaily:'/uk_energy_tracking_v6/generation_history/pvlive_solar_daily_browser.json',
  solarRecentHalfHourly:'/uk_energy_tracking_v6/generation_history/pvlive_solar_recent_30d_30min_browser.json',
  recentHalfHourly:'/uk_energy_tracking_v6/generation_history/generation_recent_30d_30min.json',
  recentEcg:'/uk_energy_tracking_v6/generation_history/generation_ecg_all_technologies_30d_30min_candidate.json',
  annualBase:'/data/generation/elexon_generation_sources_',
  firstYear:2016,
  defaultTechnology:'Wind',
  technologies:['Solar','Wind','Hydro','Gas','Coal','Biomass','Nuclear','Pumped Storage','Imports & Exports','Other']
};

Load Generation History Data

A JavaScript file in GlobalGrid2050 that fetches solar and wind. It sorts half (`sortHalf`), sorts daily (`sortDaily`) and loads JSON once (`loadJsonOnce`).

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/load_generation_history_data.js · lines 1–30 of 30 · Not reached from any entry point (candidate for review) · pattern isDayNight (shared by 2 files)

What it does
It fetches solar and wind. Defines 21 functions or classes, including cfg, todayMax, minDate, periodDays, periodLabel. Side effects: changes the web page (DOM); makes network requests.
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, wind.
What it achieves
Its name says it loads generation history data. Defines `cfg`, `todayMax`, `minDate` and 18 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
cfg, todayMax, minDate, periodDays, periodLabel, isDayNight, tierFor, isDaily, isAll, sortHalf, sortDaily, dedupe
Defines here
cfg, todayMax, minDate, periodDays, periodLabel, isDayNight, tierFor, isDaily, isAll, sortHalf, sortDaily, dedupe, loadJsonOnce, loadDaily, loadSolarDaily, loadRecent, loadSolarRecent, totalHalf, totalDaily, seriesHalf, seriesDaily
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/load_generation_history_data.js:1-30 · blob 21e0778e31c65f9dc1d3853350ee39e2a75546d8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6LoadGenerationHistoryData=(function(){
var cache={daily:null,recent:null};
function cfg(){return window.V6GenerationHistoryConfig}
function todayMax(){var d=new Date();return new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59))}
function minDate(){return new Date(Date.UTC((cfg().firstYear||2016),0,1,0,0,0))}
function groupFor(fuel){var f=String(fuel||'').toUpperCase();if(f.indexOf('SOLAR')===0||f.indexOf('PV')===0)return'Solar';if(f.indexOf('WIND')===0)return'Wind';if(f.indexOf('NPSHYD')===0||f.indexOf('HYDRO')===0)return'Hydro';if(f.indexOf('CCGT')===0||f.indexOf('OCGT')===0)return'Gas';if(f.indexOf('COAL')===0)return'Coal';if(f.indexOf('BIOMASS')===0)return'Biomass';if(f.indexOf('NUCLEAR')===0)retur  … [line shortened here: 521 characters; full line on GitHub]
function periodDays(p){return{'12hday':0.5,'12hnight':0.5,'1d':1,'24h':1,'48h':2,'7d':7,'30d':30,'3m':92,'6m':183,'12m':366,'5y':1827,'10y':3653}[p]||7}
function periodLabel(p){return{'12hday':'12 hours day','12hnight':'12 hours night','1d':'1 day','24h':'24 hours','48h':'48 hours','7d':'1 week','30d':'1 month','3m':'3 months','6m':'3 months','12m':'12 months','5y':'5 years','10y':'10 years'}[p]||'1 week'}
function isDayNight(p){return p==='12hday'||p==='12hnight'}
function tierFor(p){return ['12hday','12hnight','1d','24h','48h','7d','30d'].indexOf(p)>=0?'recent':'daily'}
function isDaily(p){return tierFor(p)==='daily'}
function isAll(t){return!t||t==='All'}
function selectedWindow(start,period){var min=minDate(),max=todayMax();if(isDayNight(period))start.setUTCHours(period==='12hday'?6:18,0,0,0);if(start<min)start=new Date(min);if(start>max)start=new Date(max);var end=new Date(start.getTime()+periodDays(period)*86400000-1000);if(end>max)end=new Date(max);return{start:start,end:end,period:period,mode:tierFor(period)==='recent'?'halfhourly':'daily',tie  … [line shortened here: 419 characters; full line on GitHub]
function sortHalf(rows){return rows.slice().sort(function(a,b){return new Date(a.time)-new Date(b.time)})}
function sortDaily(rows){return rows.slice().sort(function(a,b){return a.date<b.date?-1:a.date>b.date?1:0})}
function dedupe(rows,fn){var seen={};return rows.filter(function(r){var k=fn(r);if(seen[k])return false;seen[k]=1;return true})}
function loadJsonOnce(key,url){if(cache[key])return cache[key];cache[key]=fetch(url+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]});return cache[key]}
function loadDaily(){return loadJsonOnce('daily',cfg().dailyHistory)}
function loadSolarDaily(){return loadJsonOnce('solarDaily',cfg().solarDaily||cfg().dailyHistory)}
function loadRecent(){return loadJsonOnce('recent',cfg().recentEcg||cfg().recentHalfHourly)}
function loadSolarRecent(){return loadJsonOnce('solarRecent',cfg().solarRecentHalfHourly||cfg().recentEcg||cfg().recentHalfHourly)}
function totalHalf(rows){var by={};rows.forEach(function(r){var k=r.time;if(!by[k])by[k]={time:k,generationMW:0,source:'Sum of generation technologies'};by[k].generationMW+=Number(r.generationMW)||0});return sortHalf(Object.keys(by).map(function(k){return by[k]}))}
function totalDaily(rows){var by={};rows.forEach(function(r){var k=r.date;if(!by[k])by[k]={date:k,averageMW:0,highMW:0,lowMW:0,source:'Sum of generation technologies'};by[k].averageMW+=Number(r.averageMW)||0;by[k].highMW+=Number(r.highMW)||0;by[k].lowMW+=Number(r.lowMW)||0});return sortDaily(Object.keys(by).map(function(k){return by[k]}))}
function seriesHalf(rows){var by={};rows.forEach(function(r){(by[r.technology]=by[r.technology]||[]).push(r)});return Object.keys(by).map(function(t){return{technology:t,rows:sortHalf(by[t])}})}
function seriesDaily(rows){var by={};rows.forEach(function(r){(by[r.technology]=by[r.technology]||[]).push(r)});return Object.keys(by).map(function(t){return{technology:t,rows:sortDaily(by[t])}})}
function loadHalf(meta,technology,timeMode){var source=technology==='Solar'?loadSolarRecent():loadRecent();return source.then(function(all){var rows=all.filter(function(r){var t=new Date(r.time);if(t<meta.start||t>meta.end)return false;if(timeMode==='day'){var h=t.getUTCHours();return h>=6&&h<18}if(timeMode==='night'){var hn=t.getUTCHours();return hn>=18||hn<6}return true});rows=dedupe(sortHalf(ro  … [line shortened here: 720 characters; full line on GitHub]
function loadDailyWindow(meta,technology){var source=technology==='Solar'?loadSolarDaily():loadDaily();return source.then(function(all){var rows=all.filter(function(r){var t=new Date(r.date+'T12:00:00Z');return t>=meta.start&&t<=meta.end});rows=dedupe(sortDaily(rows),function(r){return r.date+'|'+r.technology});if(isAll(technology))return{rows:totalDaily(rows),series:seriesDaily(rows),technology:'  … [line shortened here: 587 characters; full line on GitHub]
function loadWindow(start,period,technology,timeMode){var meta=selectedWindow(new Date(start),period),tech=technology||cfg().defaultTechnology||'Wind',build=meta.tier==='recent'?loadHalf(meta,tech,timeMode||'all'):loadDailyWindow(meta,tech);return build.then(function(out){return{mode:meta.mode,tier:meta.tier,start:meta.start,end:meta.end,period:period,technology:out.technology,timeMode:timeMode||'  … [line shortened here: 440 characters; full line on GitHub]
return{loadWindow:loadWindow,periodDays:periodDays,periodLabel:periodLabel,isDaily:isDaily,minDate:minDate,maxDate:todayMax,groupFor:groupFor};
})();

Load Generation MWh Aggregates

A JavaScript file in the generation history folder of GlobalGrid2050 that fetches generation annual mwh by technology, generation monthly mwh by technology and generation seasonal mwh by technology.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/load_generation_mwh_aggregates.js · lines 1–16 of 16 · Not reached from any entry point (candidate for review)

What it does
It fetches generation annual mwh by technology, generation monthly mwh by technology, generation seasonal mwh by technology and generation day night mwh by technology. Defines f. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file generation_annual_mwh_by_technology.json; JSON file generation_monthly_mwh_by_technology.json; JSON file generation_seasonal_mwh_by_technology.json; JSON file generation_day_night_mwh_by_technology.json; JSON file generation_interconnector_index.json; JSON file generation_interconnector_total_electricity_summary.json.
What it achieves
Its name says it loads generation MWh aggregates.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
f
Defines here
f
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/load_generation_mwh_aggregates.js:1-16 · blob 33576160ea72dede0638b88643b1981d60bfa797 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6LoadGenerationMwhAggregates=(function(){
  var cache={};
  function f(k,u){
    if(cache[k])return cache[k];
    cache[k]=fetch(u+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]});
    return cache[k];
  }
  return{
    annual:function(){return f('annual','/uk_energy_tracking_v6/generation_history/generation_annual_mwh_by_technology.json')},
    monthly:function(){return f('monthly','/uk_energy_tracking_v6/generation_history/generation_monthly_mwh_by_technology.json')},
    seasonal:function(){return f('seasonal','/uk_energy_tracking_v6/generation_history/generation_seasonal_mwh_by_technology.json')},
    dayNight:function(){return f('daynight','/uk_energy_tracking_v6/generation_history/generation_day_night_mwh_by_technology.json')},
    interconnectorIndex:function(){return f('icIndex','/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_index.json')},
    interconnectorTotals:function(){return f('icTotals','/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_total_electricity_summary.json')}
  };
})();

Render Generation History Chart

A JavaScript file in GlobalGrid2050 that works with nice date (`niceDate`) and nice clock (`niceClock`) and draws on a canvas (units: MW).

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/render_generation_history_chart.js · lines 1–22 of 22 · Not reached from any entry point (candidate for review) · pattern niceClock (shared by 3 files)

What it does
It draws its content. Defines 12 functions or classes, including fmt, niceDate, niceClock, valueOf, timeOf. Side effects: changes the web page (DOM).
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
Out: canvas drawing.
What it achieves
It is built from the nice date helper (`niceDate`), the nice clock helper (`niceClock`) and the value of helper (`valueOf`). Its name says it renders generation history chart. Defines `fmt`, `niceDate`, `niceClock` and 9 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
fmt, niceDate, niceClock, valueOf, timeOf, colour, compactMode, dateLabel, shortTickLabel, minMax, step, pointFns
Defines here
fmt, niceDate, niceClock, valueOf, timeOf, colour, compactMode, dateLabel, shortTickLabel, minMax, step, pointFns
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/render_generation_history_chart.js:1-22 · blob 9819689ae0baa61cb91b2678da381889c21bb3cc · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
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 valueOf(r,mode){return mode==='daily'?Number(r.averageMW):Number(r.generationMW)}
  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(mode){return 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',month:'short'})}
  function stats(result){var rows=result.rows||[];if(!rows.length)return null;var h=rows[0],l=rows[0],s=0,n=0;rows.forEach(function(r){var v=valueOf(r,result.mode);if(isNaN(v))return;s+=v;n++;if(v>valueOf(h,result.mode))h=r;if(v<valueOf(l,result.mode))l=r});return n?{hi:h,lo:l,avg:s/n,hiValue:valueOf(h,result.mode),loValue:valueOf(l,result.mode),hiDate:niceDate(timeOf(h,result.mode)),loDate:niceDa  … [line shortened here: 573 characters; full line on GitHub]
  function minMax(rows,mode){var lo=0,hi=0;rows.forEach(function(r){var v=valueOf(r,mode);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.mode);g.fillText(title,18*q,28*q);var lx=pad.left,ly=pad.top-24*q;g.shadowColor=c;g.shadowBlur=6*q;g.fill  … [line shortened here: 648 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==='HIGH'?-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.stroke();var l  … [line shortened here: 980 characters; full line on GitHub]
  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);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.fill  … [line shortened here: 937 characters; full line on GitHub]
  function drawSummary(g,s,q,w,h,pad){if(!s)return;var y=h-72*q,bw=w-pad.left-pad.right,x=pad.left,cols=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 cx=x+i*col+12*q;g.fillStyle='#9  … [line shortened here: 856 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: 883 characters; full line on GitHub]
  return{render:render};
})();

Render Generation MWh Aggregates

A JavaScript file in the generation history folder of GlobalGrid2050 that works with latest year (`latestYear`) and bar row (`barRow`) (units: MWh), covering solar, wind and interconnectors.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/generation_history/render_generation_mwh_aggregates.js · lines 1–34 of 34 · Not reached from any entry point (candidate for review) · pattern annual (shared by 2 files)

What it does
It draws solar, wind and interconnectors. Defines 6 functions or classes, including fmt, clean, latestYear, barRow, metric. Side effects: changes the web page (DOM).
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, wind, interconnectors.
What it achieves
It is built from the latest year helper (`latestYear`), the bar row helper (`barRow`) and the metric step (`metric`). Its name says it renders generation MWh aggregates. Defines `fmt`, `clean`, `latestYear` and 3 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/generation_history · script
Uses
none found
Used by
none found
Produces
fmt, clean, latestYear, barRow, metric, annual
Defines here
fmt, clean, latestYear, barRow, metric, annual
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/generation_history/render_generation_mwh_aggregates.js:1-34 · blob 136eac0f6d46919f7e3291ebe206247f2f35a6a0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6RenderGenerationMwhAggregates=(function(){
  var colours={Solar:'#f5c518',Wind:'#00d0ff',Hydro:'#0090c0',Gas:'#c0399a',Coal:'#888888',Biomass:'#f59e2b',Nuclear:'#5cb85c','Pumped Storage':'#9b59b6',Other:'#a6adbb'};
  var hide={'Imports & Exports':1};
  var ord={Solar:10,Wind:20,Gas:30,Nuclear:40,Biomass:50,Hydro:60,'Pumped Storage':70,Coal:80,Other:90};
  function fmt(n,d){return n==null||isNaN(Number(n))?'--':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function clean(rows){return(rows||[]).filter(function(r){return r&&!hide[r.technology]})}
  function latestYear(rows,extraRows){var ys=[];(rows||[]).forEach(function(r){ys.push(Number(r.year)||0)});(extraRows||[]).forEach(function(r){ys.push(Number(r.year)||0)});return Math.max.apply(null,ys)}
  function barRow(label,pct,value,colour,title){return '<div class="mwh-row" title="'+(title||label)+'"><div class="mwh-label">'+label+'</div><div class="mwh-track"><i style="width:'+Math.max(0,Math.min(100,pct))+'%;background:'+colour+'"></i></div><div class="mwh-value">'+value+'</div></div>'}
  function metric(label,value){return '<div class="mwh-check-metric"><span>'+label+'</span><strong>'+value+'</strong></div>'}
  function annual(el,rows,icIndex,totals){
    if(!el)return;
    rows=rows||[];icIndex=icIndex||[];totals=totals||[];
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data.</div>';return}
    var y=latestYear(rows,icIndex);
    var genRows=clean(rows.filter(function(r){return Number(r.year)===y})).sort(function(a,b){return(ord[a.technology]||999)-(ord[b.technology]||999)});
    var genTotal=genRows.reduce(function(s,r){return s+Math.max(0,Number(r.totalMWh||0))},0);
    var h='<div class="mwh-aggregate-head"><strong>Annual MWh by technology</strong><span>'+y+' - generation shown</span></div><div class="mwh-bars">';
    genRows.forEach(function(r){var v=Number(r.totalMWh||0),p=genTotal?Math.max(0,v)/genTotal*100:0,c=colours[r.technology]||'#00ffff';h+=barRow(r.technology,p,fmt(v/1000000,2)+' TWh',c,r.technology+' '+fmt(v/1000000,2)+' TWh')});
    h+='</div>';
    var links=(icIndex||[]).filter(function(r){return Number(r.year)===y}).sort(function(a,b){return(Number(a.sortOrder)||0)-(Number(b.sortOrder)||0)});
    if(links.length){
      var maxAbs=Math.max.apply(null,links.map(function(r){return Math.max(Math.abs(Number(r.importMWh||0)),Math.abs(Number(r.exportMWh||0)),Math.abs(Number(r.netMWh||0)),1)}));
      h+='<div class="mwh-aggregate-head mwh-section-head"><strong>Interconnectors</strong><span>net flow shown</span></div><div class="mwh-bars">';
      links.forEach(function(r){var net=Number(r.netMWh||0),imp=Number(r.importMWh||0),exp=Number(r.exportMWh||0),p=Math.max(2,Math.abs(net)/maxAbs*100),c=net>=0?'#00d0ff':'#ff7777',label=r.country+' - '+r.bmrsCode,title=r.label+' | import '+fmt(imp/1000000,2)+' TWh | export '+fmt(exp/1000000,2)+' TWh | net '+fmt(net/1000000,2)+' TWh';h+=barRow(label,p,fmt(net/1000000,2)+' TWh',c,title)});
      h+='</div>';
    }
    var total=(totals||[]).filter(function(r){return Number(r.year)===y})[0];
    if(total){h+='<div class="mwh-total-check"><div class="mwh-aggregate-head mwh-section-head"><strong>Total electricity check</strong><span>reconciliation</span></div><div class="mwh-check-grid">'+metric('Generation',fmt(total.generationShownMWh/1000000,2)+' TWh')+metric('Imports',fmt(total.totalImportMWh/1000000,2)+' TWh')+metric('Exports',fmt(total.totalExportMWh/1000000,2)+' TWh')+metric('Net  … [line shortened here: 548 characters; full line on GitHub]
    el.innerHTML=h;
  }
  function monthly(el,rows,technology){if(!el)return;rows=clean(rows).filter(function(r){return !technology||r.technology===technology});if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting monthly MWh aggregate data.</div>';return}rows=rows.slice().sort(function(a,b){return(a.year-b.year)||(a.month-b.month)});var mx=Math.max.apply(null,rows.map(function(r){return Number(r.totalMWh)||0})  … [line shortened here: 910 characters; full line on GitHub]
  function dayNight(el,rows,technology){if(!el)return;rows=clean(rows).filter(function(r){return !technology||r.technology===technology});if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting day/night aggregate data.</div>';return}var y=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0})),day=0,night=0;rows.filter(function(r){return Number(r.year)===y}).forEach(function(r  … [line shortened here: 902 characters; full line on GitHub]
  return{annual:annual,monthly:monthly,dayNight:dayNight};
})();

Live Config

A JavaScript file in the live data pipeline folder of GlobalGrid2050 covering live grid energy, live grid price, live oil prices and oil price history.

renderglobalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/live-config.js · lines 1–14 of 14 · Entry point

What it does
Side effects: changes the web page (DOM).
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; CSV file grid_frequency_history.csv; JSON file live_grid_frequency.json.
Downstream impact
Used directly by 2 files: GB Electricity Price Grid Constraint Evidence Charts (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/gb_electricity_price_grid_constraint_evidence_charts.html); Great Britain Electricity Price Grid Constraint Trends 2016 2026 (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html). Reached from 65 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Data — Grid Studies Public Page (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the GB Electricity Price Grid Constraint Evidence Charts page at https://globalgrid2050.com/data/grid_studies_public/gb_electricity_price_grid_constraint_evidence_charts.html and 1 other page.
Application
globalgrid2050 · uk_energy_tracking_v6/live_data_pipeline · script
Uses
none found
Used by
loaded by GB Electricity Price Grid Constraint Evidence Charts (script src), loaded by Great Britain Electricity Price Grid Constraint Trends 2016 2026 (script src)
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 uk_energy_tracking_v6/live_data_pipeline/live-config.js:1-14 · blob 5dd69f16d73c3e8f8eb7beafe341f49e57d27745 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
window.V6LiveConfig={
  energy:'/uk_energy_tracking_v6/live_grid_energy.json',
  price:'/uk_energy_tracking_v6/live_grid_price.json',
  commodities:'/uk_energy_tracking_v6/live_oil_prices.json',
  oilHistory:'/uk_energy_tracking_v6/oil_price_history.geojson',
  fuel:'/uk_energy_tracking_v6/live_uk_fuel_prices.json',
  evPrices:'/uk_energy_tracking_v6/ev_charging_prices.json',
  frequencyCsv:'/uk_energy_tracking_v6/grid_frequency_history.csv',
  frequencyLive:'/uk_energy_tracking_v6/live_grid_frequency.json',
  frequencyWeekly:'/uk_energy_tracking_v6/live_grid_frequency_weekly_health.json',
  priceHistory:'/uk_energy_tracking_v6/electricity_price_history.json',
  dailyPriceHistory:'/uk_energy_tracking_v6/electricity_price_history_daily_decade.json',
  annualBase:'/data/electricity/elexon_system_prices_'
};

Load JSON

A JavaScript file in the live data pipeline folder of GlobalGrid2050. It loads JSON (`loadJson`).

renderglobalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/load_json/load_json.js · lines 1–4 of 4 · Not reached from any entry point (candidate for review) · pattern loadJson (shared by 5 files)

What it does
It fetches data. Defines loadJson. Side effects: changes the web page (DOM); 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.
What it achieves
Its name says it loads JSON. Defines `loadJson`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/live_data_pipeline/load_json · script
Uses
none found
Used by
none found
Produces
loadJson
Defines here
loadJson
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/live_data_pipeline/load_json/load_json.js:1-4 · blob 9cb26e2acf113cd9914b3347f1b2ee3b2a1ce69c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6LoadJson=(function(){
  function loadJson(url){return fetch(url+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():null}).catch(function(){return null})}
  return{loadJson:loadJson};
})();

Render Generation Mix

A JavaScript file in the live data pipeline folder of GlobalGrid2050.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/render_generation_mix/render_generation_mix.js · lines 1–20 of 20 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Defines render. Side effects: changes the web page (DOM).
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.
What it achieves
Its name says it renders generation mix. Defines `render`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/live_data_pipeline/render_generation_mix · script
Uses
none found
Used by
none found
Produces
render
Defines here
render
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/live_data_pipeline/render_generation_mix/render_generation_mix.js:1-20 · blob 9a6c7d465e32b7b845ed8087aebe9787dcdaeaa1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6RenderGenerationMix=(function(){
  function render(energy){
    var root=document.getElementById('generation-mix-grid');
    if(!root)return;
    var mix=(energy&&energy.mix)||[];
    root.innerHTML=mix.map(function(r){
      var width=Math.max(0,Math.min(100,Number(r.pct||0)));
      var color=r.color||'#00ffff';
      return '<div class="scada-mini">'+
        '<div class="scada-mini-top">'+
          '<div class="scada-mini-name">'+(r.label||'Source')+'</div>'+
          '<div class="scada-mini-value">'+Number(r.gw||0).toLocaleString('en-GB',{minimumFractionDigits:2,maximumFractionDigits:2})+' GW</div>'+
        '</div>'+
        '<div class="scada-mini-track"><div class="scada-mini-fill" style="width:'+width+'%;background:'+color+';box-shadow:0 0 10px '+color+'"></div></div>'+
        '<div class="commodity-unit">'+Number(r.pct||0).toLocaleString('en-GB',{minimumFractionDigits:2,maximumFractionDigits:2})+'%</div>'+
      '</div>';
    }).join('');
  }
  return{render:render};
})();

Render Live Snapshot

A JavaScript file in the live data pipeline folder of GlobalGrid2050 that works with latest iso (`latestIso`) and date label (`dateLabel`).

renderglobalgrid2050 / uk_energy_tracking_v6/live_data_pipeline/render_live_snapshot/render_live_snapshot.js · lines 1–29 of 29 · Not reached from any entry point (candidate for review) · pattern latestIso (shared by 3 files)

What it does
Defines latestIso, dateLabel, timeLabel, render. Side effects: changes the web page (DOM).
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.
What it achieves
It is built from the latest iso helper (`latestIso`), the date label helper (`dateLabel`) and the time label helper (`timeLabel`). Its name says it renders live snapshot. Defines `latestIso`, `dateLabel`, `timeLabel` and 1 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/live_data_pipeline/render_live_snapshot · script
Uses
none found
Used by
none found
Produces
latestIso, dateLabel, timeLabel, render
Defines here
latestIso, dateLabel, timeLabel, render
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/live_data_pipeline/render_live_snapshot/render_live_snapshot.js:1-29 · blob 7db57c80e8d4c46f3017f71b68cacd6b2dc3ab0a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
window.V6RenderLiveSnapshot=(function(){
  function latestIso(){
    var out=null;
    for(var i=0;i<arguments.length;i++){
      var v=arguments[i];
      if(!v)continue;
      var d=new Date(v);
      if(isNaN(d))continue;
      if(!out||d>out)out=d;
    }
    return out?out.toISOString():null;
  }
  function dateLabel(v){if(!v)return'—';var d=new Date(v);return isNaN(d)?'—':d.toLocaleDateString('en-GB',{day:'2-digit',month:'long',year:'numeric'})+' '+d.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'});}
  function timeLabel(v){if(!v)return'—';var d=new Date(v);return isNaN(d)?'—':d.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'});}
  function render(energy,price){
    var h=window.V6DomText;
    energy=energy||{};
    price=price||{};
    h.setText('summary-demand',h.fmt(energy.demandGW,2));
    h.setText('summary-price',h.fmt(price.priceGBPperMWh,2));
    var c=price.carbonGperKWh==null?price.carbonForecast:price.carbonGperKWh;
    h.setText('summary-carbon',c==null?'—':Math.round(Number(c)));
    var latest=latestIso(energy.updated,price.updated);
    h.setText('summary-timestamps',latest?'Updated: '+dateLabel(latest)+' · energy '+timeLabel(energy.updated)+' · price '+timeLabel(price.updated):'Awaiting source timestamps.');
    h.setText('m-updated-time',latest?dateLabel(latest):'Awaiting feed');
    h.setText('m-updated-meta','Energy '+timeLabel(energy.updated)+' · price '+timeLabel(price.updated));
  }
  return{render:render};
})();

Control Price History

A JavaScript file in the price history chart folder of GlobalGrid2050 that syncs fullscreen period (`syncFullscreenPeriod`), sets period (`setPeriod`) and attaches period buttons (`attachPeriodButtons`).

energy-dataglobalgrid2050 / uk_energy_tracking_v6/price_history_chart/control_price_history/control_price_history.js · lines 1–33 of 33 · Not reached from any entry point (candidate for review) · pattern futureMaxDate (shared by 2 files)

What it does
It draws its content. Defines 17 functions or classes, including $, ymd, maxDate, futureMaxDate, minDate. Side effects: changes the web page (DOM).
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.
What it achieves
It syncs fullscreen period (`syncFullscreenPeriod`), sets period (`setPeriod`) and attaches period buttons (`attachPeriodButtons`). Defines `ymd`, `maxDate`, `futureMaxDate` and 13 more. It responds to click, change and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/price_history_chart/control_price_history · script
Uses
none found
Used by
none found
Produces
$, ymd, maxDate, futureMaxDate, minDate, periodDays, activeDataYear, yearCutoff, yearLabel, ensureYearOptions, currentPeriod, syncFullscreenPeriod
Defines here
$, ymd, maxDate, futureMaxDate, minDate, periodDays, activeDataYear, yearCutoff, yearLabel, ensureYearOptions, currentPeriod, syncFullscreenPeriod, setPeriod, attachPeriodButtons, bindFullscreenPeriodSelect, debouncedLoad, closeFullscreen
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/price_history_chart/control_price_history/control_price_history.js:1-33 · blob 71ec5be450afa63812558a664e05b56785d8c234 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
window.V6ControlPriceHistory=(function(){
  var FIRST_YEAR=2016;
  var YEAR_ROLLOVER_MONTH=0;
  var YEAR_ROLLOVER_DAY=15;
  var STATE={timeMode:'all'};
  function $(id){return document.getElementById(id)}
  function ymd(d){return d.toISOString().slice(0,10)}
  function maxDate(){return window.V6LoadPriceHistoryData.maxDate()}
  function futureMaxDate(){return window.V6LoadPriceHistoryData.futureMaxDate?window.V6LoadPriceHistoryData.futureMaxDate():maxDate()}
  function minDate(){return window.V6LoadPriceHistoryData.minDate()}
  function periodDays(p){return window.V6LoadPriceHistoryData.periodDays(p)}
  function activeDataYear(){var d=new Date();var y=d.getUTCFullYear();if(d.getUTCMonth()===YEAR_ROLLOVER_MONTH&&d.getUTCDate()<YEAR_ROLLOVER_DAY)return y-1;return y}
  function yearCutoff(year){var m=maxDate(),active=activeDataYear();if(year===active&&year===m.getUTCFullYear())return m;return new Date(Date.UTC(year,11,31,23,59,59))}
  function yearLabel(year){return year===activeDataYear()?String(year)+' YTD':String(year)}
  function ensureYearOptions(){var y=$('price-history-year');if(!y||y.options.length)return;var active=activeDataYear();for(var n=active;n>=FIRST_YEAR;n--){var o=document.createElement('option');o.value=String(n);o.textContent=yearLabel(n);y.appendChild(o)}y.value=String(active)}
  function ensureStartDate(){var y=$('price-history-year'),s=$('price-history-start');if(!s)return;var selectedYear=y&&y.value?Number(y.value):activeDataYear();if(!s.value||s.value.slice(0,4)!==String(selectedYear)){var start;if(selectedYear===activeDataYear()){var cutoff=yearCutoff(selectedYear);start=new Date(cutoff.getTime()-7*86400000);var jan1=new Date(Date.UTC(selectedYear,0,1,0,0,0));if(sta  … [line shortened here: 493 characters; full line on GitHub]
  function ensureModeTabs(){if($('price-history-time-tabs'))return;var actions=document.querySelector('#electricity-price-history-panel .price-history-actions');if(!actions)return;var tabs=document.createElement('div');tabs.id='price-history-time-tabs';tabs.className='price-history-time-tabs';tabs.innerHTML='<span>Hour filter</span><button type="button" data-mode="all" class="active">All</button><  … [line shortened here: 771 characters; full line on GitHub]
  function currentPeriod(){var p=$('price-history-period');return p&&p.value?p.value:'7d'}
  function syncFullscreenPeriod(){var p=$('price-history-period'),fp=$('price-history-fullscreen-period-select');if(p&&fp&&fp.value!==p.value)fp.value=p.value}
  function setPeriod(value){var p=$('price-history-period');if(p)p.value=value;syncFullscreenPeriod();load()}
  function nudgePeriod(direction){var s=$('price-history-start');if(!s)return;var period=currentPeriod();var current=s.value?new Date(s.value+'T00:00:00Z'):new Date(maxDate().getTime()-7*86400000);var days=Math.max(1,Math.round(periodDays(period)));var next=new Date(current.getTime()+direction*days*86400000);if(next<minDate())next=minDate();if(next>futureMaxDate())next=futureMaxDate();s.value=ymd(  … [line shortened here: 486 characters; full line on GitHub]
  function attachPeriodButtons(scope){var back=$(scope+'-back'),forward=$(scope+'-forward');if(back&&!back.dataset.bound){back.dataset.bound='1';back.addEventListener('click',function(){nudgePeriod(-1)})}if(forward&&!forward.dataset.bound){forward.dataset.bound='1';forward.addEventListener('click',function(){nudgePeriod(1)})}}
  function ensurePeriodControls(){if($('price-history-period-nav'))return;var canvas=$('price-history-canvas');if(!canvas||!canvas.parentNode)return;var nav=document.createElement('div');nav.id='price-history-period-nav';nav.className='price-history-chart-nav';nav.innerHTML='<button type="button" id="price-history-period-back">◀ Previous period</button><button type="button" id="price-history-perio  … [line shortened here: 534 characters; full line on GitHub]
  function bindFullscreenPeriodSelect(){var fp=$('price-history-fullscreen-period-select');if(!fp||fp.dataset.bound)return;fp.dataset.bound='1';syncFullscreenPeriod();fp.addEventListener('change',function(){setPeriod(fp.value)})}
  var pending=null;
  function debouncedLoad(){clearTimeout(pending);pending=setTimeout(load,120)}
  function load(){ensureStartDate();syncFullscreenPeriod();var s=$('price-history-start'),period=currentPeriod();var start=s&&s.value?new Date(s.value+'T00:00:00Z'):new Date(maxDate().getTime()-7*86400000);return window.V6LoadPriceHistoryData.loadWindow(start,period,STATE.timeMode).then(function(result){var meta=$('price-history-fullscreen-meta');if(meta)meta.textContent=new Date(result.start).toL  … [line shortened here: 599 characters; full line on GitHub]
  function openFullscreen(){var o=$('price-history-fullscreen-overlay');if(!o)return;syncFullscreenPeriod();o.classList.add('open');document.documentElement.classList.add('v5-chart-open');document.body.classList.add('v5-chart-open');attachPeriodButtons('price-history-fullscreen-period');setTimeout(function(){if(window.V6RenderPriceChart.redrawFullscreen)window.V6RenderPriceChart.redrawFullscreen()  … [line shortened here: 406 characters; full line on GitHub]
  function closeFullscreen(){var o=$('price-history-fullscreen-overlay');if(!o)return;o.classList.remove('open');document.documentElement.classList.remove('v5-chart-open');document.body.classList.remove('v5-chart-open')}
  function attachFullscreenSwipe(){var c=$('price-history-fullscreen-canvas');if(!c||c.dataset.swipeBound)return;c.dataset.swipeBound='1';var sx=0,sy=0,active=false;c.addEventListener('touchstart',function(e){if(!e.touches||!e.touches.length)return;var t=e.touches[0];sx=t.clientX;sy=t.clientY;active=true},{passive:true});c.addEventListener('touchend',function(e){if(!active)return;active=false;var   … [line shortened here: 587 characters; full line on GitHub]
  function start(){ensureYearOptions();ensureModeTabs();ensurePeriodControls();ensureStartDate();attachPeriodButtons('price-history-fullscreen-period');attachFullscreenSwipe();bindFullscreenPeriodSelect();var btn=$('price-history-refresh'),period=$('price-history-period'),startEl=$('price-history-start'),year=$('price-history-year');if(btn)btn.addEventListener('click',load);if(period)period.addEve  … [line shortened here: 889 characters; full line on GitHub]
  return{start:start,load:load,activeDataYear:activeDataYear};
})();

Fullscreen Period Menu

A JavaScript file in the price history chart folder of GlobalGrid2050 that syncs button (`syncButton`). It closes menu (`closeMenu`) and syncs button (`syncButton`).

renderglobalgrid2050 / uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js · lines 1–45 of 45 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Defines byId, textFor, closeMenu, syncButton, start. Side effects: changes the web page (DOM).
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.
What it achieves
Defines `byId`, `textFor`, `closeMenu` and 2 more. It responds to click and change events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu · script
Uses
none found
Used by
none found
Produces
byId, textFor, closeMenu, syncButton, start
Defines here
byId, textFor, closeMenu, syncButton, start
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js:1-45 · blob e168eaecaa17734a2a7720a7fc335a031ddcc477 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
window.V6FullscreenPeriodMenu=(function(){
  function byId(id){return document.getElementById(id)}
  function textFor(select){var opt=select.options[select.selectedIndex];return opt?opt.textContent:select.value}
  function closeMenu(){var wrap=byId('price-history-fullscreen-period-menu');if(wrap)wrap.classList.remove('open')}
  function syncButton(){var select=byId('price-history-fullscreen-period-select');var button=byId('price-history-fullscreen-period-button');if(select&&button)button.textContent=textFor(select)}
  function start(){
    var select=byId('price-history-fullscreen-period-select');
    if(!select||select.dataset.scadaMenu)return;
    var label=select.closest('label');
    if(!label)return;
    select.dataset.scadaMenu='1';
    select.classList.add('price-history-native-hidden');
    var wrap=document.createElement('span');
    wrap.id='price-history-fullscreen-period-menu';
    wrap.className='price-history-custom-period';
    var button=document.createElement('button');
    button.type='button';
    button.id='price-history-fullscreen-period-button';
    button.className='price-history-custom-period-button';
    var list=document.createElement('div');
    list.className='price-history-custom-period-list';
    Array.prototype.forEach.call(select.options,function(opt){
      var item=document.createElement('button');
      item.type='button';
      item.className='price-history-custom-period-option';
      item.dataset.value=opt.value;
      item.textContent=opt.textContent;
      item.addEventListener('click',function(){
        select.value=opt.value;
        select.dispatchEvent(new Event('change',{bubbles:true}));
        closeMenu();
        syncButton();
      });
      list.appendChild(item);
    });
    button.addEventListener('click',function(ev){ev.preventDefault();ev.stopPropagation();wrap.classList.toggle('open')});
    wrap.appendChild(button);
    wrap.appendChild(list);
    label.appendChild(wrap);
    document.addEventListener('click',closeMenu);
    select.addEventListener('change',syncButton);
    syncButton();
  }
  return{start:start,sync:syncButton};
})();

Load Price History Data

A JavaScript file in the price history chart folder of GlobalGrid2050 that parses CSV line (`parseCsvLine`) and loads annual (`loadAnnual`) and daily (`loadDaily`).

energy-dataglobalgrid2050 / uk_energy_tracking_v6/price_history_chart/load_price_history_data/load_price_history_data.js · lines 1–29 of 29 · Entry point · pattern futureMaxDate (shared by 2 files)

What it does
It fetches data. Defines 16 functions or classes, including todayMax, forecastMaxDate, minDate, futureMaxDate, ymd. Side effects: changes the web page (DOM); 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.
Downstream impact
Used directly by 2 files: GB Electricity Price Grid Constraint Evidence Charts (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/gb_electricity_price_grid_constraint_evidence_charts.html); Great Britain Electricity Price Grid Constraint Trends 2016 2026 (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html). Reached from 65 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Data — Grid Studies Public Page (globalgrid2050, https://globalgrid2050.com/data/grid_studies_public/); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
It parses CSV line (`parseCsvLine`), loads annual (`loadAnnual`) and loads daily (`loadDaily`). Its name says it loads price history data. Defines `todayMax`, `forecastMaxDate`, `minDate` and 13 more.
Why it matters
Loaded by the GB Electricity Price Grid Constraint Evidence Charts page at https://globalgrid2050.com/data/grid_studies_public/gb_electricity_price_grid_constraint_evidence_charts.html and 1 other page.
Application
globalgrid2050 · uk_energy_tracking_v6/price_history_chart/load_price_history_data · script
Uses
none found
Used by
loaded by GB Electricity Price Grid Constraint Evidence Charts (script src), loaded by Great Britain Electricity Price Grid Constraint Trends 2016 2026 (script src)
Produces
todayMax, forecastMaxDate, minDate, futureMaxDate, ymd, mean, parseCsvLine, periodDays, periodLabel, isDaily, isDayNight, loadAnnual
Defines here
todayMax, forecastMaxDate, minDate, futureMaxDate, ymd, mean, parseCsvLine, periodDays, periodLabel, isDaily, isDayNight, loadAnnual, loadDaily, years, sameMonthDay, sameMonthDow
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/price_history_chart/load_price_history_data/load_price_history_data.js:1-29 · blob 1ef08898c0b492d2e83530e6cea48bde41c4332b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
window.V6LoadPriceHistoryData=(function(){
  var cache={annual:{},daily:null,capture:null};
  var FIRST_YEAR=2016;
  function todayMax(){var d=new Date();return new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59))}
  function forecastMaxDate(){return new Date(todayMax().getTime()+7*86400000)}
  function minDate(){return new Date(Date.UTC(FIRST_YEAR,0,1,0,0,0))}
  function futureMaxDate(){return forecastMaxDate()}
  function ymd(d){return d.toISOString().slice(0,10)}
  function mean(vals){var a=vals.filter(function(v){return !isNaN(Number(v))}).map(Number);return a.length?a.reduce(function(x,y){return x+y},0)/a.length:0}
  function parseCsvLine(line){var out=[],v='',q=false;for(var i=0;i<line.length;i++){var c=line[i];if(c==='"'){if(q&&line[i+1]==='"'){v+='"';i++}else q=!q}else if(c===','&&!q){out.push(v);v=''}else v+=c}out.push(v);return out}
  function parseCsv(text){text=(text||'').trim();if(!text)return[];var lines=text.split(/\r?\n/),head=parseCsvLine(lines[0]).map(function(x){return x.trim()});return lines.slice(1).map(function(line){var cells=parseCsvLine(line),r={};head.forEach(function(h,i){r[h]=(cells[i]||'').trim()});var price=r.systemBuyPriceGBPperMWh||r.systemSellPriceGBPperMWh||r.priceGBPperMWh||'';return{source:r.source||  … [line shortened here: 815 characters; full line on GitHub]
  function norm(rows){var seen={};return(rows||[]).filter(function(r){return r.priceTimeUTC&&r.priceGBPperMWh!==''&&!isNaN(Number(r.priceGBPperMWh))}).map(function(r){var o=Object.assign({},r);o.priceGBPperMWh=Number(o.priceGBPperMWh);return o}).sort(function(a,b){return new Date(a.priceTimeUTC)-new Date(b.priceTimeUTC)}).filter(function(r){var k=r.priceTimeUTC+'|'+r.priceGBPperMWh+'|'+(r.source||  … [line shortened here: 452 characters; full line on GitHub]
  function periodDays(p){return {'12hday':0.5,'12hnight':0.5,'1d':1,'24h':1,'48h':2,'7d':7,'30d':30,'3m':92,'6m':183,'12m':366,'5y':1827,'10y':3653}[p]||7}
  function periodLabel(p){return {'12hday':'12 hours day','12hnight':'12 hours night','1d':'1 day','24h':'24 hours','48h':'48 hours','7d':'1 week','30d':'1 month','3m':'3 months','6m':'6 months','12m':'12 months','5y':'5 years','10y':'10 years'}[p]||'1 week'}
  function isDaily(p){return ['12m','5y','10y'].indexOf(p)>=0}
  function isDayNight(p){return p==='12hday'||p==='12hnight'}
  function loadAnnual(year){if(cache.annual[year])return cache.annual[year];cache.annual[year]=fetch(window.V6LiveConfig.annualBase+year+'.csv?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.text():''}).then(parseCsv).catch(function(){return[]});return cache.annual[year]}
  function loadCapture(){if(cache.capture)return cache.capture;cache.capture=fetch(window.V6LiveConfig.priceHistory+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(j){return(j.rows||[]).map(function(r){return{source:r.source||'V6 captured Elexon Market Index Price',priceTimeUTC:r.priceTimeUTC||r.periodStartUTC||'',capturedAtUTC:r.capturedAtUTC||  … [line shortened here: 666 characters; full line on GitHub]
  function loadDaily(){if(cache.daily)return cache.daily;cache.daily=fetch(window.V6LiveConfig.dailyPriceHistory+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]});return cache.daily}
  function years(start,end){var out=[],last=todayMax().getUTCFullYear();for(var y=start.getUTCFullYear();y<=end.getUTCFullYear()&&y<=last;y++)out.push(y);return out}
  function selectedWindow(start,period){var min=minDate(),fmax=forecastMaxDate();if(isDayNight(period))start.setUTCHours(period==='12hday'?6:18,0,0,0);if(start<min)start=new Date(min);if(start>fmax)start=new Date(fmax);var end=new Date(start.getTime()+periodDays(period)*86400000-1000);if(end>fmax)end=new Date(fmax);return{start:start,end:end,period:period,mode:isDaily(period)?'daily':'halfhourly'}  … [line shortened here: 401 characters; full line on GitHub]
  function loadHalf(meta,timeMode){return Promise.all([loadCapture()].concat(years(meta.start,meta.end).map(loadAnnual))).then(function(parts){var cap=parts[0],sys=[];parts.slice(1).forEach(function(p){sys=sys.concat(p)});var all=norm(sys.concat(cap));return all.filter(function(r){var t=new Date(r.priceTimeUTC);if(t<meta.start||t>meta.end)return false;if(timeMode==='day'){var h=t.getUTCHours();ret  … [line shortened here: 497 characters; full line on GitHub]
  function loadWindow(start,period,timeMode){var meta=selectedWindow(new Date(start),period);if(meta.mode==='daily')return loadDaily().then(function(all){var rows=all.filter(function(r){var t=new Date(r.date+'T12:00:00Z');return t>=meta.start&&t<=meta.end});return{mode:'daily',start:meta.start,end:meta.end,period:period,timeMode:timeMode||'all',rows:rows,forecastRows:[]}});return loadHalf(meta,tim  … [line shortened here: 557 characters; full line on GitHub]
  function sameMonthDay(row,target){return row.date&&row.date.slice(5,10)===target.slice(5,10)}
  function sameMonthDow(row,d){var rd=new Date(row.date+'T12:00:00Z');return rd.getUTCMonth()===d.getUTCMonth()&&rd.getUTCDay()===d.getUTCDay()}
  function forecastPoint(all,targetDate){var target=ymd(targetDate),actual=(all||[]).find(function(r){return r.date===target&&r.high!=null&&r.low!=null&&r.average!=null});if(actual)return{date:target,high:Number(actual.high),average:Number(actual.average),low:Number(actual.low),status:'actual',source:'Published Elexon daily aggregate'};var historic=(all||[]).filter(function(r){return r.date<target  … [line shortened here: 920 characters; full line on GitHub]
  function loadForecastWindow(){return loadDaily().then(function(all){var start=new Date(todayMax().getTime()+1000),rows=[];for(var i=0;i<7;i++){rows.push(forecastPoint(all,new Date(start.getTime()+i*86400000)))}return{mode:'forecast_daily',start:start,end:new Date(start.getTime()+6*86400000),rows:rows,method:'Forecast values are the 10 year daily average for high, average and low on the matching   … [line shortened here: 533 characters; full line on GitHub]
  return{loadWindow:loadWindow,loadForecastWindow:loadForecastWindow,periodDays:periodDays,periodLabel:periodLabel,isDaily:isDaily,minDate:minDate,maxDate:todayMax,futureMaxDate:futureMaxDate};
})();

Render Price Chart Box Overlay

A JavaScript file in the price history chart folder of GlobalGrid2050 that works with nice date (`niceDate`) and nice clock (`niceClock`) and draws on a canvas.

energy-dataglobalgrid2050 / uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_box_overlay.js · lines 1–25 of 25 · Not reached from any entry point (candidate for review) · pattern price (shared by 2 files)

What it does
It draws its content. Defines 12 functions or classes, including fmt, price, time, niceDate, niceClock. Side effects: changes the web page (DOM).
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
Out: canvas drawing.
What it achieves
It is built from the nice date helper (`niceDate`), the nice clock helper (`niceClock`) and the pence step (`pence`). Its name says it renders price chart box overlay. Defines `fmt`, `price`, `time` and 9 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/price_history_chart/render_price_chart · script
Uses
none found
Used by
none found
Produces
fmt, price, time, niceDate, niceClock, pence, compactDateText, values, minMax, boxText, boxSize, coverBox
Defines here
fmt, price, time, niceDate, niceClock, pence, compactDateText, values, minMax, boxText, boxSize, coverBox
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_box_overlay.js:1-25 · blob 3df78c4bb7dd2c92c992302ec647de978c5378d1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
(function(){
  if(!window.V6RenderPriceChart||window.V6RenderPriceChart.__boxOverlayApplied)return;
  var original=window.V6RenderPriceChart.render;
  function fmt(n,d){return n==null||isNaN(Number(n))?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function price(r){return Number(r.price!=null?r.price:r.priceGBPperMWh)}
  function time(r){return r.time||r.priceTimeUTC||r.date}
  function niceDate(v){var d=v instanceof Date?v:new Date(String(v||'').replace(' ','T')+'Z');if(isNaN(d.getTime()))d=new Date(v);return isNaN(d.getTime())?'—':d.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}
  function niceClock(v){var m=String(v||'').match(/(\d{2}:\d{2})/);return m?m[1]:''}
  function pence(v){return fmt(Number(v)/10,2)}
  function compactDateText(t){return String(t||'').replace(/January/g,'Jan').replace(/February/g,'Feb').replace(/March/g,'Mar').replace(/April/g,'Apr').replace(/June/g,'Jun').replace(/July/g,'Jul').replace(/August/g,'Aug').replace(/September/g,'Sep').replace(/October/g,'Oct').replace(/November/g,'Nov').replace(/December/g,'Dec')}
  function stats(result){var rows=result.rows||[];if(!rows.length)return null;if(result.mode==='daily'){var valid=rows.filter(function(r){return r.average!=null&&r.high!=null&&r.low!=null&&!isNaN(Number(r.average))&&!isNaN(Number(r.high))&&!isNaN(Number(r.low))});if(!valid.length)return null;var hi=valid[0],lo=valid[0],sum=0;valid.forEach(function(r){sum+=Number(r.average);if(Number(r.high)>Number  … [line shortened here: 920 characters; full line on GitHub]
  function values(result){var out=[];(result.rows||[]).forEach(function(r){if(result.mode==='daily'){['average','high','low'].forEach(function(k){var v=Number(r[k]);if(!isNaN(v))out.push(v)})}else{var v=price(r);if(!isNaN(v))out.push(v)}});return out.length?out:[0,100]}
  function minMax(v){var lo=0,hi=0;v.forEach(function(x){if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=Math.max((hi-lo)*.08,10);return{lo:lo-m,hi:hi+m}}
  function boxText(label,val,date,clock){return[label,'£'+fmt(val,2)+'/MWh   '+pence(val)+'p/kWh',compactDateText(date)+(clock?' '+clock:'')]}
  function boxSize(g,lines,q){var pad=7*q,lh=15*q,w=0;g.font='900 '+9.5*q+'px Courier New';lines.forEach(function(t){w=Math.max(w,g.measureText(t).width)});return{w:w+pad*2,h:lines.length*lh+pad*2,pad:pad,lh:lh}}
  function drawBox(g,lines,q,cx,cy,maxW){var s=boxSize(g,lines,q),bw=Math.min(s.w,maxW||s.w),bh=s.h,xx=cx-bw/2,yy=cy-bh/2;if(xx<8*q)xx=8*q;if(xx+bw>g.canvas.width-8*q)xx=g.canvas.width-bw-8*q;if(yy<8*q)yy=8*q;if(yy+bh>g.canvas.height-8*q)yy=g.canvas.height-bh-8*q;g.save();g.fillStyle='rgba(5,7,12,.92)';g.strokeStyle='rgba(0,255,255,.62)';g.lineWidth=1.2*q;g.shadowColor='rgba(0,255,255,.30)';g.shad  … [line shortened here: 813 characters; full line on GitHub]
  function coverBox(g,x,y,w,h,q){g.save();g.fillStyle='#05070c';g.fillRect(x-4*q,y-4*q,w+8*q,h+8*q);g.restore()}
  function overlay(canvasId,result){var c=document.getElementById(canvasId);if(!c||!result)return;var q=window.devicePixelRatio||1,g=c.getContext('2d'),w=c.width,h=c.height,cssW=w/q,cssH=h/q,isFull=canvasId==='price-history-fullscreen-canvas',isLandscape=isFull&&cssW>cssH;if(isLandscape)return;var pad=isFull?{left:58*q,right:18*q,top:104*q,bottom:285*q}:{left:74*q,right:24*q,top:96*q,bottom:284*q}  … [line shortened here: 870 characters; full line on GitHub]
    g.save();g.strokeStyle='#05070c';g.lineWidth=7*q;g.lineCap='round';g.beginPath();g.moveTo(hiX,hiY);g.lineTo(Math.min(w-pad.right-150*q,hiX+22*q),Math.max(pad.top+70*q,Math.min(h-pad.bottom-18*q,hiY+70*q))-22*q);g.moveTo(avgX,avgY);g.lineTo(avgX,Math.max(pad.top+118*q,Math.min(h-pad.bottom-74*q,avgY-42*q))-22*q);g.moveTo(loX,loY);g.lineTo(Math.max(pad.left+150*q,loX-22*q),Math.max(pad.top+74*q,  … [line shortened here: 467 characters; full line on GitHub]
    var oldHigh=boxSize(g,boxText('HIGH',s.hiValue,s.hiDate,s.hiClock),q),oldAvg=boxSize(g,boxText('AVERAGE',s.avg,'Visible period',''),q),oldLow=boxSize(g,boxText('LOW',s.loValue,s.loDate,s.loClock),q);coverBox(g,Math.min(w-pad.right-150*q,hiX+22*q),Math.max(pad.top+70*q,Math.min(h-pad.bottom-18*q,hiY+70*q))-oldHigh.h+4*q,oldHigh.w,oldHigh.h,q);coverBox(g,avgX-oldAvg.w/2,Math.max(pad.top+118*q,Ma  … [line shortened here: 619 characters; full line on GitHub]
    var blankTop=h-pad.bottom+58*q,available=Math.max(150*q,h-blankTop-18*q),rowGap=available/3,boxX=(pad.left+w-pad.right)/2,maxW=w-pad.left-pad.right;var targets=[{x:hiX,y:hiY,cx:boxX,cy:blankTop+rowGap*.35,lines:boxText('HIGH',s.hiValue,s.hiDate,s.hiClock)},{x:avgX,y:avgY,cx:boxX,cy:blankTop+rowGap*1.35,lines:boxText('AVERAGE',s.avg,'Visible period','')},{x:loX,y:loY,cx:boxX,cy:blankTop+rowGap*  … [line shortened here: 727 characters; full line on GitHub]
  }
  window.V6RenderPriceChart.render=function(canvasId,result){original.call(window.V6RenderPriceChart,canvasId,result);overlay(canvasId,result);overlay('price-history-fullscreen-canvas',result)};
  window.V6RenderPriceChart.__boxOverlayApplied=true;
})();

Render Price Chart V6 Clean Boxes

A JavaScript file in the price history chart folder of GlobalGrid2050 that draws dot (`drawDot`).

energy-dataglobalgrid2050 / uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_v6_clean_boxes.js · lines 1–31 of 31 · Not reached from any entry point (candidate for review) · pattern price (shared by 2 files)

What it does
It draws its content. Defines 19 functions or classes, including fmt, price, time, pence, set. Side effects: changes the web page (DOM).
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
Out: canvas drawing.
What it achieves
It draws dot (`drawDot`) and is built from the pence step (`pence`) and the set step (`set`). Its name says it renders price chart clean boxes. Defines `fmt`, `price`, `time` and 16 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_energy_tracking_v6/price_history_chart/render_price_chart · script
Uses
none found
Used by
none found
Produces
fmt, price, time, pence, set, niceDate, niceClock, seasonName, seasonColor, actualValue, forecastValue, values
Defines here
fmt, price, time, pence, set, niceDate, niceClock, seasonName, seasonColor, actualValue, forecastValue, values, minMax, step, dateLabel, drawDot, boxText, render, redrawFullscreen
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_v6_clean_boxes.js:1-31 · blob 2ed1a2d4013c13322570aa2de8f0a39b0d39f388 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
window.V6RenderPriceChart=(function(){
  var lastResult=null;
  function fmt(n,d){return n==null||isNaN(Number(n))?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function price(r){return Number(r.price!=null?r.price:r.priceGBPperMWh)}
  function time(r){return r.time||r.priceTimeUTC||r.date}
  function pence(v){return fmt(Number(v)/10,2)}
  function set(id,v){var e=document.getElementById(id);if(e)e.textContent=v}
  function niceDate(v){var d=v instanceof Date?v:new Date(String(v||'').replace(' ','T')+'Z');if(isNaN(d.getTime()))d=new Date(v);return isNaN(d.getTime())?'—':d.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}
  function niceClock(v){var m=String(v||'').match(/(\d{2}:\d{2})/);return m?m[1]:''}
  function seasonName(t){var m=new Date(t).getUTCMonth()+1;if(m===12||m<=2)return'Winter';if(m>=3&&m<=5)return'Spring';if(m>=6&&m<=8)return'Summer';return'Autumn'}
  function seasonColor(t){var s=seasonName(t);if(s==='Winter')return'#00ffff';if(s==='Spring')return'#00ff88';if(s==='Summer')return'#ffcc00';return'#c79245'}
  function actualValue(r,mode){return mode==='daily'?Number(r.average):price(r)}
  function forecastValue(r){return Number(r.forecast!=null?r.forecast:r.average)}
  function values(result){var out=[];(result.rows||[]).forEach(function(r){if(result.mode==='daily'){['average','high','low'].forEach(function(k){var v=Number(r[k]);if(!isNaN(v))out.push(v)})}else{var v=price(r);if(!isNaN(v))out.push(v)}});(result.forecastRows||[]).forEach(function(r){var f=forecastValue(r);if(!isNaN(f))out.push(f)});return out}
  function stats(result){var rows=result.rows||[];if(!rows.length)return null;if(result.mode==='daily'){var valid=rows.filter(function(r){return r.average!=null&&r.high!=null&&r.low!=null&&!isNaN(Number(r.average))&&!isNaN(Number(r.high))&&!isNaN(Number(r.low))});if(!valid.length)return null;var hi=valid[0],lo=valid[0],sum=0;valid.forEach(function(r){sum+=Number(r.average);if(Number(r.high)>Number  … [line shortened here: 970 characters; full line on GitHub]
  function minMax(v){var lo=0,hi=0;v.forEach(function(x){if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=Math.max((hi-lo)*.10,10);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 dateLabel(t,span){return span>45*86400000?new Date(t).toLocaleDateString('en-GB',{month:'short',year:'numeric'}):new Date(t).toLocaleDateString('en-GB')}
  function drawAxes(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;g.save();g.font=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='#f5f7fb';g.textAlign='left';g.fillText('£'+fmt(v,0).replace('-0','0'),8*q,y+4*q)}g.strokeStyle='rgba(255,255,255,.25)';g.lineWidth=1*q;g.begi  … [line shortened here: 707 characters; full line on GitHub]
  function drawKey(g,q,pad,isFull,result){var items=result.mode==='daily'?[['Average','#00ffff'],['High','#ffcc00'],['Low','#ff3333']]:[['Winter','#00ffff'],['Spring','#00ff88'],['Summer','#ffcc00'],['Autumn','#c79245']];var x=pad.left,y=pad.top-26*q;g.save();g.font=(isFull?8.5:9.5)*q+'px Courier New';items.forEach(function(it){g.fillStyle=it[1];g.shadowColor=it[1];g.shadowBlur=5*q;g.fillRect(x,y-  … [line shortened here: 511 characters; full line on GitHub]
  function decimateRows(rows,limit){if(!rows||rows.length<=limit)return rows||[];var out=[],bucket=Math.ceil(rows.length/limit);for(var i=0;i<rows.length;i+=bucket){var slice=rows.slice(i,i+bucket),hi=slice[0],lo=slice[0];slice.forEach(function(r){if(price(r)>price(hi))hi=r;if(price(r)<price(lo))lo=r});out.push(hi);if(lo!==hi)out.push(lo)}return out.sort(function(a,b){return new Date(time(a))-new   … [line shortened here: 416 characters; full line on GitHub]
  function drawDot(g,x,y,q,label){g.save();g.fillStyle='#ff3333';g.shadowColor='rgba(0,255,255,.85)';g.shadowBlur=8*q;g.beginPath();g.arc(x,y,5.2*q,0,Math.PI*2);g.fill();g.restore()}
  function boxText(label,val,date,clock){return[label,'£'+fmt(val,2)+'/MWh   '+pence(val)+'p/kWh',date+(clock?' '+clock:'')]}
  function drawBox(g,lines,q,cx,cy,maxW){var pad=8*q,lh=16*q,wid=0;g.save();g.font='900 '+9.5*q+'px Courier New';lines.forEach(function(t){wid=Math.max(wid,g.measureText(t).width)});var bw=Math.min(wid+pad*2,maxW||320*q),bh=lines.length*lh+pad*2,xx=cx-bw/2,yy=cy-bh/2;if(xx<8*q)xx=8*q;if(xx+bw>g.canvas.width-8*q)xx=g.canvas.width-bw-8*q;if(yy<8*q)yy=8*q;if(yy+bh>g.canvas.height-8*q)yy=g.canvas.heig  … [line shortened here: 863 characters; full line on GitHub]
  function drawTrackers(g,s,q,w,h,pad,X,Y){var top=pad.top,bottom=h-pad.bottom,plotH=bottom-top,zoneX=(pad.left+w-pad.right)/2;var hiX=X(s.hi),hiY=Y(s.hiValue),loX=X(s.lo),loY=Y(s.loValue),avgY=Y(s.avg);drawDot(g,hiX,hiY,q);drawDot(g,loX,loY,q);drawBox(g,boxText('HIGH',s.hiValue,s.hiDate,s.hiClock),q,zoneX,top+plotH*.18,w-pad.left-pad.right);drawBox(g,boxText('AVERAGE',s.avg,'Visible period',''),q  … [line shortened here: 541 characters; full line on GitHub]
  function drawDaily(g,result,q,X,Y){var rows=result.rows||[];[['high','#ffcc00'],['average','#00ffff'],['low','#ff3333']].forEach(function(s){g.save();g.lineWidth=2.2*q;g.lineCap='round';g.lineJoin='round';g.strokeStyle=s[1];g.shadowColor=s[1];g.shadowBlur=5*q;g.beginPath();var on=false;rows.forEach(function(r){var v=Number(r[s[0]]);if(isNaN(v))return;var x=X(r),y=Y(v);if(on)g.lineTo(x,y);else{g.  … [line shortened here: 448 characters; full line on GitHub]
  function renderTo(canvasId,result){var c=document.getElementById(canvasId);if(!c)return;var isFull=canvasId==='price-history-fullscreen-canvas';var q=window.devicePixelRatio||1,r=c.getBoundingClientRect();c.width=Math.max(320,Math.floor((r.width||900)*q));c.height=Math.max(420,Math.floor((r.height||720)*q));var g=c.getContext('2d'),w=c.width,h=c.height,cssW=w/q,cssH=h/q,isLandscape=isFull&&cssW>  … [line shortened here: 1,728 characters; full line on GitHub]
  function render(canvasId,result){lastResult=result;renderTo(canvasId,result);renderTo('price-history-fullscreen-canvas',result)}
  function redrawFullscreen(){if(lastResult)renderTo('price-history-fullscreen-canvas',lastResult)}
  return{render:render,redrawFullscreen:redrawFullscreen};
})();