GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / globalgrid2050 / grid_engine

Specs (part 1)

A JavaScript module in the grid engine folder of GlobalGrid2050 that tests substations and uses data from National Energy System Operator (NESO) data portal. Served with the page at https://globalgrid2050.com/grid_engine/.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Websites and apps. Section 1894 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. Specs test · globalgrid2050 / grid_engine/specs.mjs lines 583–1282

Specs

A JavaScript module in the grid engine folder of GlobalGrid2050 that tests substations and uses data from National Energy System Operator (NESO) data portal. Served with the page at https://globalgrid2050.com/grid_engine/.

testglobalgrid2050 / grid_engine/specs.mjs · lines 583–1282 of 1930 (continued from section 1893) · Not reached from any entry point (candidate for review) · pattern parseCrossings (shared by 2 files)

What it does
It tests substations, transformers, cables and solar. Defines 50 functions or classes, including bind, parseUnits, render, bind, render. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: substations, transformers, cables, solar, 400kV, 11kV.
Inputs & outputs
Voltage levels named: 400kV, 11kV.
Downstream impact
Used directly by 1 file: Build (globalgrid2050, https://globalgrid2050.com/grid_engine/).
What it achieves
It parses units (`parseUnits`), parses profile (`parseProfile`) and parses crossings (`parseCrossings`). One entry per workbench iteration. Its code works with 11 kV, 62.5 GW and 7 kW. It responds to input events.
Why it matters
Imported by Build.
Application
globalgrid2050 · grid_engine · JavaScript module
Uses
none found
Used by
imported by Build (import)
Produces
SPECS
Defines here
bind, render, bind, render, bind, parsePoly, render, bind, render, bind, render, bind, render, bind, parseUnits, 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 grid_engine/specs.mjs:583-1282 · blob 201bb20fe4483fed4abea7109c590ba20d030a9d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
            {
                heading: '1 · THE RECORD',
                lede: `A fault level is not one number. Make against break, three-phase against
                   single-phase, and a DC offset set by X/R — NESO's ETYS Appendix D publishes
                   <em>eight</em> separately named currents for one busbar, and collapsing them into
                   a generic "fault level" is the error this contract exists to prevent. Edit the
                   record below and watch it be accepted or refused. <strong>It opens refused on
                   purpose:</strong> the study basis is empty, because the estate's pinned ETYS
                   artefact genuinely records no basis today. That is a real open item, not a
                   contrived demonstration.`,
                controls: [
                    { id: 'rec', type: 'text', label: 'Study basis (fill this to see the record accepted)', value: '' }
                ],
                outId: 'out-record'
            },
            {
                heading: '2 · QUOTING ONE NAMED METRIC',
                lede: `Once a record is accepted, a figure may be quoted — but only one named metric
                   at a time, with its unit, site, busbar, voltage, publisher, basis and date attached.
                   Nothing here will ever print the bare words "fault level".`,
                controls: [
                    { id: 'metric', type: 'text', label: 'Metric name', value: 'three_phase_rms_break_current_ka' }
                ],
                outId: 'out-quote',
                tableId: 'metric-table',
                tableHead: [{ label: 'Metric ETYS publishes' }, { label: 'Unit', right: true }],
                note: `The eight ETYS metric names are listed above exactly as data-grid-gb
                   normalises them. A generic name — <code>fault_level</code>, <code>scl</code>,
                   <code>maximum_fault_level</code> — is refused outright, because a reader cannot
                   tell which current it is and the wrong one against the wrong switchgear rating is
                   how a screening tool becomes a false connection assessment.`
            }
        ],
        script: `
// The real pinned artefact: NESO ETYS 2025 Appendix D peak-demand workbook, with
// the byte count and SHA-256 recorded in data-grid-gb chatgpt/sources.json, and
// the publication date verified against NESO's documents page on 2026-09-06.
// study_basis is deliberately EMPTY: the estate does not record one, so the page
// opens refused rather than inventing a plausible string.
const BASE = {
  provenance: {
    publisher: 'NESO',
    publication: 'ETYS 2025 Appendix D — peak demand fault current scenarios',
    source_url: 'https://www.neso.energy/document/383951/download',
    sha256: 'ad8b54fa0b0562c34295514c150f33913a92fc756ff140e0154d53c181363440',
    published_date: '2026-06-30',
    study_basis: ''
  },
  site: { name: 'EXAMPLE 400 kV substation', voltage_kv: 400, busbar: 'A' },
  metrics: {
    three_phase_rms_break_current_ka: { min: 31.2, max: 34.8 },
    three_phase_initial_peak_current_ka: { min: 78.4, max: 88.1 }
  }
};

function bind() { ['rec','metric'].forEach(id => el(id).addEventListener('input', render)); }

function render() {
  const input = JSON.parse(JSON.stringify(BASE));
  input.provenance.study_basis = el('rec').value.trim();

  // record() returns { ok, record, refused }. quote() takes the INNER record,
  // not the envelope -- passing the envelope returns null, silently, which is
  // exactly what the first version of this page did.
  const r = E.record(input);
  const ok = r && r.ok === true && r.record;
  el('out-record').innerHTML =
    '<div class="figure"><span class="q">record()</span><span class="n' + (ok ? '' : ' over') + '">' +
    (ok ? 'ACCEPTED' : 'REFUSED') + '</span></div>' +
    '<p class="basis">' + (ok
      ? 'Every required field is present: publisher, publication, source URL, SHA-256, an ISO date, a study basis, a named site and voltage, and metrics named by exact metric. ' + (E.CAVEAT || '')
      : 'Refused: <b>' + ((r && r.refused) || 'unknown reason') + '</b>. ' +
        'This is the contract working. A figure without its basis is not a measurement, it is a rumour.') +
    '</p>';

  const tb = document.querySelector('#metric-table tbody');
  tb.innerHTML = E.ETYS_METRICS.map(n => {
    const m = E.METRIC_LABELS[n];
    return '<tr><td style="font-size:10px">' + n + '<div style="color:#7f8996">' +
      (m ? m.label : '') + '</div></td><td class="n">' + (m ? m.unit : '?') + '</td></tr>';
  }).join('');

  if (!ok) {
    el('out-quote').innerHTML = '<p class="basis" style="border:0;padding:0;margin:0">' +
      'No quotation: the record was refused, so there is nothing here that may be printed.</p>';
    return;
  }
  try {
    const name = el('metric').value.trim();
    const q = E.quote(r.record, name);
    el('out-quote').innerHTML = q === null || q === undefined
      ? '<div class="figure"><span class="q">quote()</span><span class="n over">NOT QUOTED</span></div>' +
        '<p class="basis">The engine will not quote <b>' + name + '</b> from this record. Either the ' +
        'record does not carry that metric, or the name is a generic one the contract refuses. ' +
        'Try one of the exact names in the table below.</p>'
      : '<div class="figure"><span class="q">quote()</span><span class="n" style="font-size:14px;line-height:1.4">' +
        (typeof q === 'string' ? q : JSON.stringify(q)) + '</span></div>' +
        '<p class="basis">' + (E.NO_HEADROOM || '') + '</p>';
  } catch (err) {
    el('out-quote').innerHTML = '<p class="basis" style="color:#ffae00;border:0;padding:0;margin:0">' +
      'Engine refused this metric: ' + err.message + '</p>';
  }
}`
    },
    {
        stamp: '202609060237',
        slug: 'corridor-estimate',
        title: 'Corridor Estimate Workbench',
        sub: 'The straight-line first pass, and the one multiplier that is allowed to touch it',
        feature: 'The calibrated straight-line-to-corridor factor for cable circuits, with the calibration sample, the error distribution, and the minimum separation below which it refuses to answer at all.',
        engineModule: 'corridor-estimate.js',
        engineCommit: '7d40365',
        schema: 'gridatlas.module.corridor-estimate.v1',
        checks: 15,
        panels: [
            {
                heading: '1 · STRAIGHT LINE TO CORRIDOR',
                lede: `A straight line is not a route. Buried cable circuits follow the highway
                   network, and across 95 published GB transmission cable circuits that detour
                   measures a factor of <strong>1.245</strong>. This is the estate's first pass and it
                   stays exactly as it is — everything else built tonight is additive to it.`,
                controls: [
                    { id: 'km', type: 'number', label: 'Straight-line distance (km)', value: '10', min: 0, max: 2000, step: 0.01 }
                ],
                outId: 'out-corridor'
            },
            {
                heading: '2 · WHERE IT REFUSES, AND WHY THAT MATTERS MORE',
                lede: `Below about a kilometre the factor is not measuring route detour at all — it is
                   measuring the distance between two site centroids, and the median error rises to
                   52.5%. So it returns <em>null</em>, not zero and not a small number. A tool that
                   answers everything cannot be trusted on anything.`,
                controls: [],
                tableId: 'basis-table',
                tableHead: [{ label: 'Calibration' }, { label: 'Value', right: true }],
                note: `The factor is calibrated on cable, which follows roads. Overhead line crosses
                   open country and measures 1.13 — published here only so a reader can see why the
                   cable factor is the wrong model for an overhead question. There is deliberately no
                   forOverhead().`
            }
        ],
        script: `
function bind() { el('km').addEventListener('input', render); }

function render() {
  const km = num('km');
  // forCable returns { km, factor, straight_km, withheld }. Below the minimum
  // separation it returns an OBJECT whose km is null and whose withheld says
  // why; only a zero distance returns null outright. Calling toFixed on that
  // null is what left this page showing a stale figure.
  const r = E.forCable(km);
  const value = r && r.km;
  el('out-corridor').innerHTML = (value === null || value === undefined)
    ? '<div class="figure"><span class="q">corridor estimate</span><span class="n over">NO ESTIMATE</span></div>' +
      '<p class="basis">' + ((r && r.withheld) || 'No distance given, so there is nothing to estimate.') + '</p>'
    : '<div class="figure"><span class="q">corridor estimate</span><span class="n">' +
      value.toFixed(2) + '</span><span class="u">km</span></div><p class="basis">' +
      'A straight line of ' + r.straight_km + ' km, multiplied by the calibrated cable factor of ' +
      r.factor + '. ' + E.CAVEAT + '</p>';

  const b = E.BASIS;
  document.querySelector('#basis-table tbody').innerHTML = [
    ['Cable factor', E.CABLE_FACTOR],
    ['Overhead factor (not applied here)', E.OHL_FACTOR],
    ['Circuits in the sample', b.circuits],
    ['Distinct site pairs', b.distinct_site_pairs],
    ['Median absolute error', b.median_absolute_error_pct + '%'],
    ['Within 15%', b.within_15_pct + '%'],
    ['Minimum separation', b.minimum_separation_km + ' km']
  ].map(r2 => '<tr><td>' + r2[0] + '</td><td class="n">' + r2[1] + '</td></tr>').join('') +
    '<tr><td colspan="2" style="font-size:10px;color:#7f8996">' + b.sample_note + '</td></tr>';
}`
    },
    {
        stamp: '202609060238',
        slug: 'site-geometry',
        title: 'Site Geometry Workbench',
        sub: 'Distance, bearing, area and perimeter on the one geodesy the estate agrees on',
        feature: 'Great-circle distance and bearing between two points, and polygon area, perimeter and circle-cap area for a site boundary — computed by the same geodesy every map in the estate uses.',
        engineModule: ['v9-geodesy.js', 'geo-area.js'],
        engineCommit: '7d40365',
        schema: ['gridatlas.module.geodesy.v1', null],
        checks: 23,
        panels: [
            {
                heading: '1 · TWO POINTS',
                lede: `Great-circle distance and initial bearing, in (longitude, latitude) order — the
                   order the estate standardised on after mixing it up cost a day. The radius is
                   6378.137 km, the equatorial figure the Atlas uses; the estate also carries a UK
                   figure and a mean figure, and which one is correct depends on the question.`,
                controls: [
                    { id: 'lon1', type: 'number', label: 'From longitude', value: '-1.4', min: -180, max: 180, step: 0.0001 },
                    { id: 'lat1', type: 'number', label: 'From latitude', value: '52.5', min: -90, max: 90, step: 0.0001 },
                    { id: 'lon2', type: 'number', label: 'To longitude', value: '-0.9', min: -180, max: 180, step: 0.0001 },
                    { id: 'lat2', type: 'number', label: 'To latitude', value: '53.1', min: -90, max: 90, step: 0.0001 }
                ],
                outId: 'out-distance'
            },
            {
                heading: '2 · A SITE BOUNDARY',
                lede: `Paste a closed boundary as <code>lon,lat</code> pairs separated by semicolons.
                   Area and perimeter are computed on the sphere, not on a flat projection — at UK
                   latitudes a planar approximation of a large site is wrong by enough to matter to a
                   land agreement.`,
                controls: [
                    { id: 'poly', type: 'text', label: 'Boundary (lon,lat; lon,lat; …)', value: '-1.40,52.50; -1.39,52.50; -1.39,52.51; -1.40,52.51' }
                ],
                outId: 'out-area',
                tableId: 'geo-table',
                tableHead: [{ label: 'Measure' }, { label: 'Value', right: true }],
                note: `A circle-cap area is given alongside for comparison: it is the area within a
                   radius on the sphere, which is what a "within X km" search actually covers and is
                   noticeably larger than πr² once the radius is big.`
            }
        ],
        script: `
function bind() { ['lon1','lat1','lon2','lat2','poly'].forEach(id => el(id).addEventListener('input', render)); }
function parsePoly(raw) {
  return raw.split(';').map(s => s.trim()).filter(Boolean).map(pair => {
    const [a, b] = pair.split(',').map(Number);
    if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error('cannot read point "' + pair + '"');
    return [a, b];
  });
}

function render() {
  try {
    const km = E.distanceKm(num('lon1'), num('lat1'), num('lon2'), num('lat2'));
    const brg = E.initialBearingDeg(num('lon1'), num('lat1'), num('lon2'), num('lat2'));
    el('out-distance').innerHTML =
      '<div class="figure"><span class="q">great-circle distance</span><span class="n">' +
      km.toFixed(3) + '</span><span class="u">km · bearing ' + brg.toFixed(1) + '°</span></div>' +
      '<p class="basis">Computed on a sphere of radius ' + E.EARTH_RADIUS_KM +
      ' km in (longitude, latitude) order. A straight line between two points is a measurement; ' +
      'it is not a route and it is not a cable length.</p>';
  } catch (err) { refuse('out-distance', err.message); }

  const tb = document.querySelector('#geo-table tbody');
  try {
    const pts = parsePoly(el('poly').value);
    if (pts.length < 3) throw new Error('a boundary needs at least three points');
    // polygonAreaKm2 and circleCapAreaKm2 return a whole set of units, not a
    // bare number: { areaKm2, areaM2, areaHa, areaAc, areaMi2, perimKm,
    // pitches }. Reading them as numbers threw, and the page said so rather
    // than showing a stale figure.
    const area = E.polygonAreaKm2(pts);
    const perimKm = E.polylinePerimeterKm(pts, true);
    const cap1 = E.circleCapAreaKm2(1);
    const cap50 = E.circleCapAreaKm2(50);
    el('out-area').innerHTML =
      '<div class="figure"><span class="q">site area</span><span class="n">' +
      area.areaHa.toFixed(2) + '</span><span class="u">hectares · ' +
      area.areaAc.toFixed(1) + ' acres · ' + area.areaKm2.toFixed(5) + ' km²</span></div>' +
      '<p class="basis">Spherical area of a closed boundary of ' + pts.length + ' points, on a ' +
      'sphere rather than a flat projection. At UK latitudes a planar approximation of a large ' +
      'site is wrong by enough to matter to a land agreement.</p>';
    tb.innerHTML = [
      ['Boundary points', pts.length],
      ['Area', area.areaKm2.toFixed(6) + ' km²'],
      ['Area', area.areaHa.toFixed(3) + ' ha'],
      ['Area', area.areaAc.toFixed(2) + ' acres'],
      ['Area, in football pitches', area.pitches.toFixed(1)],
      ['Perimeter (closed)', perimKm.toFixed(4) + ' km'],
      ['Within 1 km — spherical cap', cap1.areaKm2.toFixed(5) + ' km²'],
      ['Within 1 km — flat πr², for comparison', Math.PI.toFixed(5) + ' km²'],
      ['Within 50 km — spherical cap', cap50.areaKm2.toFixed(2) + ' km²'],
      ['Within 50 km — flat πr², for comparison', (Math.PI * 2500).toFixed(2) + ' km²'],
      ['Difference at 50 km', ((Math.PI * 2500 - cap50.areaKm2) / cap50.areaKm2 * 100).toFixed(3) + '%']
    ].map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td></tr>').join('');
  } catch (err) { refuse('out-area', err.message); tb.innerHTML = ''; }
}`
    },
    {
        stamp: '202609060305',
        slug: 'interconnectors',
        title: 'Interconnector Workbench',
        sub: 'An edge between two systems, priced — in text, and deliberately never drawn',
        feature: 'The GB interconnector fleet as text against electricity prices: which way a link flows at a stated spread, the energy it moves, the gross congestion rent, and the 10.3 GW that is observable separated from the 7.65 GW that is still a plan.',
        engineModule: 'interconnector-economics.js',
        engineCommit: 'a3a5e23',
        schema: 'ventus-grid-engine.interconnector-economics.v1',
        checks: 38,
        panels: [
            {
                heading: '1 · WHICH WAY, AND WHAT IT IS WORTH',
                lede: `An interconnector generates nothing. It moves what the exporting system's plant
                   produced, from wherever energy is cheaper to wherever it is dearer — so the
                   direction follows the price spread and nothing else. Set both prices. They travel
                   back with the answer, because a direction quoted without the prices that produced
                   it is an opinion.`,
                controls: [
                    { id: 'gbp', type: 'number', label: 'GB price (£/MWh)', value: '92', min: -500, max: 5000, step: 0.5 },
                    { id: 'nbp', type: 'number', label: 'Neighbour price (£/MWh)', value: '58', min: -500, max: 5000, step: 0.5 },
                    { id: 'cap', type: 'number', label: 'Link capacity (GW)', value: '1.4', min: 0.01, max: 10, step: 0.01 },
                    { id: 'util', type: 'range', label: 'Utilisation', value: '0.55', min: 0.05, max: 1.00, step: 0.01 },
                    { id: 'hrs', type: 'number', label: 'Hours', value: '8760', min: 1, max: 8784, step: 1 }
                ],
                outId: 'out-flow'
            },
            {
                heading: '2 · THE ENERGY AND THE RENT',
                lede: `Congestion rent is the energy moved multiplied by the price difference it is
                   moved across. It is the <strong>gross</strong> value of the arbitrage — before
                   losses, before outages, before operating cost and before any cap-and-floor
                   arrangement. It is not profit and nothing here calls it profit.`,
                controls: [],
                outId: 'out-rent',
                tableId: 'rent-table',
                tableHead: [{ label: 'Measure' }, { label: 'Value', right: true }]
            },
            {
                heading: '3 · THE FLEET, AND WHAT IS ACTUALLY OBSERVABLE',
                lede: `Sixteen links. Ten carry a BMRS code, so their flow appears in published data
                   and can be checked. Six have no code because they are not built — their capacity is
                   a plan. Adding the two numbers together is the easiest way to overstate the fleet,
                   so they are kept apart here.`,
                controls: [],
                outId: 'out-fleet',
                tableId: 'fleet-table',
                tableHead: [
                    { label: 'Link' }, { label: 'Country' }, { label: 'GW', right: true }, { label: 'Flow data', right: true }
                ],
                note: `<strong>No map.</strong> Subsea cable routes are licensed — TeleGeography is the
                   usual source and it is not ours to redraw — and neither NESO nor National Grid
                   publishes a route the estate could carry instead. So the estate does not draw these
                   cables, and the engine holds no coordinates at all; its proof asserts that no export
                   carries one. That is a licensing position stated where a reader will look, not a
                   missing feature for somebody to fill in later from a screenshot.`
            }
        ],
        script: `
// reference/interconnector_cables.csv in data-interconnectors, carried as text.
const FLEET = [
  { bmrsCode:'INTFR',   country:'France',           name:'IFA',                      capacityGw:2.0, status:'operational' },
  { bmrsCode:'INTIFA2', country:'France',           name:'IFA2',                     capacityGw:1.0, status:'operational' },
  { bmrsCode:'INTELEC', country:'France',           name:'ElecLink',                 capacityGw:1.0, status:'operational' },
  { bmrsCode:'INTNED',  country:'Netherlands',      name:'BritNed',                  capacityGw:1.0, status:'operational' },
  { bmrsCode:'INTNEM',  country:'Belgium',          name:'Nemo Link',                capacityGw:1.0, status:'operational' },
  { bmrsCode:'INTNSL',  country:'Norway',           name:'North Sea Link',           capacityGw:1.4, status:'operational' },
  { bmrsCode:'INTVKL',  country:'Denmark',          name:'Viking Link',              capacityGw:1.4, status:'operational' },
  { bmrsCode:'INTEW',   country:'Ireland',          name:'East West Interconnector', capacityGw:0.5, status:'operational' },
  { bmrsCode:'INTGRNL', country:'Ireland',          name:'Greenlink',                capacityGw:0.5, status:'operational' },
  { bmrsCode:'INTIRL',  country:'Northern Ireland', name:'Moyle',                    capacityGw:0.5, status:'operational' },
  { bmrsCode:'',        country:'Germany',          name:'NeuConnect',               capacityGw:1.4, status:'future' },
  { bmrsCode:'',        country:'Germany',          name:'Tarchon Energy',           capacityGw:1.4, status:'future' },
  { bmrsCode:'',        country:'Netherlands',      name:'LionLink',                 capacityGw:2.0, status:'future' },
  { bmrsCode:'',        country:'Belgium',          name:'Nautilus',                 capacityGw:1.4, status:'future' },
  { bmrsCode:'',        country:'Ireland',          name:'MaresConnect',             capacityGw:0.75, status:'future' },
  { bmrsCode:'',        country:'Northern Ireland', name:'LirIC',                    capacityGw:0.7, status:'future' }
];

function bind() { ['gbp','nbp','cap','util','hrs'].forEach(id => el(id).addEventListener('input', render)); }

function render() {
  el('util-val').textContent = num('util').toFixed(2);
  let dir = null;
  try {
    dir = E.flowDirection({ gbPriceGbpPerMwh: num('gbp'), neighbourPriceGbpPerMwh: num('nbp') });
    el('out-flow').innerHTML =
      '<div class="figure"><span class="q">commercial flow direction</span><span class="n" style="font-size:19px">' +
      dir.direction.toUpperCase() + '</span><span class="u">spread £' + dir.spreadGbpPerMwh.toFixed(2) + '/MWh</span></div>' +
      '<p class="basis">' + dir.basis + '</p>';
  } catch (err) { refuse('out-flow', err.message); }

  const rt = document.querySelector('#rent-table tbody');
  try {
    const energy = E.energyTransferredGwh({ capacityGw: num('cap'), hours: num('hrs'), utilisation: num('util') });
    if (!dir || dir.spreadGbpPerMwh === 0) {
      el('out-rent').innerHTML = '<p class="basis" style="border:0;padding:0;margin:0">' +
        'No spread, so no arbitrage value. The link may still flow for system reasons this engine does not model.</p>';
      rt.innerHTML = '<tr><td>Energy moved</td><td class="n">' + energy.value.toFixed(1) + ' GWh</td></tr>';
    } else {
      const rent = E.congestionRentGbp({ capacityGw: num('cap'), hours: num('hrs'),
        utilisation: num('util'), spreadGbpPerMwh: dir.spreadGbpPerMwh });
      el('out-rent').innerHTML =
        '<div class="figure"><span class="q">gross congestion rent</span><span class="n">£' +
        (rent.value/1e6).toFixed(2) + 'm</span></div><p class="basis">' + rent.basis + '</p>';
      const share = E.shareOfDemand({ transferGw: num('cap') * num('util'), gbDemandGw: 34.2 });
      rt.innerHTML = [
        ['Energy moved', energy.value.toLocaleString('en-GB',{maximumFractionDigits:0}) + ' GWh'],
        ['Spread', '£' + dir.spreadGbpPerMwh.toFixed(2) + '/MWh'],
        ['Gross rent', '£' + rent.value.toLocaleString('en-GB',{maximumFractionDigits:0})],
        ['Average transfer', (num('cap') * num('util')).toFixed(2) + ' GW'],
        ['Share of a 34.2 GW mean demand', share.percent.toFixed(1) + '%']
      ].map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td></tr>').join('');
    }
  } catch (err) { refuse('out-rent', err.message); rt.innerHTML = ''; }

  try {
    const f = E.fleetCapacity({ links: FLEET });
    el('out-fleet').innerHTML =
      '<div class="figure"><span class="q">fleet capacity</span><span class="n">' +
      f.value.toFixed(2) + '</span><span class="u">GW · ' + f.observableGw.toFixed(2) +
      ' observable, ' + f.unobservableGw.toFixed(2) + ' planned</span></div>' +
      '<p class="basis">' + f.basis + '</p>';
    document.querySelector('#fleet-table tbody').innerHTML = FLEET.map(l =>
      '<tr><td>' + l.name + '</td><td>' + l.country + '</td><td class="n">' + l.capacityGw.toFixed(2) +
      '</td><td class="n" style="color:' + (l.bmrsCode ? '#00ff88' : '#8e98a5') + '">' +
      (l.bmrsCode ? l.bmrsCode : 'no code yet') + '</td></tr>').join('');
  } catch (err) { refuse('out-fleet', err.message); }
}`
    },
    {
        stamp: '202609060309',
        slug: 'power-factor',
        title: 'Power Factor Workbench',
        sub: 'Capacity released without building anything',
        feature: 'Reactive power, apparent power, and the correction that moves a site from one power factor to another — with the connection capacity that releases, and the agreed capacity it may let you fit inside.',
        engineModule: 'power-factor.js',
        engineCommit: 'd1b459c',
        schema: 'ventus-grid-engine.power-factor.v1',
        checks: 33,
        panels: [
            {
                heading: '1 · THE LOAD AS THE PLANT SEES IT',
                lede: `A load does not present kilowatts to a transformer, it presents kilovolt-amperes.
                   Reactive power does no work, but it is carried by the same conductors and occupies
                   the same rating as the real power beside it. That is why a site can be well inside
                   its kW and outside its agreed capacity.`,
                controls: [
                    { id: 'kw', type: 'number', label: 'Real power (kW)', value: '1000', min: 1, max: 500000, step: 1 },
                    { id: 'pf0', type: 'range', label: 'Present power factor', value: '0.85', min: 0.50, max: 1.00, step: 0.01 }
                ],
                outId: 'out-now'
            },
            {
                heading: '2 · THE CORRECTION, AND WHAT IT GIVES BACK',
                lede: `Correction supplies the reactive power locally instead of drawing it across the
                   network. The site consumes exactly the same energy afterwards and occupies less of
                   its connection. <strong>Do not aim at unity:</strong> the last few percent costs
                   disproportionately, and a fixed bank sized for full load will over-correct at part
                   load — at which point the site can be charged for exporting reactive power instead.`,
                controls: [
                    { id: 'pf1', type: 'range', label: 'Target power factor', value: '0.98', min: 0.60, max: 1.00, step: 0.01 }
                ],
                outId: 'out-correction',
                tableId: 'pf-table',
                tableHead: [{ label: 'Measure' }, { label: 'Before', right: true }, { label: 'After', right: true }]
            },
            {
                heading: '3 · AGAINST YOUR AGREED CAPACITY',
                lede: `The figure in your connection agreement, which is commercial and is yours to
                   type in — nothing here infers it. Watch what happens to the same load at the two
                   power factors above.`,
                controls: [
                    { id: 'agreed', type: 'number', label: 'Agreed capacity (kVA)', value: '1100', min: 1, max: 500000, step: 1 }
                ],
                outId: 'out-agreed',
                note: `A ratio of two numbers you supplied. It is not a connection assessment: the
                   binding constraint may be the upstream circuit, the fault level at the busbar, or a
                   position in a queue, none of which appear in this arithmetic.`
            }
        ],
        script: `
function bind() { ['kw','pf0','pf1','agreed'].forEach(id => el(id).addEventListener('input', render)); }

function render() {
  el('pf0-val').textContent = num('pf0').toFixed(2);
  el('pf1-val').textContent = num('pf1').toFixed(2);
  const kw = num('kw'), pf0 = num('pf0'), pf1 = num('pf1');

  try {
    const s = E.apparentPowerKva({ kw, powerFactor: pf0 });
    const q = E.reactivePowerKvar({ kw, powerFactor: pf0 });
    el('out-now').innerHTML =
      '<div class="figure"><span class="q">as the plant sees it</span><span class="n">' +
      s.value.toFixed(1) + '</span><span class="u">kVA · ' + q.value.toFixed(1) + ' kVAr reactive</span></div>' +
      '<p class="basis">' + q.basis + '</p>';
  } catch (err) { refuse('out-now', err.message); }

  const tb = document.querySelector('#pf-table tbody');
  try {
    const c = E.correctionKvar({ kw, fromPowerFactor: pf0, toPowerFactor: pf1 });
    el('out-correction').innerHTML =
      '<div class="figure"><span class="q">correction required</span><span class="n">' +
      c.value.toFixed(1) + '</span><span class="u">kVAr · releases ' + c.capacityReleasedKva.toFixed(1) +
      ' kVA (' + c.capacityReleasedPercent.toFixed(1) + '%)</span></div>' +
      '<p class="basis">' + c.basis + '</p>';
    tb.innerHTML = [
      ['Power factor', pf0.toFixed(2), pf1.toFixed(2)],
      ['Real power', kw.toFixed(0) + ' kW', kw.toFixed(0) + ' kW'],
      ['Reactive power', c.reactiveBeforeKvar.toFixed(1) + ' kVAr', c.reactiveAfterKvar.toFixed(1) + ' kVAr'],
      ['Apparent power', c.apparentBeforeKva.toFixed(1) + ' kVA', c.apparentAfterKva.toFixed(1) + ' kVA']
    ].map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td><td class="n" style="color:#00ff88">' + r[2] + '</td></tr>').join('');
  } catch (err) {
    refuse('out-correction', err.message);
    tb.innerHTML = '';
  }

  try {
    const before = E.againstAgreedCapacity({ kw, powerFactor: pf0, agreedKva: num('agreed') });
    let after = null;
    try { after = E.againstAgreedCapacity({ kw, powerFactor: pf1, agreedKva: num('agreed') }); } catch (e) {}
    el('out-agreed').innerHTML =
      '<div class="figure"><span class="q">at ' + pf0.toFixed(2) + '</span><span class="n' +
      (before.exceeds ? ' over' : '') + '">' + before.percent.toFixed(1) + '%</span>' +
      (after ? '<span class="u">→ at ' + pf1.toFixed(2) + ': ' + after.percent.toFixed(1) + '%' +
        (before.exceeds && !after.exceeds ? ' — now inside it' : '') + '</span>' : '') +
      '</div><p class="basis">' + before.basis + '</p>';
  } catch (err) { refuse('out-agreed', err.message); }
}`
    },
    {
        stamp: '202609060313',
        slug: 'voltage-drop',
        title: 'Voltage Drop Workbench',
        sub: 'What a cable run costs in volts, and separately in watts',
        feature: 'Voltage drop along a run with the reactance term carried properly against power factor, the resistive and reactive parts shown apart, losses computed from resistance only, and annual energy at a stated loss load factor.',
        engineModule: 'voltage-drop.js',
        engineCommit: '2b0db38',
        schema: 'ventus-grid-engine.voltage-drop.v1',
        checks: 32,
        panels: [
            {
                heading: '1 · THE RUN',
                lede: `On a long run — a solar farm's internal collection, a depot's feeders, anything
                   in hundreds of metres — voltage drop chooses the conductor more often than current
                   does. Resistance and reactance are per kilometre and belong to the conductor you are
                   actually using: the engine carries none of its own, because a plausible-looking
                   default would be the most dangerous thing in it.`,
                controls: [
                    { id: 'amps', type: 'number', label: 'Current (A)', value: '200', min: 0.1, max: 20000, step: 1 },
                    { id: 'len', type: 'number', label: 'Run length (m)', value: '250', min: 1, max: 50000, step: 1 },
                    { id: 'r', type: 'number', label: 'Resistance (ohm/km)', value: '0.1', min: 0.0001, max: 20, step: 0.0001 },
                    { id: 'x', type: 'number', label: 'Reactance (ohm/km)', value: '0.08', min: 0, max: 20, step: 0.0001 },
                    { id: 'pf', type: 'range', label: 'Load power factor', value: '0.90', min: 0.50, max: 1.00, step: 0.01 },
                    { id: 'vn', type: 'number', label: 'Nominal voltage (V)', value: '400', min: 1, max: 500000, step: 1 }
                ],
                outId: 'out-drop'
            },
            {
                heading: '2 · WHERE THE VOLTS ACTUALLY GO',
                lede: `The reactance term is carried against sin(phi). At unity power factor it
                   contributes exactly nothing; at 0.8 it contributes 60% of X. On a large cable —
                   where X approaches and can exceed R — leaving it out under-states the drop badly,
                   and a poorly corrected industrial load is precisely where that lands. Move the
                   power factor slider and watch the reactive share move with it.`,
                controls: [],
                tableId: 'drop-table',
                tableHead: [{ label: 'Component' }, { label: 'Volts', right: true }, { label: 'Share', right: true }],
                note: `No permitted limit is asserted anywhere on this page. What drop is allowed
                   depends on the installation, on what sits at the far end, and on how much of the
                   allowance the rest of the system has already spent.`
            },
            {
                heading: '3 · HEAT, WHICH IS A DIFFERENT QUESTION',
                lede: `Losses are I²R and take <em>only</em> resistance — reactance stores and returns
                   energy rather than dissipating it. So a run can pass on volts and be expensive in
                   watts, or the reverse. Annual energy needs the <strong>loss</strong> load factor,
                   which is not the load factor: losses follow the square of current, so using the
                   load factor over-states them.`,
                controls: [
                    { id: 'llf', type: 'range', label: 'Loss load factor', value: '0.30', min: 0.02, max: 1.00, step: 0.01 }
                ],
                outId: 'out-loss',
                tableId: 'loss-table',
                tableHead: [{ label: 'Measure' }, { label: 'Three phase', right: true }, { label: 'Single phase', right: true }]
            }
        ],
        script: `
function bind() { ['amps','len','r','x','pf','vn','llf'].forEach(id => el(id).addEventListener('input', render)); }

function render() {
  el('pf-val').textContent = num('pf').toFixed(2);
  el('llf-val').textContent = num('llf').toFixed(2);
  const a = { currentA: num('amps'), lengthM: num('len'), resistanceOhmPerKm: num('r'),
              reactanceOhmPerKm: num('x'), powerFactor: num('pf') };

  const dt = document.querySelector('#drop-table tbody');
  try {
    const three = E.voltageDropVolts({ ...a, phases: 'three' });
    const single = E.voltageDropVolts({ ...a, phases: 'single' });
    const pc = E.dropPercent({ dropVolts: three.value, nominalVolts: num('vn') });
    el('out-drop').innerHTML =
      '<div class="figure"><span class="q">three-phase voltage drop</span><span class="n">' +
      three.value.toFixed(2) + '</span><span class="u">V · ' + pc.value.toFixed(3) + '% of ' + num('vn') + ' V</span></div>' +
      '<p class="basis">' + three.basis + '</p>';
    const tot = three.value;
    dt.innerHTML = [
      ['Resistive (R cos φ)', three.resistiveVolts.toFixed(2), ((three.resistiveVolts/tot)*100).toFixed(1) + '%'],
      ['Reactive (X sin φ)', three.reactiveVolts.toFixed(2), ((three.reactiveVolts/tot)*100).toFixed(1) + '%'],
      ['Total, three phase', tot.toFixed(2), pc.value.toFixed(3) + '% of nominal'],
      ['Same run, single phase', single.value.toFixed(2), (single.value/tot).toFixed(4) + '× the three-phase figure']
    ].map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td><td class="n">' + r[2] + '</td></tr>').join('');
  } catch (err) { refuse('out-drop', err.message); dt.innerHTML = ''; }

  const lt = document.querySelector('#loss-table tbody');
  try {
    const l3 = E.lossesWatts({ currentA: a.currentA, lengthM: a.lengthM, resistanceOhmPerKm: a.resistanceOhmPerKm, phases: 'three' });
    const l1 = E.lossesWatts({ currentA: a.currentA, lengthM: a.lengthM, resistanceOhmPerKm: a.resistanceOhmPerKm, phases: 'single' });
    const y3 = E.annualLossKwh({ peakLossWatts: l3.value, lossLoadFactor: num('llf') });
    const y1 = E.annualLossKwh({ peakLossWatts: l1.value, lossLoadFactor: num('llf') });
    el('out-loss').innerHTML =
      '<div class="figure"><span class="q">losses at peak, three phase</span><span class="n">' +
      (l3.value/1000).toFixed(3) + '</span><span class="u">kW · ' +
      y3.value.toLocaleString('en-GB',{maximumFractionDigits:0}) + ' kWh a year</span></div>' +
      '<p class="basis">' + l3.basis + '</p>';
    lt.innerHTML = [
      ['Conductors carrying current', l3.conductors, l1.conductors],
      ['Losses at peak', (l3.value/1000).toFixed(3) + ' kW', (l1.value/1000).toFixed(3) + ' kW'],
      ['Annual energy lost', y3.value.toLocaleString('en-GB',{maximumFractionDigits:0}) + ' kWh',
                             y1.value.toLocaleString('en-GB',{maximumFractionDigits:0}) + ' kWh']
    ].map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td><td class="n">' + r[2] + '</td></tr>').join('');
  } catch (err) { refuse('out-loss', err.message); lt.innerHTML = ''; }
}`
    },
    {
        stamp: '202609060316',
        slug: 'data-centre-connection',
        title: 'Data Centre Connection Workbench',
        sub: 'A large, concentrated, fast-moving load, sized against the substation it wants',
        feature: 'A data centre load taken end to end: IT load to MVA at a stated power factor, diversity across halls, annual energy at a load factor, and the whole thing assessed against a substation\'s N-1 firm capacity rather than its nameplate.',
        engineModule: ['firm-capacity.js', 'diversified-demand.js', 'electrification-demand.js'],
        engineCommit: '2b0db38',
        schema: [
            'ventus-grid-engine.firm-capacity.v1',
            'ventus-grid-engine.diversified-demand.v1',
            'ventus-grid-engine.electrification-demand.v1'
        ],
        checks: 93,
        panels: [
            {
                heading: '1 · THE LOAD, AS THE SUBSTATION SEES IT',
                lede: `Data centres are the load class changing GB distribution fastest: concentrated,
                   large, and moving quicker than networks are built. Government put GB colocation IT
                   capacity at about 1.6 GW in autumn 2024, two thirds of it in London, and the UK
                   Compute Roadmap now looks for at least 6 GW of AI-capable capacity by 2030. Enter
                   the IT load per hall and how many halls. Power factor matters here as everywhere:
                   the transformer carries the MVA, not the MW.`,
                controls: [
                    { id: 'halls', type: 'number', label: 'Number of halls', value: '8', min: 1, max: 500, step: 1 },
                    { id: 'permw', type: 'number', label: 'IT load per hall (MW)', value: '12.5', min: 0.1, max: 500, step: 0.1 },
                    { id: 'pue', type: 'number', label: 'PUE (total facility ÷ IT load)', value: '1.25', min: 1.0, max: 3.0, step: 0.01 },
                    { id: 'pf', type: 'range', label: 'Power factor', value: '0.95', min: 0.70, max: 1.00, step: 0.01 }
                ],
                outId: 'out-load'
            },
            {
                heading: '2 · DIVERSITY, WHICH IS SMALL HERE AND THAT IS THE POINT',
                lede: `Most load classes diversify heavily — a hundred homes never all draw at once.
                   A data centre barely diversifies at all: it is designed to run flat, which is
                   exactly why it is hard to connect. Set the coincidence factor you can actually
                   defend. At 1.0 there is no diversity and the site presents everything it has.`,
                controls: [
                    { id: 'coin', type: 'range', label: 'Coincidence across halls', value: '0.95', min: 0.30, max: 1.00, step: 0.01 },
                    { id: 'lf', type: 'range', label: 'Annual load factor', value: '0.90', min: 0.10, max: 1.00, step: 0.01 }
                ],
                outId: 'out-diversity',
                tableId: 'dc-table',
                tableHead: [{ label: 'Measure' }, { label: 'Value', right: true }]
            },
            {
                heading: '3 · AGAINST THE SUBSTATION IT WANTS',
                lede: `Now the question that decides the project. Not "is there a big substation
                   nearby" but "does this load still fit with the largest transformer out". Enter the
                   bank. Watch what happens to a site that looks comfortable on installed capacity.`,
                controls: [
                    { id: 'units', type: 'text', label: 'Transformer ratings (MVA, comma separated)', value: '90, 90, 90' }
                ],
                outId: 'out-firm',
                tableId: 'firm-table',
                tableHead: [{ label: 'Measure' }, { label: 'Value', right: true }, { label: 'Reading', right: true }],
                note: `A connection is not granted by arithmetic. The binding constraint is frequently
                   the upstream circuit, the fault level at the busbar, or a position in a queue —
                   Ofgem has reported demand connection applications rising from 41 GW to 125 GW, at
                   least 80 GW of it data centres, while warning that a significant portion may be
                   speculative. Nothing here distinguishes a financed project from an enquiry.`
            }
        ],
        script: `
function bind() { ['halls','permw','pue','pf','coin','lf','units'].forEach(id => el(id).addEventListener('input', render)); }
function parseUnits(raw) { return raw.split(',').map(s => s.trim()).filter(Boolean).map(Number); }

function render() {
  el('pf-val').textContent = num('pf').toFixed(2);
  el('coin-val').textContent = num('coin').toFixed(2);
  el('lf-val').textContent = num('lf').toFixed(2);

  const halls = Math.round(num('halls'));
  const itMw = num('permw');
  const facilityMwPerHall = itMw * num('pue');
  let diversifiedMw = null, mva = null;

  try {
    const admd = E.diversifiedDemandKw({ unitCount: halls, perUnitKw: facilityMwPerHall * 1000,
      coincidenceFactor: num('coin') });
    diversifiedMw = admd.value / 1000;
    mva = E.apparentPowerMva({ mw: diversifiedMw, powerFactor: num('pf') });
    el('out-load').innerHTML =
      '<div class="figure"><span class="q">demand at the connection</span><span class="n">' +
      mva.value.toFixed(1) + '</span><span class="u">MVA · ' + diversifiedMw.toFixed(1) + ' MW after diversity</span></div>' +
      '<p class="basis">' + mva.basis + '</p>';
  } catch (err) { refuse('out-load', err.message); }

  const dt = document.querySelector('#dc-table tbody');
  try {
    const unrestrictedMw = halls * facilityMwPerHall;
    // MW x hours is MWh, and MWh to TWh is a division by 1e6. The first
    // version multiplied by 1000 after that and printed 936 TWh for a
    // 125 MW site - three orders of magnitude out, and obvious only