GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / data-grid-gb / conventional/fetchers

Verify Phase0 Acceptance and 3 more files

A Python command-line tool in the derived folder of Data Grid GB that reads GB transmission network, connection points, transformers and 132kV, using SHA-256 and haversine.

700 lines of Python from data-grid-gb, in 4 files. Topic: Websites and apps. Section 1880 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. Dukes 5 11 transform · data-grid-gb / conventional/fetchers/dukes_5_11.py lines 1–28
  2. Wri Gppd transform · data-grid-gb / conventional/fetchers/wri_gppd.py lines 1–20
  3. Verify Connection Points ingest · data-grid-gb / derived/verify_connection_points.py lines 1–239
  4. Verify Phase0 Acceptance electrical · data-grid-gb / derived/verify_phase0_acceptance.py lines 1–413

Dukes 5 11

A Python module in the fetchers folder of Data Grid GB. It is built from the raw requests helper (`raw_requests`) and the normalise step (`normalise`).

transformdata-grid-gb / conventional/fetchers/dukes_5_11.py · lines 1–28 of 28 · Not reached from any entry point (candidate for review) · pattern raw_requests (shared by 11 files)

What it does
It calculates its inputs. Defines raw_requests, normalise.
Inputs & outputs
In: Excel file DUKES_5.11.xlsx; Excel file DUKES_5.11-2026-05.xlsx.
What it achieves
DUKES Table 5.11: Power stations in the United Kingdom (DESNZ, OGL v3.0).
Why it matters
No other file in the estate was found to import it.
Application
data-grid-gb · conventional/fetchers · Python module
Uses
none found
Used by
none found
Produces
raw_requests, normalise
Defines here
raw_requests, normalise
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 conventional/fetchers/dukes_5_11.py:1-28 · blob 1231155bf082fa0e4e7111a376a34ad29feeac82 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""DUKES Table 5.11: Power stations in the United Kingdom (DESNZ, OGL v3.0).

SNAPSHOT. The fetch workflow downloads and pins the May 2026 edition. No normaliser
exists yet: the sandbox that built lane DC-A6 could not reach gov.uk, so nobody has
seen this edition's sheet layout. A parser written without seeing it would be a
guess. Once the snapshot is committed, DC-A6 (or a successor) writes ``normalise``
against the pinned bytes and sets STATUS = "ready". Its output then fills the fuel,
technology, status and installed capacity of the 167 "unstated" sites in
conventional/lanes/dc-a6.

Licence: "All content is available under the Open Government Licence v3.0" (GOV.UK
DUKES chapter 5 page, quoted by DC-A6 on 29 Oct 2026).
"""

SOURCE_ID = "dukes-5-11"
LANE = "DC-A6"
STATUS = "snapshot"

# Pinned to one edition. A new DUKES edition is a new URL and a reviewed change here.
URL = "https://assets.publishing.service.gov.uk/media/6a6a365b0ddb7e4831c629f3/DUKES_5.11.xlsx"


def raw_requests():
    return [{"file": "DUKES_5.11-2026-05.xlsx", "url": URL}]


def normalise(raw):
    raise NotImplementedError("dukes-5-11: snapshot only; write the parser against the pinned bytes")

Wri Gppd

A Python module in the fetchers folder of Data Grid GB. It is built from the raw requests helper (`raw_requests`) and the normalise step (`normalise`).

transformdata-grid-gb / conventional/fetchers/wri_gppd.py · lines 1–20 of 20 · Not reached from any entry point (candidate for review) · pattern raw_requests (shared by 11 files)

What it does
It calculates its inputs. Defines raw_requests, normalise.
What it achieves
WRI Global Power Plant Database, GB rows (v1.3.0).
Why it matters
No other file in the estate was found to import it.
Application
data-grid-gb · conventional/fetchers · Python module
Uses
none found
Used by
none found
Produces
raw_requests, normalise
Defines here
raw_requests, normalise
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 conventional/fetchers/wri_gppd.py:1-20 · blob 61986081c476696c60e2dbfdb5f2abda3d572693 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""WRI Global Power Plant Database, GB rows (v1.3.0).

PLACEHOLDER. Lane TBC (DC-A1..A6) owns this source; its fetcher replaces this file when it
lands, keeping the contract in assetpipe/pipeline.py (FETCHER_CONTRACT). Until then the
pipeline skips it and never fails because of it.

Registry entry: conventional/sources.json id "wri-gppd" (open: yes, licence: CC-BY-4.0).
"""

SOURCE_ID = "wri-gppd"
LANE = "TBC (DC-A1..A6)"
STATUS = "placeholder"


def raw_requests():
    return []


def normalise(raw):
    raise NotImplementedError("wri-gppd: fetcher not yet delivered by lane TBC (DC-A1..A6)")

Verify Connection Points

A Python command-line tool in the derived folder of Data Grid GB that reads GB transmission network and transformers. It is built from the check step (`check`).

ingestdata-grid-gb / derived/verify_connection_points.py · lines 1–239 of 239 · Entry point

What it does
It loads GB transmission network and transformers. Defines check, main. Uses libraries io, json, os, sys, collections. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV, 132kV (all 132kV or above)): 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: transformers, 400kV, 132kV.
Inputs & outputs
In: JSON file gb-transmission-network.v1.json; JSON file connection-points.v3.json. Voltage levels named: 400kV, 132kV.
Downstream impact
Used directly by 1 file: Refresh Network Products Workflow (data-grid-gb).
What it achieves
Verify both products before anything is allowed to consume them. Its code works with 132 kV and 400 kV.
Why it matters
Run by Refresh Network Products Workflow.
Application
data-grid-gb · derived · Python CLI
Uses
Build Connection Points (import), io, json, os, sys, collections
Used by
run by Refresh Network Products Workflow (workflow run)
Produces
check, main
Defines here
check, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 derived/verify_connection_points.py:1-239 · blob 724b090236e913230a705026e7284d95a751eb2f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Verify both products before anything is allowed to consume them.

The rule this repository inherits from the price repository: a consumer
reads a product that already sits clean. So the checks here fail closed,
and they check the things that would quietly mislead a reader rather than
the things that would obviously break a parser.

    python derived/verify_connection_points.py
"""

import io
import json
import os
import sys
from collections import Counter, defaultdict

from build_connection_points import normalise, site_join_context

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

failures = []
passed = 0


def check(label, condition):
    global passed
    if condition:
        passed += 1
        print(f"  [PASS] {label}")
    else:
        failures.append(label)
        print(f"  [FAIL] {label}")


def main():
    network = json.load(io.open(os.path.join(REPO, "derived", "gb-transmission-network.v1.json"),
                                encoding="utf-8"))
    points = json.load(io.open(os.path.join(REPO, "derived", "connection-points.v3.json"),
                               encoding="utf-8"))

    print("\nthe network model\n")
    check("schema is named and versioned",
          network.get("schema") == "data-grid-gb.transmission-network.v1")
    check("the publisher and publication are stated",
          network["source"]["publisher"] == "NESO"
          and "Ten Year Statement" in network["source"]["publication"])
    # The substance, not one product's sentence: both must say that queue
    # position and commercial terms decide connection and that no appendix
    # carries them. Pinning the exact wording made this check about prose.
    check("it refuses to be read as a connection assessment",
          "no published appendix contains" in network["not_a_connection_assessment"]
          and "queue position" in network["not_a_connection_assessment"].lower())
    counts = network["counts"]
    check("every transmission owner's sites are present",
          {s["transmission_owner"] for s in network["sites"]} == {"SHET", "SPT", "NGET", "OFTO"})
    check("circuits carry impedance on the declared base",
          all("r_pct_100mva" in c and "x_pct_100mva" in c for c in network["circuits"][:200]))
    check("circuits carry at least a winter rating",
          sum(1 for c in network["circuits"] if c.get("winter_mva")) > len(network["circuits"]) * 0.8)
    check("planned changes carry a year and a status",
          all(c.get("year") and c.get("status") for c in network["planned_changes"][:200]))
    check("the voltage-digit convention is published as derived, with its counts",
          network["node_code_convention"]["derived_not_documented"] is True
          and network["node_code_convention"]["observed_digit_to_site_voltage_counts"])
    check("nodes whose voltage the site does not declare are counted, not hidden",
          isinstance(network["node_code_convention"]
                     ["nodes_whose_voltage_is_not_declared_by_their_site"], int))
    check("the model is not trivially small",
          counts["circuits"] > 1000 and counts["nodes"] > 2000
          and counts["planned_changes"] > 1000)
    check("the ETYS 2025 model retains 1,472 distinct transformer records",
          counts["transformers"] == 1472
          and len(network["transformers"]) == 1472)

    print("\nthe connection points\n")
    check("schema is named and versioned",
          points.get("schema") == "data-grid-gb.connection-points.v3")
    check("it refuses to be read as a connection assessment",
          "no published appendix contains" in points["not_a_connection_assessment"]
          and "queue position" in points["not_a_connection_assessment"].lower())
    check("nothing below the declared minimum voltage is published",
          all(max(p["voltages_kv"]) >= points["minimum_kv"] for p in points["connection_points"]))
    join = points["join"]
    check("the join is reported by tier, not as a single number",
          all(k in join for k in ("exact_name", "distinctive_tokens",
                                  "ambiguous_exact_name",
                                  "ambiguous_distinctive_tokens",
                                  "ambiguous_authoritative_identity",
                                  "rejected_shore_qualifier_conflict", "unlocated")))
    check("the join total equals the number of points",
          join["exact_name"] + join["distinctive_tokens"] + join["unlocated"]
          == len(points["connection_points"]))
    check("ambiguous exact names fail closed inside the unlocated tier",
          0 < join["ambiguous_exact_name"] <= join["unlocated"])
    check("ambiguous token matches fail closed inside the unlocated tier",
          0 < join["ambiguous_distinctive_tokens"] <= join["unlocated"])
    check("an ambiguous authoritative name/voltage/owner identity fails closed",
          0 < join["ambiguous_authoritative_identity"] <= join["unlocated"])
    check("a mapped onshore/offshore qualifier conflict fails closed",
          0 < join["rejected_shore_qualifier_conflict"] <= join["unlocated"])
    check("unlocated sites are published rather than dropped",
          join["unlocated"] > 0
          and sum(1 for p in points["connection_points"] if "location" not in p)
          == join["unlocated"])
    check("every located point carries plausible GB coordinates",
          all(49 < p["location"]["lat"] < 61 and -9 < p["location"]["lon"] < 3
              for p in points["connection_points"] if "location" in p))
    check("a located point says how it was matched",
          all(p["location"]["matched_by"] in ("exact_name_highest_voltage",
                                                "exact_name_voltage_compatible",
                                                "distinctive_tokens_highest_voltage")
              for p in points["connection_points"] if "location" in p))
    check("onshore, offshore and extension remain identity-bearing",
          normalise("Moray East Onshore") == "MORAY EAST ONSHORE"
          and normalise("Moray East Offshore") == "MORAY EAST OFFSHORE"
          and normalise("Arecleoch Extension") == "ARECLEOCH EXTENSION")
    contexts = defaultdict(list)
    for site in network["sites"]:
        if site["voltages_kv"] and max(site["voltages_kv"]) >= points["minimum_kv"]:
            contexts[site_join_context(site)].append(site["code"])
    point_by_code = {p["site_code"]: p for p in points["connection_points"]}
    check("context keys combine name, voltage and owner and fail closed on duplicates",
          all((point_by_code[code]["join_context_key"] is not None) == (len(codes) == 1)
              for context, codes in contexts.items() for code in codes)
          and all("|" in p["join_context_key"]
                  for p in points["connection_points"] if p["join_context_key"] is not None))
    check("Thanet onshore does not lend its coordinate to Thanet offshore",
          "location" in point_by_code["THAW"]
          and "ONSHORE" in point_by_code["THAW"]["location"]["mapped_name"].upper()
          and "location" not in point_by_code["THOW"])
    check("Moray East offshore does not inherit Moray East onshore geometry",
          "location" in point_by_code["MORO"]
          and "ONSHORE" in point_by_code["MORO"]["location"]["mapped_name"].upper()
          and "location" not in point_by_code["MOWE"])
    expected_metrics = {
        "three_phase_initial_peak_current_ka", "three_phase_rms_break_current_ka",
        "three_phase_dc_break_current_ka", "three_phase_peak_break_current_ka",
        "single_phase_initial_peak_current_ka", "single_phase_rms_break_current_ka",
        "single_phase_dc_break_current_ka", "single_phase_peak_break_current_ka"}
    check("the root feed retains all eight exact Appendix D metrics",
          set(network.get("fault_current_metrics", [])) == expected_metrics)
    check("fault-current summaries name every metric and unit separately",
          all(set(entry["metrics"]) == expected_metrics
              and all(metric["unit"] == "kA" and metric["min"] <= metric["max"]
                      for metric in entry["metrics"].values())
              for point in points["connection_points"] if point["fault_current"]
              for entry in point["fault_current"].values()))
    check("fault-current summaries retain scenarios, winters and locations",
          all(entry["scenarios"] > 0 and entry["winters"] and entry["locations"]
              for point in points["connection_points"] if point["fault_current"]
              for entry in point["fault_current"].values()))
    check("every fault-current site envelope states when it combines voltages",
          all("site-wide envelope" in entry["scope"] and entry["voltages_kv"]
              for point in points["connection_points"] if point["fault_current"]
              for entry in point["fault_current"].values()))
    check("fault-current summaries are also separated by published voltage",
          all(point["fault_current_by_voltage"]
              and all(len(entry["voltages_kv"]) == 1
                      and str(int(entry["voltages_kv"][0])) == voltage
                      for voltage, cases in point["fault_current_by_voltage"].items()
                      for entry in cases.values())
              for point in points["connection_points"] if point["fault_current"]))
    cottam = [row for row in network["fault_current_scenarios"]
              if row["demand_case"] == "peak" and row["winter"] == "2025/26"
              and row["location"] == "COTT4 M1"]
    check("Cottam proves initial-peak is not renamed break current",
          len(cottam) == 1
          and abs(cottam[0]["three_phase_initial_peak_current_ka"]
                  - 109.219270174868) < 1e-9
          and "three_phase_rms_break_current_ka" in cottam[0]
          and "three_phase_break_ka" not in cottam[0])
    check("planned change years are consistent with their count",
          all((p["planned_changes"] > 0) == bool(p["planned_change_years"])
              for p in points["connection_points"]))

    # One transformer source row is one physical record.  Its two node ends
    # remain available as winding/landing evidence, but a same-site row must
    # contribute only once to that site's headline equipment count.
    node_by_name = {n["node"]: n for n in network["nodes"]}
    transformer_rows_by_site = defaultdict(set)
    for row_index, transformer in enumerate(network["transformers"]):
        incident_sites = {
            node_by_name[transformer[end]]["site_code"]
            for end in ("node_1", "node_2")
        }
        for site_code in incident_sites:
            transformer_rows_by_site[site_code].add(row_index)
    check("every site transformer headline counts distinct source rows, not node ends",
          all(p["transformers"] == len(transformer_rows_by_site[p["site_code"]])
              for p in points["connection_points"]))
    cowley = point_by_code["COWL"]
    cowley_rows = transformer_rows_by_site["COWL"]
    cowley_windings = Counter(
        node_by_name[transformer[end]]["voltage_kv"]
        for row_index, transformer in enumerate(network["transformers"])
        if row_index in cowley_rows
        for end in ("node_1", "node_2")
        if node_by_name[transformer[end]]["site_code"] == "COWL")
    check("Cowley is five physical records while both voltage winding counts remain five",
          cowley["transformers"] == 5 and len(cowley_rows) == 5
          and cowley_windings == Counter({400: 5, 132: 5}))
    check("the product declares its transformer count semantics",
          "one count per published Appendix B transformer row" in
          points.get("transformer_count_semantics", ""))
    check("the product stays browser-sized",
          os.path.getsize(os.path.join(REPO, "derived", "connection-points.v3.json")) < 3_000_000)

    # A named spot check: if these move, something upstream changed and a
    # reader deserves to hear about it before a map does.
    named = {p["name"].upper(): p for p in points["connection_points"]}
    for site, minimum_circuits in (("COTTAM", 4), ("WEST BURTON", 4),
                                   ("THORPE MARSH", 4), ("BICKER FEN", 4)):
        check(f"{site.title()} is present with its circuits and a location",
              site in named and named[site]["circuits"] >= minimum_circuits
              and "location" in named[site])
    west_burton = named["WEST BURTON"]
    check("West Burton resolves to the voltage-compatible Nottinghamshire feature",
          west_burton["location"]["matched_by"] == "exact_name_highest_voltage"
          and abs(west_burton["location"]["lat"] - 53.359219) < 0.001
          and abs(west_burton["location"]["lon"] + 0.809114) < 0.001)
    check("West Burton keeps 132 kV and 400 kV fault envelopes separate",
          set(west_burton["fault_current_by_voltage"]) == {"132", "400"}
          and west_burton["fault_current_by_voltage"]["400"]["peak"]
              ["metrics"]["three_phase_rms_break_current_ka"]["min"] > 30)

    print(f"\n{passed}/{passed + len(failures)} checks passed")
    if failures:
        print("\nFAILURES")
        for failure in failures:
            print("  " + failure)
        return 1
    print("both products are clean: parameters as published, join reported, "
          "and neither claims to assess a connection.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Verify Phase0 Acceptance

A Python command-line tool in the derived folder of Data Grid GB that reads GB transmission network, connection points, transformers and 132kV, using SHA-256 and haversine.

electricaldata-grid-gb / derived/verify_phase0_acceptance.py · lines 1–413 of 661 · Entry point · pattern summarise (shared by 11 files)

What it does
It loads GB transmission network, connection points, transformers and 132kV. Defines 15 functions or classes, including load_json, sha256, legacy_normalise, collision_summary, haversine. Uses libraries argparse, hashlib, io, json, math. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain terms in the code: transformers, 132kV, 400kV, 275kV, 66kV, 33kV.
Inputs & outputs
In: JSON file gb-transmission-network.v1.json; JSON file connection-points.v3.json; command-line arguments. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It loads JSON (`load_json`), replays road results (`replay_road_results`) and builds evidence (`build_evidence`). Independent Phase-0 acceptance oracle for the Electricity Ten Year Statement (ETYS) network products. Its code works with 132 kV. It accepts `--comparison-ref`, `--road-routes` and `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · derived · Python CLI
Uses
Build Connection Points (import), argparse, hashlib, io, json, math, os, re, statistics
Used by
none found
Produces
load_json, sha256, legacy_normalise, collision_summary, haversine, scalar_metrics, cable_evidence, coverage_evidence, transformer_evidence, points_from_git, location_delta, replay_road_results
Defines here
load_json, sha256, legacy_normalise, collision_summary, haversine, scalar_metrics, cable_evidence, summarise, coverage_evidence, transformer_evidence, points_from_git, location_delta
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 derived/verify_phase0_acceptance.py:1-413 · blob cfc5ca228326be4bae37e04e8027d0ec9aa87585 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
"""Independent Phase-0 acceptance oracle for the ETYS network products.

This oracle keeps four different populations separate:

* 1,472 Appendix B transformer rows (global physical-record population);
* transformer-to-site incidences after one row is counted once per site;
* node-end/winding landings, which legitimately count both ends; and
* cable *records* versus independent endpoint pairs.

It intentionally does not reproduce the road-routing experiment: the graph
binary and its source-build provenance are not in this repository.  An
optional externally generated route-result file can be re-scored, but that is
labelled evidence replay rather than an independent graph reconstruction.

Examples:

    python derived/verify_phase0_acceptance.py
    python derived/verify_phase0_acceptance.py --output evidence.json

The historical comparison defaults to the immutable pre-remediation commit
recorded below.  Do not substitute ``HEAD``: after this work is committed,
``HEAD`` is the corrected product rather than the 502/886 baseline.
"""

import argparse
import hashlib
import io
import json
import math
import os
import re
import statistics
import subprocess
import sys
from collections import Counter, defaultdict

from build_connection_points import normalise, site_join_context


HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
NETWORK_PATH = os.path.join(REPO, "derived", "gb-transmission-network.v1.json")
POINTS_PATH = os.path.join(REPO, "derived", "connection-points.v3.json")
R_KM = 6371.0088
FIXED_CORRIDOR_FACTOR = 1.245
HISTORICAL_BASELINE_REF = "1c9909d1138704b29235c27fd769436dda8a0b18"

LEGACY_NOISE = re.compile(
    r"\b(SUBSTATION|SUB STATION|SUBSTN|GRID|SUPPLY|POINT|GSP|NATIONAL|"
    r"POWER|STATION|WIND|FARM|WINDFARM|OFFSHORE|ONSHORE|EXTENSION|"
    r"400KV|275KV|132KV|66KV|33KV|11KV|NGET|SSE|SP|SHE)\b")


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


def sha256(path):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def legacy_normalise(name):
    text = str(name or "").upper()
    text = re.sub(r"[^A-Z0-9 ]", " ", text)
    return " ".join(LEGACY_NOISE.sub(" ", text).split())


def collision_summary(rows, normaliser):
    groups = defaultdict(list)
    for row in rows:
        groups[normaliser(row["name"])].append(row)
    collisions = {key: values for key, values in groups.items() if len(values) > 1}
    exact_name_groups = {
        key: values for key, values in collisions.items()
        if len({value["name"] for value in values}) == 1
    }
    destructive = {
        key: values for key, values in collisions.items()
        if len({value["name"] for value in values}) > 1
    }
    return {
        "rows": len(rows),
        "distinct_keys": len(groups),
        "collision_groups": len(collisions),
        "rows_in_collision_groups": sum(len(values) for values in collisions.values()),
        "first_win_rows_lost": sum(len(values) - 1 for values in collisions.values()),
        "exact_source_name_duplicate_groups": len(exact_name_groups),
        "exact_source_name_duplicate_rows": sum(
            len(values) for values in exact_name_groups.values()),
        "destructive_normalisation_groups": len(destructive),
        "distinct_source_names_in_destructive_groups": sum(
            len({value["name"] for value in values}) for values in destructive.values()),
        "rows_in_destructive_groups": sum(len(values) for values in destructive.values()),
        "groups": [
            {
                "key": key,
                "sites": [
                    {
                        "site_code": value["code"] if "code" in value else value["site_code"],
                        "name": value["name"],
                        "highest_voltage_kv": max(value["voltages_kv"]),
                        "transmission_owner": value["transmission_owner"],
                    }
                    for value in values
                ],
            }
            for key, values in sorted(collisions.items())
        ],
    }


def haversine(location_a, location_b):
    lat1, lon1 = location_a
    lat2, lon2 = location_b
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = phi2 - phi1
    dlambda = math.radians(lon2 - lon1)
    a = (math.sin(dphi / 2.0) ** 2
         + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2)
    return 2.0 * R_KM * math.atan2(math.sqrt(a), math.sqrt(max(0.0, 1.0 - a)))


def scalar_metrics(rows, factor=FIXED_CORRIDOR_FACTOR):
    errors = [abs(factor * row["straight_km"] - row["cable_km"])
              / row["cable_km"] * 100.0 for row in rows]
    within = sum(error <= 15.0 for error in errors)
    best = None
    for step in range(2501):
        candidate = 0.5 + step * 0.001
        candidate_errors = [
            abs(candidate * row["straight_km"] - row["cable_km"])
            / row["cable_km"] * 100.0 for row in rows
        ]
        score = statistics.median(candidate_errors)
        if best is None or score < best[1]:
            best = (candidate, score)
    return {
        "n": len(rows),
        "factor": factor,
        "median_absolute_percentage_error": statistics.median(errors),
        "within_15_percent_n": within,
        "within_15_percent_fraction": within / len(rows),
        "best_factor_grid_0.001": best[0],
        "best_factor_in_sample_median_absolute_percentage_error": best[1],
        "evaluation_warning": (
            "Descriptive in-sample calibration only; this is not a held-out "
            "accuracy estimate and does not establish route geometry."),
    }


def cable_evidence(network, points):
    node_site = {node["node"]: node["site_code"] for node in network["nodes"]}
    locations = {
        point["site_code"]: (float(point["location"]["lat"]),
                             float(point["location"]["lon"]))
        for point in points["connection_points"] if point.get("location")
    }
    rows = []
    skipped = Counter()
    for index, circuit in enumerate(network["circuits"]):
        if circuit.get("circuit_type") != "Cable":
            continue
        site_1 = node_site.get(circuit.get("node_1"))
        site_2 = node_site.get(circuit.get("node_2"))
        if not site_1 or not site_2:
            skipped["node_without_site"] += 1
            continue
        if site_1 == site_2:
            skipped["same_authoritative_site"] += 1
            continue
        if site_1 not in locations or site_2 not in locations:
            skipped["endpoint_without_mapped_joined_coordinates"] += 1
            continue
        cable_km = float(circuit.get("cable_km") or 0.0)
        ohl_km = float(circuit.get("ohl_km") or 0.0)
        if cable_km <= 0.0:
            skipped["no_positive_cable_km"] += 1
            continue
        straight = haversine(locations[site_1], locations[site_2])
        rows.append({
            "circuit_index": index,
            "node_1": circuit["node_1"],
            "node_2": circuit["node_2"],
            "site_1": site_1,
            "site_2": site_2,
            "pair": "|".join(sorted((site_1, site_2))),
            "cable_km": cable_km,
            "ohl_km": ohl_km,
            "straight_km": straight,
        })

    study_rows = [row for row in rows if row["straight_km"] > 1.0]

    def summarise(sample):
        pairs = defaultdict(list)
        for row in sample:
            pairs[row["pair"]].append(row)
        circuit_membership = [
            {
                "circuit_index": row["circuit_index"],
                "pair": row["pair"],
                "node_1": row["node_1"],
                "node_2": row["node_2"],
            }
            for row in sorted(sample, key=lambda item: item["circuit_index"])
        ]
        pair_membership = sorted(pairs)
        circuit_membership_bytes = json.dumps(
            circuit_membership, sort_keys=True, separators=(",", ":")
        ).encode("utf-8")
        pair_membership_bytes = json.dumps(
            pair_membership, separators=(",", ":")
        ).encode("utf-8")
        pair_rows = []
        for pair, members in sorted(pairs.items()):
            pair_rows.append({
                "pair": pair,
                "straight_km": members[0]["straight_km"],
                "cable_km": statistics.mean(member["cable_km"] for member in members),
                "parallel_circuit_records": len(members),
            })
        contradictions = [
            row for row in sample if row["straight_km"] > row["cable_km"] + 1e-9
        ]
        return {
            "circuit_records": len(sample),
            "distinct_site_pairs": len(pairs),
            "parallel_record_excess": len(sample) - len(pairs),
            "membership": {
                "circuit_records": circuit_membership,
                "circuit_records_sha256": hashlib.sha256(
                    circuit_membership_bytes).hexdigest(),
                "site_pairs": pair_membership,
                "site_pairs_sha256": hashlib.sha256(
                    pair_membership_bytes).hexdigest(),
                "split_rule": (
                    "Freeze and split by site pair; parallel circuit records for one "
                    "pair must never cross train/holdout boundaries."),
            },
            "straight_exceeds_published_cable_km_records": len(contradictions),
            "straight_exceeds_warning": (
                "A contradiction is a location-join/coordinate/length-semantics QA "
                "signal; it does not by itself identify the cause."),
            "fixed_factor_circuit_weighted": scalar_metrics(sample),
            "fixed_factor_pair_weighted_mean_published_length": scalar_metrics(pair_rows),
        }

    return {
        "selection": (
            "circuit_type == 'Cable'; distinct authoritative endpoint sites; "
            "both endpoints have mapped/joined coordinates; cable_km > 0"),
        "all_coordinate_known_intersite_cable_records": summarise(rows),
        "coordinate_known_intersite_records_at_or_below_1km": sum(
            row["straight_km"] <= 1.0 for row in rows),
        "legacy_study_filter_straight_distance_gt_1km": summarise(study_rows),
        "skipped_before_coordinate_known_intersite_sample": dict(skipped),
        "earth_radius_km": R_KM,
        "independence_warning": (
            "Circuit rows sharing a site pair are not independent route geometries; "
            "report record-weighted and pair-weighted results separately. Dynamic "
            "count-only cohorts are not predictive gates; freeze membership before "
            "a pair-grouped train/holdout split."),
    }


def coverage_evidence(points):
    rows = points["connection_points"]
    output = {
        "connection_points": len(rows),
        "with_mapped_joined_coordinates": sum(bool(row.get("location")) for row in rows),
    }
    output["without_mapped_joined_coordinates"] = (
        output["connection_points"] - output["with_mapped_joined_coordinates"])
    output["coverage_fraction"] = (
        output["with_mapped_joined_coordinates"] / output["connection_points"])
    by_voltage = {}
    for voltage in (400, 275, 220, 132, 66, 33, 11):
        population = [row for row in rows if voltage in row["voltages_kv"]]
        located = sum(bool(row.get("location")) for row in population)
        by_voltage[str(voltage)] = {
            "connection_points": len(population),
            "with_mapped_joined_coordinates": located,
            "without_mapped_joined_coordinates": len(population) - located,
            "coverage_fraction": located / len(population) if population else None,
        }
    output["by_voltage_kv"] = by_voltage
    output["wording_boundary"] = (
        "NESO ETYS does not publish these coordinates; they are mapped geometry "
        "joined to ETYS identities and must not be called published coordinates.")
    return output


def transformer_evidence(network, points):
    nodes = {node["node"]: node for node in network["nodes"]}
    all_incidences = defaultdict(set)
    endpoint_landings = Counter()
    same_site_rows = 0
    for index, transformer in enumerate(network["transformers"]):
        endpoint_sites = []
        for end in ("node_1", "node_2"):
            site_code = nodes[transformer[end]]["site_code"]
            endpoint_sites.append(site_code)
            endpoint_landings[site_code] += 1
        if len(set(endpoint_sites)) == 1:
            same_site_rows += 1
        for site_code in set(endpoint_sites):
            all_incidences[site_code].add(index)

    rollup_codes = {point["site_code"] for point in points["connection_points"]}
    point_by_code = {point["site_code"]: point for point in points["connection_points"]}
    rollup_incidences = {
        code: indices for code, indices in all_incidences.items() if code in rollup_codes
    }
    cowley_indices = all_incidences["COWL"]
    cowley_windings = Counter()
    cowley_signatures = Counter()
    for index in sorted(cowley_indices):
        transformer = network["transformers"][index]
        cowley_signatures[json.dumps(transformer, sort_keys=True,
                                     separators=(",", ":"))] += 1
        for end in ("node_1", "node_2"):
            node = nodes[transformer[end]]
            if node["site_code"] == "COWL":
                cowley_windings[str(node["voltage_kv"])] += 1

    mismatches = [
        {
            "site_code": code,
            "product": point_by_code[code]["transformers"],
            "oracle": len(indices),
        }
        for code, indices in rollup_incidences.items()
        if point_by_code[code]["transformers"] != len(indices)
    ]
    return {
        "global_transformer_records": len(network["transformers"]),
        "same_site_transformer_records": same_site_rows,
        "same_site_transformer_record_fraction": same_site_rows / len(network["transformers"]),
        "global_node_end_landings": sum(endpoint_landings.values()),
        "global_transformer_site_incidences": sum(
            len(indices) for indices in all_incidences.values()),
        "global_sites_with_transformers": len(all_incidences),
        "global_sites_inflated_by_endpoint_count": sum(
            endpoint_landings[code] > len(indices)
            for code, indices in all_incidences.items()),
        "rollup_node_end_landings": sum(
            endpoint_landings[code] for code in rollup_incidences),
        "rollup_transformer_site_incidences": sum(
            len(indices) for indices in rollup_incidences.values()),
        "rollup_sites_with_transformers": len(rollup_incidences),
        "rollup_sites_inflated_by_endpoint_count": sum(
            endpoint_landings[code] > len(indices)
            for code, indices in rollup_incidences.items()),
        "product_count_mismatches": mismatches,
        "cowley": {
            "product_physical_record_count": point_by_code["COWL"]["transformers"],
            "oracle_physical_record_count": len(cowley_indices),
            "node_end_windings_by_voltage_kv": dict(sorted(cowley_windings.items())),
            "largest_byte_identical_parallel_group": max(cowley_signatures.values()),
            "identity_rule": (
                "Use source-row ordinal while indexing. Never deduplicate by row "
                "content: distinct parallel units can be byte-identical."),
        },
        "terminology": {
            "1472": "global physical/source transformer records",
            "1550": "global transformer-to-site incidences",
            "1526": "transformer-to-site incidences in the >=132 kV rollup only",
            "2944": "global node-end/winding landings",
            "2920": "node-end/winding landings in the >=132 kV rollup",
        },
    }


def points_from_git(ref):
    raw = subprocess.check_output(
        ["git", "show", f"{ref}:derived/connection-points.v3.json"],
        cwd=REPO)
    return json.loads(raw.decode("utf-8"))


def location_delta(current, comparison):
    current_by_code = {point["site_code"]: point for point in current["connection_points"]}
    comparison_by_code = {
        point["site_code"]: point for point in comparison["connection_points"]
    }
    lost, gained, changed = [], [], []
    for code in sorted(current_by_code):
        now = current_by_code[code].get("location")
        before = comparison_by_code[code].get("location")
        if before and not now:
            lost.append({"site_code": code, "name": current_by_code[code]["name"],
                         "before": before})
        elif now and not before:
            gained.append({"site_code": code, "name": current_by_code[code]["name"],
                           "after": now})
        elif now and before and now != before:
            changed.append({"site_code": code, "name": current_by_code[code]["name"],
                            "before": before, "after": now})
    return {
        "lost": lost,
        "gained": gained,
        "changed": changed,
        "counts": {"lost": len(lost), "gained": len(gained),
                   "changed": len(changed),
                   "net_location_change": len(gained) - len(lost)},
        "interpretation": (
            "A lower count is not automatically a regression: fail-closed removal of "
            "an unsupported join is an epistemic correction. Review every code."),
    }