GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / testcode / sandbox/202609060459/atlas/cartridges

Interconnector Economics and 3 more files

A JavaScript module in Ventus Grid Engine that works with interconnectors and cables. It is built from the finite step (`finite`), the positive step (`positive`) and the ratio step (`ratio`).

436 lines of JavaScript and Python from testcode, vedic-, ventus-grid-engine, in 4 files. Topic: Grid network and substations. Section 461 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. Substation Intelligence geodesy · testcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js lines 5330–5400
  2. VEDIC Faraday Orient Experiment storage · vedic- / tools/faraday_orient_experiment.mjs lines 1–82
  3. VEDIC Replay Faraday Orient storage · vedic- / tools/replay_faraday_orient.py lines 1–57
  4. Interconnector Economics energy-data · ventus-grid-engine / engine/interconnector-economics.js lines 1–226

Substation Intelligence

A JavaScript file in the cartridges folder of Testcode that maps elizabeth line and london underground, using haversine and SHA-256, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: 99% of its lines are the same as apps/substation-finder/Si/202609060537-substation-intelligence.js (code-generator), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9913 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
  • sha256 916bad1b531c94d9acd3bc54f6ed205b467b96e6c1d86beea47a7d66e2f51669
  • target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesytestcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js · lines 5330–5400 of 5400 · version 2026-09-06 04:59 (continued from section 453) · Not reached from any entry point (candidate for review) · pattern _zoneDrawRefreshEditor (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 230 functions or classes, including close, open, show, clearValues, validOutline. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json. Out: CSV file gridatlas-polygon-vertices.csv; downloaded file gridatlas-polygon-; downloaded file gridatlas-polygon-vertices.csv; downloaded file gridatlas-; downloaded file globalgrid2050-map-; browser storage (setItem); interactive map; canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It saves outline (`saveOutline`), reads outline (`readOutline`) and exports outline (`exportOutline`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 400 kV and 100 MVA. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/202609060459/atlas/cartridges · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
mentioned in Standalone (comment link)
Produces
close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on
Defines here
captureMapJpeg, finish, grab, pdfFileStamp, pad, wrapPdfText, savePdf, install
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js:5330-5400 · blob fd03f2ae502f2d404cb773df8858c2746ada6401 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
for (i = 0; i < offsets.length; i += 1) {
out += ('0000000000' + offsets[i]).slice(-10) + ' 00000 n \n';
}
out += 'trailer\n<< /Size ' + (objects.length + 1) + ' /Root 1 0 R >>\n'
+ 'startxref\n' + xref + '\n%%EOF\n';
var bytes = new Uint8Array(out.length);
for (i = 0; i < out.length; i += 1) bytes[i] = out.charCodeAt(i) & 0xff;
return { bytes: bytes, pageW: pageW, pageH: pageH };
}
function captureMapJpeg(doc, then) {
var map = mapHandle(),settled=false,timer;
var finish=function(url,canvas){if(settled)return;settled=true;clearTimeout(timer);if(map&&map.off&&grab)map.off('render',grab);then(url,canvas);};
timer=setTimeout(function(){finish(null,null);},10000);
var canvas = doc.querySelector('.maplibregl-canvas')
|| (map && map.getCanvas ? map.getCanvas() : null);
if (!canvas) { finish(null, null); return; }
var grab = function () {
var url = null;
try { url = canvas.toDataURL('image/jpeg', 0.92); } catch (_) { url = null; }
if (!url || url.indexOf('data:image/jpeg') !== 0 || looksBlank(canvas)) {
finish(null, canvas);
return;
}
finish(url, canvas);
};
if (map && map.once && map.triggerRepaint) {
map.once('render', grab);
map.triggerRepaint();
} else {
grab();
}
}
function pdfFileStamp() {
var d = new Date();
var pad = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getUTCFullYear() + pad(d.getUTCMonth() + 1) + pad(d.getUTCDate())
+ pad(d.getUTCHours()) + pad(d.getUTCMinutes());
}
function wrapPdfText(value,maxChars){
const text=String(value??'').replace(/\u00a9/g,'(c)').replace(/[\u00b7\u2013\u2014]/g,'-').replace(/[^\x20-\x7e]/g,' ').replace(/\s+/g,' ').trim();
const lines=[];let line='';
for(const word of text.split(' ')){let rest=word;while(rest.length>maxChars){if(line){lines.push(line);line='';}lines.push(rest.slice(0,maxChars));rest=rest.slice(maxChars);}if(!rest)continue;if(line.length+rest.length+1>maxChars){lines.push(line);line=rest;}else line+=(line?' ':'')+rest;}
if(line)lines.push(line);return lines;
}
function savePdf(doc,button){
if(button.disabled)return;button.disabled=true;button.textContent='Building map PDF...';
captureMapJpeg(doc,function(data,canvas){
button.disabled=false;
if(!data){button.textContent='Map capture unavailable - redraw and try again';return;}
try{
const binary=atob(data.slice(data.indexOf(',')+1));
const built=buildMapPdf(binary,canvas.width,canvas.height,'GlobalGrid2050 - Grid Atlas map',attributionText(doc),generationText()+' - '+new Date().toISOString().slice(0,16).replace('T',' ')+' UTC');
const url=URL.createObjectURL(new Blob([built.bytes],{type:'application/pdf'})),anchor=doc.createElement('a');
anchor.href=url;anchor.download='globalgrid2050-map-'+pdfFileStamp()+'.pdf';doc.body.append(anchor);anchor.click();anchor.remove();
setTimeout(()=>URL.revokeObjectURL(url),30000);button.textContent='PDF saved - '+built.pageW+' x '+built.pageH+' native pixels';
}catch(error){button.textContent='PDF could not be created: '+error.message;}
});
}
function install(){
if(document.getElementById('gridatlas-export-pdf'))return true;
const sibling=document.getElementById('gridatlas-export-image')||[...document.querySelectorAll('#gridatlas-menu-bar button[data-gm-export]')].find(button=>/save an image/i.test(button.textContent));if(!sibling)return false;
const button=document.createElement('button');button.id='gridatlas-export-pdf';button.type='button';button.dataset.gmExport='pdf';
button.textContent='Save map as PDF';button.title='Download the visible map at native resolution, with source credits and release identity';button.style.minHeight='44px';button.setAttribute('aria-live','polite');
button.addEventListener('click',()=>savePdf(document,button));sibling.before(button);return true;
}
registry.mapPdf=Object.freeze({schema:'gridatlas.map-pdf.v1',buildMapPdf,wrapPdfText,install});
if(typeof document!=='undefined'&&!install()){
const observer=new MutationObserver(()=>{if(install())observer.disconnect();});observer.observe(document.documentElement,{childList:true,subtree:true});
setTimeout(()=>observer.disconnect(),120000);
}
})();

VEDIC Faraday Orient Experiment

A JavaScript module in the tools folder. It is built from the point step (`point`), the run step (`run`) and the experiment step (`experiment`).

storagevedic- / tools/faraday_orient_experiment.mjs · lines 1–82 of 82 · Not reached from any entry point (candidate for review) · pattern input (shared by 7 files)

What it does
Defines point, run, experiment, input, confirm. Uses libraries node:assert/strict, node:child_process, node:fs, node:os, node:path. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiment'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file coords.json. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
Candidate apparatus for Faraday's existing numbered runner.
Why it matters
No other file in the estate was found to import it.
Application
vedic- · tools · JavaScript module
Uses
node:assert/strict, node:child_process, node:fs, node:os, node:path
Used by
none found
Produces
experiment
Defines here
point, run, experiment, input, confirm
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/faraday_orient_experiment.mjs:1-82 · blob ea585ef5ffba4d4940a8885ca3d8244527aa0205 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: ai_agent · canonical: unreached_review
// Candidate apparatus for Faraday's existing numbered runner.
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const requirements = [
  'VEDIC_PYTHON', 'VEDIC_COMPILER', 'VEDIC_FACTORY_REPO',
  'VEDIC_ORIENT_ARCHIVE', 'VEDIC_ORIENT_BUILD_RECEIPT',
];

const point = (longitude, latitude) => ({ longitude, latitude });

function run(phrase, values, file) {
  writeFileSync(file, JSON.stringify(values));
  const result = spawnSync(process.env.VEDIC_PYTHON, [
    process.env.VEDIC_COMPILER, phrase, '--input', file,
    '--factory-repo', process.env.VEDIC_FACTORY_REPO,
    '--archive', process.env.VEDIC_ORIENT_ARCHIVE,
    '--build-receipt', process.env.VEDIC_ORIENT_BUILD_RECEIPT,
  ], { encoding: 'utf8', timeout: 40_000 });
  if (result.error) throw result.error;
  return { exit: result.status, receipt: JSON.parse(result.stdout) };
}

export default async function experiment() {
  for (const name of requirements) assert.ok(process.env[name], name);
  const root = mkdtempSync(join(tmpdir(), 'faraday-vedic-orient-'));
  const request = join(root, 'coords.json');
  const input = (a, b, unit = 'degrees') => ({
    crs: 'WGS84', unit, point_a: a, point_b: b,
  });
  const observed = {};
  const failure = [];
  const confirm = (name, actual, predicate) => {
    observed[name] = actual;
    if (!predicate(actual)) failure.push(name);
  };
  try {
    for (const [name, phrase, a, b, degrees, direction] of [
      ['equator', 'ORIENT', point(0, 0), point(1, 0), 1, 90],
      ['antimeridian', 'measure distance and bearing', point(179, 0), point(-179, 0), 2, 90],
      ['meridian', 'orient', point(20, 10), point(20, 13), 3, 0],
    ]) {
      const result = run(phrase, input(a, b), request);
      const output = result.receipt.package_execution?.pattern.output;
      const expected = { distance_km: 6378.137 * degrees * (Math.PI / 180), initial_bearing_deg: direction };
      confirm(name, {
        exit: result.exit, state: result.receipt.state, command_id: result.receipt.plan?.command_id,
        components: result.receipt.plan?.components, output, expected,
        pattern_sha256: result.receipt.package_execution?.pattern_sha256,
      }, (x) => x.exit === 0 && x.state === 'EXECUTED_PRIVATE_PACKAGE'
        && x.command_id === 'GG2050-VEDIC-000006'
        && x.components.join(',') === 'GG2050-VEDIC-000001,GG2050-VEDIC-000005'
        && Math.abs(x.output.distance_km - expected.distance_km) <= 1e-9
        && Math.abs(x.output.initial_bearing_deg - direction) <= 1e-9);
    }
    for (const [name, phrase, data, reason, packageReason] of [
      ['coincident', 'ORIENT', input(point(3, 4), point(3, 4)), 'PACKAGE_REFUSED', 'UPSTREAM_RESULT_REFUSED'],
      ['antipodal', 'ORIENT', input(point(0, 0), point(180, 0)), 'PACKAGE_REFUSED', 'UPSTREAM_RESULT_REFUSED'],
      ['polar_origin', 'ORIENT', input(point(0, 90), point(1, 20)), 'PACKAGE_REFUSED', 'UPSTREAM_RESULT_REFUSED'],
      ['wrong_units', 'ORIENT', input(point(0, 0), point(1, 0), 'radians'), 'PACKAGE_REFUSED', 'INPUT_UNITS'],
      ['missing_coordinate', 'ORIENT', input(point(0, 0), { longitude: 1 }), 'PACKAGE_REFUSED', 'FIELDS'],
      ['ambiguous_term', 'AREA', {}, 'AMBIGUOUS_COMMAND'],
      ['unadmitted', 'CHECK POWER CAP', {}, 'PACKAGE_NOT_ADMITTED'],
    ]) {
      const result = run(phrase, data, request);
      confirm(name, result, x => x.exit === 2 && x.receipt.state === 'REFUSED'
        && x.receipt.reason === reason
        && x.receipt.package_reason === packageReason);
    }
  } finally {
    rmSync(root, { recursive: true });
  }
  return {
    did: 'Fired the existing VEDIC ORIENT package on three independently calculable spherical cases and seven refusals.',
    observed: JSON.stringify({ cases: observed, failed: failure }),
    shows: 'One existing command drives two canonical geodesy operations through the byte-pinned package. The cases exercise its declared units and scope.',
    result: failure.length ? 'REFUTED' : 'CONFIRMED',
  };
}

VEDIC Replay Faraday Orient

A Python command-line tool in the tools folder covering build receipt.

storagevedic- / tools/replay_faraday_orient.py · lines 1–57 of 57 · Entry point

What it does
Defines main. Uses libraries argparse, os, pathlib, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file build-receipt.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Run the VEDIC ORIENT apparatus using the existing Faraday experiment runner.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
vedic- · tools · Python CLI
Uses
VEDIC Semantic Compiler (import), argparse, os, pathlib, subprocess, sys
Used by
none found
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/replay_faraday_orient.py:1-57 · blob 52cbe418df207a0c3ba749a39ab7f9fd01a33786 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Run the VEDIC ORIENT apparatus using the existing Faraday experiment runner."""
import argparse
import os
from pathlib import Path
import subprocess
import sys

from semantic_compiler import ROOT, Refusal, need, pinned_git_file, strict_json

FARADAY = "e439b450f37a8c124fa4a0cb38159ae0dc337062"
EXPERIMENT = 101
FILES = {
    "run.mjs": "b0d63f8350f081079f0df7508a120f512ff845c143585c758ae42fb1d1db5be3",
    "INDEX.tsv": "25bd06cc1a904df3dcd4c63d9e7a43f86558b5b7920989cb46f34ddf4e0fd0d2",
}
CANDIDATE_ROW = (
    "101\tVEDIC packaged geodesy\tDo the known spherical outputs and bounded refusals follow through ORIENT?"
    "\tExact private package via the VEDIC compiler\tAny mismatched output, scope or refusal"
)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("faraday", "factory-repo", "private-package", "out"):
        parser.add_argument("--" + name, required=True, type=Path)
    args = parser.parse_args()
    try:
        source = {name: pinned_git_file(args.faraday, FARADAY, f"experiments/{name}", digest)
                  for name, digest in FILES.items()}
        index = source["INDEX.tsv"].decode("utf-8").rstrip("\r\n")
        numbers = [int(line.split("\t", 1)[0]) for line in index.splitlines()[1:]]
        need(numbers == list(range(1, EXPERIMENT)), "FARADAY_INDEX_CHANGED")
        args.out.mkdir()
        for name, raw in source.items():
            (args.out / name).write_bytes(raw)
        (args.out / "INDEX.tsv").write_bytes((index + "\n" + CANDIDATE_ROW + "\n").encode("utf-8"))
        (args.out / f"e{EXPERIMENT:03}.mjs").write_bytes(
            (ROOT / "tools/faraday_orient_experiment.mjs").read_bytes())
        package = args.private_package.resolve()
        env = {**os.environ, "VEDIC_PYTHON": sys.executable,
               "VEDIC_COMPILER": str(ROOT / "tools/semantic_compiler.py"),
               "VEDIC_FACTORY_REPO": str(args.factory_repo.resolve()),
               "VEDIC_ORIENT_ARCHIVE": str(package / "orient.zip"),
               "VEDIC_ORIENT_BUILD_RECEIPT": str(package / "build-receipt.json")}
        outcome = subprocess.run(["node", "--no-addons", "run.mjs", str(EXPERIMENT)],
                                 cwd=args.out, env=env, check=False, timeout=120)
        receipt = strict_json((args.out / f"results/e{EXPERIMENT:03}.json").read_bytes())
        need(outcome.returncode == 0 and receipt["result"] == "CONFIRMED", "FARADAY_NOT_CONFIRMED")
    except (Refusal, OSError, subprocess.SubprocessError) as exc:
        print(str(exc), file=sys.stderr)
        return 1
    print(f"Confirmed staged Faraday candidate {EXPERIMENT} from {FARADAY}")
    return 0


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

Interconnector Economics

A JavaScript module in Ventus Grid Engine that works with interconnectors and cables. It is built from the finite step (`finite`), the positive step (`positive`) and the ratio step (`ratio`).

energy-dataventus-grid-engine / engine/interconnector-economics.js · lines 1–226 of 226 · pattern ratio (shared by 8 files)

What it does
It calculates interconnectors and cables. Defines 8 functions or classes, including finite, positive, ratio, flowDirection, energyTransferredGwh.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'interconnector'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: interconnectors, cables.
Downstream impact
Used directly by 3 files: Grid Engine — Interconnectors Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060305-interconnectors/); Interconnector Economics Proof (ventus-grid-engine); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 4 other entry points, including Homepage V090 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v090.html); Homepage V091 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v091.html); Homepage V093 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v093.html).
What it achieves
What an interconnector does, and what a price difference across it is worth — in text, deliberately never as a drawing. Its code works with 2 GW.
Why it matters
Loaded by the Interconnectors page in GlobalGrid2050 at https://globalgrid2050.com/grid_engine/202609060305-interconnectors/. Also imported by Interconnector Economics Proof and Build Graph.
Application
ventus-grid-engine · engine · JavaScript module
Uses
none found
Used by
linked from Grid Engine — Interconnectors Page (link), imported by Interconnector Economics Proof (import), named by URL in Build Graph (estate URL)
Produces
schema, flowDirection, energyTransferredGwh, congestionRentGbp, fleetCapacity, shareOfDemand, NOT_COMPUTED
Defines here
finite, positive, ratio, flowDirection, energyTransferredGwh, congestionRentGbp, fleetCapacity, shareOfDemand
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/interconnector-economics.js:1-226 · blob 5415f5cf37d97d3d7edfee86cc5ac6f8eae579f3 · 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
/**
 * Module: interconnector-economics
 *
 * APPLIED ENGINEERING. What an interconnector does, and what a price
 * difference across it is worth — in text, deliberately never as a drawing.
 *
 * WHY THERE IS NO GEOMETRY HERE, AND WHY THAT IS A DECISION NOT A GAP.
 * Subsea cable routes are, in practice, licensed data. TeleGeography's route
 * geometry 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 this
 * module holds no coordinates, exports no geometry, and the estate's map does
 * not draw these cables. That is a licensing position, stated once, in the
 * place a reader will look — not a missing feature somebody helpfully adds
 * later from a screenshot. If a route is ever published under terms that allow
 * it, this refusal is the thing to change, deliberately.
 *
 * Everything an interconnector actually needs for analysis — the link, its
 * countries, its capacity, its status, its BMRS code, and what the price
 * spread across it means — is text and numbers, and text and numbers are here.
 *
 * WHAT AN INTERCONNECTOR IS, ELECTRICALLY AND ECONOMICALLY.
 * It is an edge between two systems, not a generator. It produces nothing. It
 * moves energy from wherever it is cheaper to wherever it is dearer, because
 * that is what the market instructs it to do, and the direction therefore
 * follows the price spread rather than any physical preference. A link at full
 * capacity is not "generating" — it is importing, and the exporting system's
 * plant is doing the generating.
 *
 * CONGESTION RENT, AND WHY IT IS THE HONEST NUMBER.
 * The economic value created by a link over a period is the energy it moves
 * multiplied by the price difference it moves that energy across:
 *
 *     rent = capacity x utilisation x hours x |spread|
 *
 * That is the gross value of the arbitrage, and it is what an interconnector
 * earns before costs, before losses and before any capacity-market or cap-and-
 * floor arrangement. It is not profit and this module does not call it profit.
 *
 * WHAT IT REFUSES.
 * It does not forecast a price, and it will not take a forecast as an input
 * dressed up as a fact — every price is supplied by the caller and travels back
 * with the answer so nobody can quote the output without the assumption. It
 * does not model losses, availability outages, cap-and-floor regimes, or the
 * flow the market actually schedules, which follows day-ahead coupling and not
 * a single spread. And it draws nothing.
 *
 * Depends on: nothing. Pure arithmetic over caller-supplied prices and a
 * caller-supplied link list.
 *
 * Schema: ventus-grid-engine.interconnector-economics.v1
 */

export const schema = 'ventus-grid-engine.interconnector-economics.v1';

function finite(name, v) {
    if (typeof v !== 'number' || !Number.isFinite(v)) {
        throw new TypeError(`${name} must be a finite number, received ${v === null ? 'null' : typeof v}`);
    }
    return v;
}

function positive(name, v) {
    finite(name, v);
    if (v <= 0) throw new RangeError(`${name} must be greater than zero, received ${v}`);
    return v;
}

function ratio(name, v) {
    positive(name, v);
    if (v > 1) throw new RangeError(
        `${name} must be a fraction in (0, 1], received ${v}. A percentage such as 70 must be passed as 0.7.`);
    return v;
}

/**
 * Which way the energy goes, from two prices the caller states.
 *
 * Both prices travel back with the answer. A direction without the prices that
 * produced it is an opinion.
 */
export function flowDirection({ gbPriceGbpPerMwh, neighbourPriceGbpPerMwh }) {
    finite('gbPriceGbpPerMwh', gbPriceGbpPerMwh);
    finite('neighbourPriceGbpPerMwh', neighbourPriceGbpPerMwh);
    const spread = gbPriceGbpPerMwh - neighbourPriceGbpPerMwh;
    const direction = spread > 0 ? 'import to GB' : spread < 0 ? 'export from GB' : 'no commercial incentive';
    return {
        schema,
        quantity: 'commercial_flow_direction',
        direction,
        spreadGbpPerMwh: Math.abs(spread),
        signedSpreadGbpPerMwh: spread,
        from: { gbPriceGbpPerMwh, neighbourPriceGbpPerMwh },
        basis: spread === 0
            ? `Both systems are at £${gbPriceGbpPerMwh}/MWh. With no spread there is no commercial ` +
              `reason to flow either way, though a link may still flow for system reasons this ` +
              `module does not model.`
            : `GB at £${gbPriceGbpPerMwh}/MWh against £${neighbourPriceGbpPerMwh}/MWh gives a spread ` +
              `of £${Math.abs(spread).toFixed(2)}/MWh, so energy moves ${direction === 'import to GB' ? 'INTO' : 'OUT OF'} ` +
              `GB — from the cheaper system to the dearer one. An interconnector generates nothing; ` +
              `it moves what the exporting system's plant produced. Real scheduling follows day-ahead ` +
              `market coupling, not a single spread.`
    };
}

/**
 * Energy moved over a period at a stated utilisation.
 */
export function energyTransferredGwh({ capacityGw, hours, utilisation }) {
    positive('capacityGw', capacityGw);
    positive('hours', hours);
    ratio('utilisation', utilisation);
    return {
        schema,
        quantity: 'energy_transferred_gwh',
        value: capacityGw * hours * utilisation,
        unit: 'GWh',
        from: { capacityGw, hours, utilisation },
        basis:
            `${capacityGw} GW at ${(utilisation * 100).toFixed(0)}% utilisation over ${hours} hours. ` +
            `Utilisation is stated by the caller, never assumed: a link's actual load factor depends ` +
            `on the spread persisting, on availability, and on what the coupled markets schedule.`
    };
}

/**
 * Gross congestion rent: the value of moving energy across a price difference.
 *
 * Before losses, before costs, before any cap-and-floor arrangement. Not
 * profit, and this module will not call it profit.
 */
export function congestionRentGbp({ capacityGw, hours, utilisation, spreadGbpPerMwh }) {
    const energy = energyTransferredGwh({ capacityGw, hours, utilisation });
    positive('spreadGbpPerMwh', spreadGbpPerMwh);
    const mwh = energy.value * 1000;
    return {
        schema,
        quantity: 'gross_congestion_rent_gbp',
        value: mwh * spreadGbpPerMwh,
        unit: 'GBP',
        energyGwh: energy.value,
        from: { capacityGw, hours, utilisation, spreadGbpPerMwh },
        basis:
            `${energy.value.toFixed(1)} GWh moved across a £${spreadGbpPerMwh}/MWh spread. This is the ` +
            `GROSS value of the arbitrage: before transmission losses, before availability outages, ` +
            `before operating cost, and before any cap-and-floor regime. It is not profit and nothing ` +
            `here calls it profit.`
    };
}

/**
 * Capacity totals across a fleet of links, split by status.
 *
 * The distinction that matters: a link with a BMRS code is wired and its flow
 * is observable; one without a code is a project, and its capacity is a plan.
 */
export function fleetCapacity({ links }) {
    if (!Array.isArray(links) || links.length === 0) {
        throw new TypeError('links must be a non-empty array');
    }
    const byStatus = {};
    const byCountry = {};
    let observable = 0, planned = 0;
    links.forEach((l, i) => {
        positive(`links[${i}].capacityGw`, l.capacityGw);
        if (typeof l.status !== 'string' || !l.status) {
            throw new TypeError(`links[${i}].status must be a non-empty string`);
        }
        byStatus[l.status] = (byStatus[l.status] || 0) + l.capacityGw;
        byCountry[l.country] = (byCountry[l.country] || 0) + l.capacityGw;
        if (l.bmrsCode) observable += l.capacityGw; else planned += l.capacityGw;
    });
    const total = links.reduce((a, b) => a + b.capacityGw, 0);
    return {
        schema,
        quantity: 'fleet_capacity_gw',
        value: total,
        unit: 'GW',
        byStatus,
        byCountry,
        observableGw: observable,
        unobservableGw: planned,
        linkCount: links.length,
        basis:
            `${links.length} links totalling ${total.toFixed(2)} GW. ${observable.toFixed(2)} GW carries ` +
            `a BMRS code and its flow is therefore observable in published data; ${planned.toFixed(2)} GW ` +
            `does not, and its capacity is a plan rather than a measurement. Capacity is not energy: a ` +
            `link at 2 GW moves nothing when the spread is against it.`
    };
}

/**
 * What a link's transfer is worth as a share of a stated GB demand.
 *
 * Deliberately expressed against a demand the caller supplies, because "X% of
 * GB demand" is meaningless without saying which demand and when.
 */
export function shareOfDemand({ transferGw, gbDemandGw }) {
    positive('transferGw', transferGw);
    positive('gbDemandGw', gbDemandGw);
    return {
        schema,
        quantity: 'share_of_stated_demand',
        value: transferGw / gbDemandGw,
        unit: 'dimensionless',
        percent: (transferGw / gbDemandGw) * 100,
        from: { transferGw, gbDemandGw },
        basis:
            `${transferGw} GW against a stated GB demand of ${gbDemandGw} GW is ` +
            `${((transferGw / gbDemandGw) * 100).toFixed(1)}%. The demand figure is yours: a share of ` +
            `"GB demand" means nothing without saying which demand and at what moment, and the same ` +
            `link is a very different share of a summer minimum and a winter peak.`
    };
}

export const NOT_COMPUTED = Object.freeze({
    cableGeometry:
        'This module holds no route geometry and the estate does not draw subsea cables. Route data is 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. This is a licensing position, not a missing feature. If a route is ever published under terms that permit it, change this refusal delibe  … [line shortened here: 456 characters; full line on GitHub]
    priceForecast:
        'No price is forecast here. Every price is supplied by the caller and travels back with the answer, so an output cannot be quoted without the assumption that produced it.',
    scheduledFlow:
        'What actually flows follows day-ahead market coupling, intraday trading, availability and system constraints — not a single price spread. This arithmetic describes the incentive, not the schedule.',
    profit:
        'Congestion rent is gross value before losses, outages, operating cost and any cap-and-floor regime. It is not profit and is never labelled as profit here.',
    lossesAndAvailability:
        'Converter and cable losses, planned outages and forced outages all reduce delivered energy. They are the operator\'s figures for a specific link and are not modelled.'
});