GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / tools/interconnectors

Fetch Far End Converters and 1 more file

A Python command-line tool in the interconnectors folder of GridAtlas that fetches generation interconnector, grid substations, interconnector endpoints and overpass converters, using EPSG:4326 from OpenStreetMap (Overpass).

557 lines of Python and JavaScript from gridatlas, in 2 files. Topic: Grid network and substations. Section 445 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. Fetch Far End Converters geodesy · gridatlas / tools/interconnectors/fetch_far_end_converters.py lines 1–377
  2. Interconnector Module energy-data · gridatlas / tools/interconnectors/interconnector-module.js lines 1–180

Fetch Far End Converters

A Python command-line tool in the interconnectors folder of GridAtlas that fetches generation interconnector, grid substations, interconnector endpoints and overpass converters, using EPSG:4326 from OpenStreetMap (Overpass).

geodesygridatlas / tools/interconnectors/fetch_far_end_converters.py · lines 1–377 of 377 · Entry point · pattern haversine_km (shared by 7 files)

What it does
It fetches generation interconnector, grid substations, interconnector endpoints and overpass converters. Defines haversine_km, fetch_converters, load_gb_substations, load_flows, main. Uses libraries __future__, argparse, datetime, json, math. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'interconnectors'): 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: data source: OpenStreetMap (Overpass); JSON file generation_interconnector_index.json; GeoJSON file grid_substations.geojson; JSON file interconnector-endpoints.json; JSON file .overpass-converters.json; GeoJSON file interconnectors.geojson; command-line arguments. Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It fetches converters (`fetch_converters`), loads GB substations (`load_gb_substations`) and loads flows (`load_flows`). Find the far-end converter station for each GB interconnector. It accepts `--root`, `--out` and `--cache`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/interconnectors · Python CLI
Uses
__future__, argparse, datetime, json, math, re, sys, urllib.parse
Used by
none found
Produces
haversine_km, fetch_converters, load_gb_substations, load_flows, main
Defines here
haversine_km, fetch_converters, load_gb_substations, load_flows, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/interconnectors/fetch_far_end_converters.py:1-377 · blob f9fb427696f0ffde8d07b360af914cc5138e7236 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Find the far-end converter station for each GB interconnector.

The estate already holds the GB end of every link: our own substation data names
Sellindge Converter Station, Grain Static Inverter Plant and Auchencrosh Static
Inverter Plant outright, and the rest land at named substations. What it has
never held is the other end, so no link could be drawn.

HVDC converters are tagged `power=converter` in OpenStreetMap, which makes the
far ends queryable rather than guessable. This fetches them across north-west
Europe, matches them to the links by name, pairs them with the GB end, and emits
a straight line for each.

A straight line between converter stations is the intended output, not a
stopgap. It states the separation exactly and is honest so long as it is labelled
a straight line rather than a cable route. Where a true cable length is known the
report carries the route factor beside it: BritNed is ~245 km of submarine cable
against its own straight line, quoted in BritNed v ABB [2018] EWHC 2616 (Ch).

Nothing here is asserted from memory. A link with no OSM match is reported as
unmatched rather than filled in.

Usage:
    python fetch_far_end_converters.py --out atlas/data/interconnector-endpoints.json
    python fetch_far_end_converters.py --offline   # reuse a cached Overpass response
"""

from __future__ import annotations

import argparse
import datetime as _dt
import json
import math
import re
import sys
import urllib.parse
import urllib.request
from pathlib import Path

OVERPASS = "https://overpass-api.de/api/interpreter"
BBOX = (48.0, -11.5, 62.5, 13.0)  # south, west, north, east — Ireland to Denmark
USER_AGENT = "GridAtlas-CI/1.0 (interconnector endpoint reconciliation)"

# Each link: the GB substation to look for in our own data, and the names its
# far-end converter answers to in OSM. Aliases are needed because operators and
# mappers do not agree: "HVDC Britned", "Konti-Skan", "Cross-Skagerrak".
LINKS = [
    {"link": "IFA",              "bmrs": "INTFR",   "gb": "sellindge",        "far_aliases": ["ifa", "les mandarins", "bonningues"]},
    {"link": "IFA2",             "bmrs": "INTIFA2", "gb": "chilling",         "far_aliases": ["ifa2", "ifa 2", "tourbe"]},
    {"link": "ElecLink",         "bmrs": "INTELEC", "gb": "sellindge",        "far_aliases": ["eleclink", "elec link"]},
    {"link": "BritNed",          "bmrs": "INTNED",  "gb": "grain static",     "far_aliases": ["britned", "brit ned", "maasvlakte"]},
    {"link": "Nemo Link",        "bmrs": "INTNEM",  "gb": "richborough",      "far_aliases": ["nemo", "herdersbrug", "zeebrugge"]},
    {"link": "North Sea Link",   "bmrs": "INTNSL",  "gb": "blyth substation", "far_aliases": ["north sea link", "nsl", "kvilldal"]},
    {"link": "Viking Link",      "bmrs": "INTVKL",  "gb": "bicker fen",       "far_aliases": ["viking link", "revsing"]},
    {"link": "East West",        "bmrs": "INTEW",   "gb": "deeside",          "far_aliases": ["east west interconnector", "ewic", "woodland"]},
    {"link": "Greenlink",        "bmrs": "INTGRNL", "gb": "pembroke",         "far_aliases": ["greenlink", "great island"]},
    {"link": "Moyle",            "bmrs": "INTIRL",  "gb": "auchencrosh",      "far_aliases": ["moyle", "ballycronan"]},
]

# Cable lengths quoted in court or by the operator, for the route factor.
KNOWN_CABLE_KM = {
    "BritNed": {
        "submarine_km": 245,
        "land_km": 9,
        "source": "BritNed Development Ltd v ABB AB [2018] EWHC 2616 (Ch)",
    }
}

# The estate already tracks what flows through these links. uk_energy_tracking_v6
# carries import/export MWh per link per year, keyed by the same BMRS code this
# tool keys on, with its sign convention stated in the file: imports positive,
# exports negative. Joining on that code puts the electricity and the geometry
# in one artefact instead of two half-answers.
FLOW_INDEX = [
    "globalgrid2050/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_index.json",
    "../globalgrid2050/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_index.json",
]

GB_SUBSTATIONS = [
    "gridatlas/atlas/releases/202608292311-atlas-v9/data/grid_substations.geojson",
    "atlas/releases/202608292311-atlas-v9/data/grid_substations.geojson",
]


def haversine_km(lon1: float, lat1: float, lon2: float, lat2: float) -> float:
    """Great-circle distance on the estate's declared WGS84 sphere."""
    radius = 6378.137
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dp = math.radians(lat2 - lat1)
    dl = math.radians(lon2 - lon1)
    a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * radius * math.asin(math.sqrt(a))


def fetch_converters(cache: Path, offline: bool) -> list[dict]:
    if offline or cache.exists():
        if cache.exists():
            payload = json.loads(cache.read_text(encoding="utf-8"))
            print(f"  using cached Overpass response ({cache.name})")
            return payload.get("elements") or []
        raise SystemExit(f"--offline given but no cache at {cache}")

    south, west, north, east = BBOX
    query = f"""[out:json][timeout:180];
(
  node["power"="converter"]({south},{west},{north},{east});
  way["power"="converter"]({south},{west},{north},{east});
  relation["power"="converter"]({south},{west},{north},{east});
);
out center tags;"""
    request = urllib.request.Request(
        OVERPASS,
        data=urllib.parse.urlencode({"data": query}).encode(),
        headers={"User-Agent": USER_AGENT},
    )
    print("  querying Overpass ...")
    with urllib.request.urlopen(request, timeout=240) as response:
        payload = json.loads(response.read().decode("utf-8"))
    cache.parent.mkdir(parents=True, exist_ok=True)
    cache.write_text(json.dumps(payload), encoding="utf-8")
    print(f"  cached to {cache.name}")
    return payload.get("elements") or []


def load_gb_substations(root: Path) -> list[dict]:
    for candidate in GB_SUBSTATIONS:
        path = root / candidate
        if not path.is_file():
            continue
        payload = json.loads(path.read_text(encoding="utf-8"))
        out = []
        for feature in payload.get("features") or []:
            coords = (feature.get("geometry") or {}).get("coordinates")
            if not coords:
                continue
            out.append(
                {
                    "name": str((feature.get("properties") or {}).get("name", "")),
                    "lon": round(float(coords[0]), 5),
                    "lat": round(float(coords[1]), 5),
                    "voltage": (feature.get("properties") or {}).get("voltage"),
                }
            )
        print(f"  GB substations: {len(out)} from {path.name}")
        return out
    raise SystemExit("grid_substations.geojson not found")


def load_flows(root: Path) -> tuple[dict, dict]:
    """Import/export MWh per BMRS code, and the source's own contract."""
    for candidate in FLOW_INDEX:
        path = root / candidate
        if not path.is_file():
            continue
        payload = json.loads(path.read_text(encoding="utf-8"))
        totals: dict[str, dict] = {}
        for row in payload.get("rows") or []:
            code = row.get("bmrsCode")
            if not code:
                continue
            bucket = totals.setdefault(
                code,
                {"country": row.get("country"), "name": row.get("interconnector"),
                 "import_mwh": 0.0, "export_mwh": 0.0, "years": []},
            )
            bucket["import_mwh"] += row.get("importMWh") or 0.0
            bucket["export_mwh"] += row.get("exportMWh") or 0.0
            if row.get("year") is not None:
                bucket["years"].append(row["year"])
        for bucket in totals.values():
            years = bucket.pop("years")
            bucket["years"] = f"{min(years)}-{max(years)}" if years else None
            bucket["net_mwh"] = round(bucket["import_mwh"] + bucket["export_mwh"], 1)
            bucket["import_mwh"] = round(bucket["import_mwh"], 1)
            bucket["export_mwh"] = round(bucket["export_mwh"], 1)
        contract = {
            "source": str(path.as_posix()),
            "title": payload.get("title"),
            "label_contract": payload.get("labelContract"),
            "sign_convention": payload.get("signConvention"),
            "generated_utc": payload.get("generatedUTC"),
        }
        print(f"  flow data: {len(totals)} links from {path.name}")
        return totals, contract
    print("  flow data: not found (geometry only)", file=sys.stderr)
    return {}, {}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", default=".")
    parser.add_argument("--out", default="atlas/data/interconnector-endpoints.json")
    parser.add_argument("--cache", default="atlas/data/.overpass-converters.json")
    parser.add_argument("--offline", action="store_true")
    args = parser.parse_args()

    root = Path(args.root).resolve()
    gb = load_gb_substations(root)
    flows, flow_contract = load_flows(root)
    elements = fetch_converters(Path(args.cache), args.offline)

    converters = []
    for element in elements:
        tags = element.get("tags") or {}
        name = tags.get("name")
        if not name:
            continue
        lat = element.get("lat") or (element.get("center") or {}).get("lat")
        lon = element.get("lon") or (element.get("center") or {}).get("lon")
        if lat is None or lon is None:
            continue
        converters.append(
            {
                "name": name,
                "lon": round(float(lon), 5),
                "lat": round(float(lat), 5),
                "operator": tags.get("operator"),
                "osm": f"{element.get('type')}/{element.get('id')}",
            }
        )
    print(f"  OSM converters with a name and a position: {len(converters)}")

    results = []
    for spec in LINKS:
        gb_hit = next((s for s in gb if spec["gb"] in s["name"].lower()), None)
        far_hit = None
        for alias in spec["far_aliases"]:
            far_hit = next((c for c in converters if alias in c["name"].lower()), None)
            if far_hit:
                break

        row = {
            "link": spec["link"],
            "bmrs": spec["bmrs"],
            "gb_name": gb_hit["name"] if gb_hit else None,
            "gb_lon": gb_hit["lon"] if gb_hit else None,
            "gb_lat": gb_hit["lat"] if gb_hit else None,
            "gb_source": "gridatlas grid_substations.geojson",
            "far_name": far_hit["name"] if far_hit else None,
            "far_lon": far_hit["lon"] if far_hit else None,
            "far_lat": far_hit["lat"] if far_hit else None,
            "far_source": f"OpenStreetMap {far_hit['osm']}" if far_hit else None,
            "crs": "EPSG:4326",
        }

        flow = flows.get(spec["bmrs"])
        if flow:
            row["country"] = flow["country"]
            row["flow_years"] = flow["years"]
            row["import_mwh"] = flow["import_mwh"]
            row["export_mwh"] = flow["export_mwh"]
            row["net_mwh"] = flow["net_mwh"]
            row["net_direction"] = "net import to GB" if flow["net_mwh"] > 0 else "net export from GB"

        if gb_hit and far_hit:
            straight = haversine_km(gb_hit["lon"], gb_hit["lat"], far_hit["lon"], far_hit["lat"])
            row["straight_line_km"] = round(straight, 2)
            row["midpoint_lon"] = round((gb_hit["lon"] + far_hit["lon"]) / 2, 5)
            row["midpoint_lat"] = round((gb_hit["lat"] + far_hit["lat"]) / 2, 5)
            row["geometry_kind"] = "STRAIGHT_LINE_CONVERTER_TO_CONVERTER"
            row["drawable"] = True
            known = KNOWN_CABLE_KM.get(spec["link"])
            if known:
                row["known_submarine_cable_km"] = known["submarine_km"]
                row["route_factor"] = round(known["submarine_km"] / straight, 3)
                row["route_factor_source"] = known["source"]
        else:
            row["drawable"] = False
            row["missing"] = "far end" if gb_hit else ("GB end" if far_hit else "both ends")
        results.append(row)

    drawable = [r for r in results if r["drawable"]]
    report = {
        "schema": "gridatlas.interconnector-endpoints.v1",
        "generated_utc": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "purpose": (
            "Converter-station pairs for GB interconnectors. GB ends come from our own "
            "substation data; far ends are queried from OpenStreetMap power=converter. "
            "The line between them is a straight line and is labelled as one: it measures "
            "separation between converter stations, not cable length."
        ),
        "far_end_source": "OpenStreetMap Overpass, power=converter",
        "bbox": {"south": BBOX[0], "west": BBOX[1], "north": BBOX[2], "east": BBOX[3]},
        "flow_data": flow_contract,
        "links": len(results),
        "drawable": len(drawable),
        "gb_ends_found": sum(1 for r in results if r["gb_lon"] is not None),
        "far_ends_found": sum(1 for r in results if r["far_lon"] is not None),
        "endpoints": results,
    }

    print()
    for row in results:
        if row["drawable"]:
            extra = f"  route factor {row['route_factor']}" if "route_factor" in row else ""
            print(f"  {row['link']:<18} {row['gb_name'][:28]:<30} -> {row['far_name'][:26]:<28} {row['straight_line_km']:>7.1f} km{extra}")
        else:
            print(f"  {row['link']:<18} {str(row['gb_name'])[:28]:<30} -> missing {row['missing']}")

    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(report, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
    # A GeoJSON the Atlas can consume without new plumbing. Each drawable link
    # yields two features: the straight line, and a midpoint carrying the same
    # property names an offshore project carries, so the existing offshore
    # rendering and the existing MAP button apply to it unchanged.
    features = []
    for row in results:
        if not row["drawable"]:
            continue
        common = {
            "link": row["link"],
            "bmrs_code": row["bmrs"],
            "gb_converter": row["gb_name"],
            "far_converter": row["far_name"],
            "straight_line_km": row["straight_line_km"],
            "geometry_kind": row["geometry_kind"],
            "far_end_source": row["far_source"],
            "country": row.get("country"),
            "flow_years": row.get("flow_years"),
            "import_mwh": row.get("import_mwh"),
            "export_mwh": row.get("export_mwh"),
            "net_mwh": row.get("net_mwh"),
            "net_direction": row.get("net_direction"),
        }
        if "route_factor" in row:
            common["known_submarine_cable_km"] = row["known_submarine_cable_km"]
            common["route_factor"] = row["route_factor"]
        features.append({
            "type": "Feature",
            "properties": dict(common, feature_role="link-line"),
            "geometry": {
                "type": "LineString",
                "coordinates": [[row["gb_lon"], row["gb_lat"]], [row["far_lon"], row["far_lat"]]],
            },
        })
        features.append({
            "type": "Feature",
            "properties": dict(
                common,
                feature_role="midpoint",
                name=row["link"],
                technology="interconnector",
                repd_ref=row["bmrs"],
                capacity_mw=None,
            ),
            "geometry": {"type": "Point", "coordinates": [row["midpoint_lon"], row["midpoint_lat"]]},
        })

    geo_path = out_path.with_name("interconnectors.geojson")
    geo_path.write_text(
        json.dumps(
            {
                "type": "FeatureCollection",
                "crs": {"type": "name", "properties": {"name": "EPSG:4326"}},
                "generated_utc": report["generated_utc"],
                "note": (
                    "Straight lines between converter stations, not surveyed cable routes. "
                    "Midpoints carry offshore-project property names so the existing "
                    "rendering and MAP button apply unchanged."
                ),
                "features": features,
            },
            indent=1,
            ensure_ascii=False,
        )
        + "\n",
        encoding="utf-8",
    )

    print(f"\n  {report['drawable']}/{report['links']} drawable · written {out_path}")
    print(f"  {len(features)} features · written {geo_path}")
    return 0


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

Interconnector Module

A JavaScript file in the interconnectors folder of GridAtlas that maps interconnectors and substations. It searches km (`searchKm`) and measures end (`measureEnd`).

energy-datagridatlas / tools/interconnectors/interconnector-module.js · lines 1–180 of 180 · Not reached from any entry point (candidate for review) · pattern measureEnd (shared by 4 files)

What it does
It maps interconnectors and substations. Defines 8 functions or classes, including rad, haversineKm, searchKm, label, measureEnd. Side effects: changes the web page (DOM); makes network requests.
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, substations.
Inputs & outputs
In: GeoJSON file interconnectors.geojson.
What it achieves
An interconnector is not a generator and it does not arrive anywhere.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/interconnectors · script
Uses
none found
Used by
none found
Produces
rad, haversineKm, searchKm, label, measureEnd, paint, boot, ready
Defines here
rad, haversineKm, searchKm, label, measureEnd, paint, boot, ready
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/interconnectors/interconnector-module.js:1-180 · blob 6214403eea08bab4782d73016e639d8287bc8dd0 · 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: unreached_review

/* ---------------------------------------------------------------------------
   INTERCONNECTORS

   An interconnector is not a generator and it does not arrive anywhere. It has
   two ends, and its connection is already known: it is the thing at the other
   end of its own cable. So this module does not reuse the project arrival at
   all - measured, a BritNed midpoint sits 59.2 km from the nearest substation
   and the far end resolves to Lowestoft at 165.9 km, because our substation
   payload is GB only. Firing the project engine from a midpoint would have
   reported nothing on every link, and matching a Dutch converter to Suffolk
   would have been worse than nothing.

   The model instead is a span with a search budget at each end:

       40km <- Grain --[ BritNed 234.9 km ]-- Maasvlakte -> 40km

   The span is unbounded. The per-end search keeps the ordinary onshore limit
   unless the user widens it with the radius box, and each end states its own
   data coverage so "no substation data for the Netherlands" can never be read
   as "no connection".
   --------------------------------------------------------------------------- */
(function interconnectors() {
  'use strict';

  const SOURCE_ID = 'src-interconnectors';
  const LINE_LAYER = 'l-interconnectors';
  const NODE_LAYER = 'l-interconnector-nodes';
  const DATA_URL = '../../data/interconnectors.geojson';
  const DEFAULT_SEARCH_KM = 40;

  const state = {
    schema: 'gridatlas.interconnectors.v1',
    loaded: false,
    links: [],
    error: null,
    search_km: DEFAULT_SEARCH_KM,
    search_source: 'default',
  };
  window.__GRIDATLAS_INTERCONNECTORS__ = state;

  // Match the estate-wide Ventus distance contract used by the onshore engine.
  const EARTH_KM = 6378.137;
  const rad = (d) => (d * Math.PI) / 180;
  function haversineKm(lon1, lat1, lon2, lat2) {
    const p1 = rad(lat1), p2 = rad(lat2);
    const dp = rad(lat2 - lat1), dl = rad(lon2 - lon1);
    const a = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
    return 2 * EARTH_KM * Math.asin(Math.sqrt(a));
  }

  /* The radius box is the override, so a widened search is a deliberate and
     attributable choice rather than a different physics applied silently to one
     technology. Onshore keeps its limit until someone types past it. */
  function searchKm() {
    const input = document.getElementById('radius-input');
    const typed = input ? parseFloat(input.value) : NaN;
    if (Number.isFinite(typed) && typed > 0) {
      state.search_km = typed;
      state.search_source = 'user';
      return typed;
    }
    state.search_km = DEFAULT_SEARCH_KM;
    state.search_source = 'default';
    return DEFAULT_SEARCH_KM;
  }

  // 40km <- Grain --[ BritNed 234.9 km ]-- Maasvlakte -> 40km
  function label(link, km) {
    const gb = String(link.gb_converter || 'GB end').replace(/ (Static Inverter Plant|Converter Station|Substation)$/i, '');
    const far = String(link.far_converter || 'far end').replace(/^HVDC /i, '');
    return `${km}km ← ${gb} ──[ ${link.link} ${link.straight_line_km} km ]── ${far} → ${km}km`;
  }

  /* Each end is measured against the substations we actually hold. The GB end
     is a converter inside a substation compound and scores ~0 km. The far end
     has no payload at all, and that is reported as absent coverage rather than
     as an empty result. */
  function measureEnd(role, lon, lat, km, subs) {
    if (!subs || !subs.length) {
      return { role, lon, lat, search_km: km, coverage: 'NONE',
               statement: 'No substation payload for this end, so nothing can be measured here. This is missing data, not an absence of connection.',
               nearest_km: null, nearest_name: null, within: 0 };
    }
    let nearest = null, within = 0;
    for (const sub of subs) {
      const at = sub.at || sub.coordinates;
      if (!at) continue;
      const d = haversineKm(lon, lat, +at[0], +at[1]);
      if (d <= km) within += 1;
      if (!nearest || d < nearest.km) nearest = { km: d, name: sub.name || null };
    }
    return {
      role, lon, lat, search_km: km, coverage: 'GB_SUBSTATIONS',
      nearest_km: nearest ? Number(nearest.km.toFixed(3)) : null,
      nearest_name: nearest ? nearest.name : null,
      nearest_beyond_search: nearest ? nearest.km > km : null,
      within,
    };
  }

  function paint(map, geojson) {
    if (!map.getSource(SOURCE_ID)) {
      map.addSource(SOURCE_ID, { type: 'geojson', data: geojson });
    } else {
      map.getSource(SOURCE_ID).setData(geojson);
    }
    if (!map.getLayer(LINE_LAYER)) {
      map.addLayer({
        id: LINE_LAYER, type: 'line', source: SOURCE_ID,
        filter: ['==', ['get', 'feature_role'], 'link-line'],
        layout: { visibility: 'none', 'line-cap': 'round' },
        paint: { 'line-color': '#ffae00', 'line-width': 2, 'line-opacity': 0.9, 'line-dasharray': [3, 2] },
      });
    }
    if (!map.getLayer(NODE_LAYER)) {
      map.addLayer({
        id: NODE_LAYER, type: 'circle', source: SOURCE_ID,
        filter: ['==', ['get', 'feature_role'], 'midpoint'],
        layout: { visibility: 'none' },
        paint: { 'circle-radius': 5, 'circle-color': '#ffae00', 'circle-stroke-width': 1, 'circle-stroke-color': '#0b0d10' },
      });
    }
  }

  async function boot(map) {
    let geojson;
    try {
      const response = await fetch(DATA_URL, { cache: 'no-store' });
      if (!response.ok) throw new Error('HTTP ' + response.status);
      geojson = await response.json();
    } catch (error) {
      state.error = 'interconnector data not served: ' + String(error && error.message || error);
      return;
    }

    const subs = (window.__GRIDATLAS_NEON_LINKS__ || {}).substations
      || (window.__GRIDATLAS_SUBSTATIONS__ || []);
    const km = searchKm();

    state.links = (geojson.features || [])
      .filter((f) => f.properties && f.properties.feature_role === 'link-line')
      .map((f) => {
        const p = f.properties;
        const [a, b] = f.geometry.coordinates;
        return {
          link: p.link, bmrs: p.bmrs_code,
          span_km: p.straight_line_km,
          geometry_kind: p.geometry_kind,
          route_factor: p.route_factor ?? null,
          known_submarine_cable_km: p.known_submarine_cable_km ?? null,
          net_mwh: p.net_mwh ?? null,
          net_direction: p.net_direction ?? null,
          label: label(p, km),
          ends: [
            measureEnd('gb', a[0], a[1], km, subs),
            measureEnd('far', b[0], b[1], km, []),
          ],
        };
      });

    state.loaded = true;
    state.search_km = km;
    paint(map, geojson);
  }

  function ready(map) {
    if (!map) return;
    if (map.isStyleLoaded && map.isStyleLoaded()) boot(map);
    else map.once('load', () => boot(map));
  }

  const timer = setInterval(() => {
    const map = window.__GRIDATLAS_V9_MAP__;
    if (!map) return;
    clearInterval(timer);
    try { ready(map); } catch (error) { state.error = String(error && error.message || error); }
  }, 400);
  setTimeout(() => clearInterval(timer), 90000);
})();