GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Regional Native (part 4)

A JavaScript file in the atlas folder of GridAtlas 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.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 545 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. Regional Native geodesy · gridatlas / atlas/modules/202612012117-regional-native.js lines 2499–3198

Regional Native

A JavaScript file in the atlas folder of GridAtlas 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 atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.994 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 6350426294d6ee73ee6b6475003b30b79be79ae5a1e4a5a15de1a780fe517ce0
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202612012117-regional-native.js · lines 2499–3198 of 8607 · version 2026-12-01 21:17 (continued from section 541) · Not reached from any entry point (candidate for review) · pattern regionalEligible (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 239 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · 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
none found
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
seasonsOf, flagsFor, at, makeUnionFind, find, assemble, busOf, componentOf, multiply, solve, sinkFor, respond
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612012117-regional-native.js:2499-3198 · blob e01079f148704c08dfda3ccf7ae8239e3d77a00a · 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
          const code = graph.nodeSiteCode(farNode);
          if (!code || String(code).toUpperCase() === String(site.code).toUpperCase()) continue;
          if (bySite.has(code)) continue;
          const far = graph.siteByCode(code);
          bySite.set(code, {
            code,
            name: far ? far.name : null,
            hops: depth,
            first_node: farNode,
            voltage_kv: cross.far_kv,
            via: entry.kind
          });
        }
      }
      if (!next.length) break;
      frontier = next.sort();
    }

    const sites = [...bySite.values()].sort((a, b) =>
      a.hops - b.hops || String(a.code).localeCompare(String(b.code)));

    return {
      schema: SCHEMA,
      site: { code: site.code, name: site.name },
      requested_voltage_kv: voltageKv,
      hop_limit: limit,
      origin_nodes: origins.length,
      sites,
      counts: {
        sites: sites.length,
        by_hop: sites.reduce((acc, s) => {
          acc[s.hops] = (acc[s.hops] || 0) + 1;
          return acc;
        }, {})
      },
      refusals,
      not_a_distance: NOT_A_DISTANCE,
      not_a_capacity: NOT_A_CAPACITY
    };
  }

  NS.electricalDistance = Object.freeze({
    schema: SCHEMA,
    requires: REQUIRES,
    not_a_distance: NOT_A_DISTANCE,
    not_a_capacity: NOT_A_CAPACITY,
    impedance_basis: IMPEDANCE_CARRIED,
    undeclared: UNDECLARED,
    between,
    within
  });
})();

/**
 * Module: rating-envelope
 *
 * What the operator publishes a circuit can carry, season by season -
 * and a structural refusal to add those numbers up.
 *
 * WHY THE REFUSAL IS THE FEATURE
 * ------------------------------
 * A substation with eight 400 kV circuits rated 3,000 MVA each does not
 * have 24,000 MVA of anything. The ratings are thermal limits on
 * individual branches under stated seasonal conditions; they are not
 * additive, they are not simultaneous, and the sum is not a quantity that
 * exists in the network. Yet a sum is the single easiest number to
 * produce from this data and the single most persuasive to a reader, and
 * once printed it is indistinguishable from a capacity figure. That is
 * how a published rating becomes an invented headroom number.
 *
 * So this module reports each circuit's ratings individually, names the
 * season each one belongs to, and contains no code path that produces a
 * site total. The proof asserts the absence, not merely the intent.
 *
 * WHAT IT ADDS BEYOND "THE MINIMUM AND THE MAXIMUM"
 * -------------------------------------------------
 * The owner product already publishes a site-wide winter envelope
 * (`circuit_winter_rating_mva.min/max`). Three things it does not do,
 * which are done here:
 *
 *   1. All four seasons, not winter alone. Summer ratings are the binding
 *      ones for a thermally limited circuit, and the product carries them
 *      on 1,276 of 1,392 circuits - the 116 without are OFTO-labelled and
 *      are reported as not published rather than filled in.
 *
 *   2. Scoped to a voltage. A site-wide range across a 132 kV and a
 *      400 kV busbar is a number about no busbar at all.
 *
 *   3. Implausible values named rather than averaged away. Four circuits
 *      publish winter_mva of exactly 9999, on spans of a kilometre or
 *      less with zero impedance; planned changes reach 69,275. These have
 *      the shape of placeholders, not ratings. A module that quietly
 *      includes them in a maximum reports a lie with a citation attached,
 *      so they are carried, flagged, and excluded from the envelope with
 *      the exclusion stated.
 *
 *   node tools/proofs/modules/202609012250-rating-envelope.proof.mjs
 */
(() => {
  const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
  if (NS.ratingEnvelope) return;

  const SCHEMA = 'gridatlas.module.rating-envelope.v1';
  const REQUIRES = 'gridatlas.module.network-topology.graph.v1';

  const SEASONS = Object.freeze(['winter', 'spring', 'summer', 'autumn']);
  const FIELD = Object.freeze({
    winter: 'winter_mva', spring: 'spring_mva',
    summer: 'summer_mva', autumn: 'autumn_mva'
  });

  const NEVER_SUMMED =
    'These are per-circuit thermal ratings under stated seasonal '
    + 'conditions. They are not additive and they are not simultaneous: '
    + 'the sum of the circuits at a site is not a quantity that exists in '
    + 'the network, and this module contains no code that produces one.';

  const NOT_A_CAPACITY =
    'A rating is what a circuit is rated to carry, not what is free on '
    + 'it. Existing flows, committed connections, queue position, outage '
    + 'conditions and commercial terms decide what a project could use, '
    + 'and no published appendix contains any of them.';

  /* A rating that is obviously not a rating.
     -----------------------------------------------------------------
     9999 on a one-kilometre span with zero impedance is a placeholder,
     not a thermal limit; so is 69,275 on a hundred-metre cable. The test
     is deliberately narrow - a value at or above this threshold is
     flagged, nothing else is second-guessed - because a module that
     starts judging which published numbers it believes has stopped
     reporting the published record. */
  const IMPLAUSIBLE_MVA = 9999;

  function seasonsOf(row) {
    const published = {};
    const absent = [];
    for (const season of SEASONS) {
      const value = row[FIELD[season]];
      if (Number.isFinite(value)) published[season] = value;
      else absent.push(season);
    }
    return { published, absent };
  }

  function flagsFor(published) {
    const flags = [];
    for (const [season, value] of Object.entries(published)) {
      if (value >= IMPLAUSIBLE_MVA) {
        flags.push({
          season,
          value,
          reason: 'at or above ' + IMPLAUSIBLE_MVA + ' MVA, which has the '
            + 'shape of a placeholder rather than a thermal rating; it is '
            + 'reported and excluded from the range below'
        });
      }
    }
    return flags;
  }

  /**
   * Every circuit landing at a site, at one voltage, with its own
   * seasonal ratings. No total anywhere.
   *
   * @param index      a network-topology index exposing graph()
   * @param key        site code or exact site name
   * @param options    { voltageKv }
   */
  function at(index, key, options) {
    if (!index || typeof index.graph !== 'function') return null;
    const graph = index.graph();
    if (!graph || graph.schema !== REQUIRES) return null;

    const site = index.site(key);
    if (!site) return null;

    const opts = options || {};
    const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;

    const nodes = graph.nodesOfSite(site.code)
      .filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);

    const circuits = [];
    const seen = new Set();
    for (const nodeName of nodes) {
      for (const entry of graph.edgesAt(nodeName)) {
        if (entry.kind !== 'circuit') continue;
        const far = entry.row[entry.far];
        const id = [nodeName, far].sort().join('|');
        if (seen.has(id)) continue;
        seen.add(id);
        const { published, absent } = seasonsOf(entry.row);
        if (!Object.keys(published).length) continue;
        circuits.push({
          from_node: nodeName,
          to_node: far,
          to_site_code: graph.nodeSiteCode(far) || null,
          voltage_kv: graph.nodeVoltageKv(nodeName),
          circuit_type: typeof entry.row.circuit_type === 'string' ? entry.row.circuit_type : null,
          ohl_km: Number.isFinite(entry.row.ohl_km) ? entry.row.ohl_km : null,
          cable_km: Number.isFinite(entry.row.cable_km) ? entry.row.cable_km : null,
          ratings_mva: published,
          seasons_not_published: absent,
          flags: flagsFor(published),
          parameters_pct_100mva: graph.parametersOf(entry.row)
        });
      }
    }

    circuits.sort((a, b) => String(a.to_node).localeCompare(String(b.to_node)));

    /* The per-season RANGE across circuits - a lowest and a highest
       rating, which are two real published values - never a sum, and
       never a mean, which would be a number no circuit is rated at. */
    const by_season = {};
    for (const season of SEASONS) {
      const values = circuits
        .filter((c) => Number.isFinite(c.ratings_mva[season])
          && c.ratings_mva[season] < IMPLAUSIBLE_MVA)
        .map((c) => c.ratings_mva[season]);
      const excluded = circuits
        .filter((c) => Number.isFinite(c.ratings_mva[season])
          && c.ratings_mva[season] >= IMPLAUSIBLE_MVA).length;
      by_season[season] = values.length
        ? {
          lowest_circuit_mva: Math.min.apply(null, values),
          highest_circuit_mva: Math.max.apply(null, values),
          circuits: values.length,
          excluded_as_implausible: excluded
        }
        : { circuits: 0, excluded_as_implausible: excluded, published: false };
    }

    const flagged = circuits.filter((c) => c.flags.length);
    const missingSeasons = circuits.filter((c) => c.seasons_not_published.length);

    return {
      schema: SCHEMA,
      site: { code: site.code, name: site.name },
      requested_voltage_kv: voltageKv,
      scope: voltageKv == null
        ? 'every voltage at this site; a range across two busbar voltages '
          + 'is a number about neither of them'
        : voltageKv + ' kV nodes at this site only',
      circuits,
      by_season,
      counts: {
        circuits: circuits.length,
        with_a_flagged_value: flagged.length,
        with_a_season_not_published: missingSeasons.length
      },
      never_summed: NEVER_SUMMED,
      not_a_capacity: NOT_A_CAPACITY
    };
  }

  NS.ratingEnvelope = Object.freeze({
    schema: SCHEMA,
    requires: REQUIRES,
    seasons: SEASONS,
    implausible_mva: IMPLAUSIBLE_MVA,
    never_summed: NEVER_SUMMED,
    not_a_capacity: NOT_A_CAPACITY,
    at
  });
})();

/**
 * Module: injection-response
 *
 * A DECLARED DC power-flow model of the published GB transmission network,
 * used to answer one question: if power is injected here, which circuits
 * carry it, and what fraction of it does each one carry?
 *
 * ─────────────────────────────────────────────────────────────────────
 * WHY THIS IS A POWER FLOW AND NOT A PRETENDED ONE
 * ─────────────────────────────────────────────────────────────────────
 *
 * The standing rule in this estate has been that R, X and B are carried
 * and never computed with, because "the ETYS node/branch dataset is not a
 * solved power-flow model merely because it contains R/X/B". That rule is
 * right, and it is not repealed here. What it forbids is calling published
 * parameters a solution. What it permits - what it was always pointing at -
 * is a model that DECLARES itself: states its equations, its base, its
 * slack, its assumptions and its validation, and is honest about which
 * quantities it cannot produce.
 *
 * A full AC load flow of GB needs generation and load at every node,
 * transformer tap positions, voltage set points, contingency definitions
 * and validation against a trusted solver. None of those are published in
 * Appendix B, and this module does not invent them, so it does not
 * pretend to a load flow.
 *
 * An INJECTION RESPONSE needs none of them. It is the linear sensitivity
 * of branch flows to a transfer between two points - the power-transfer
 * distribution factor - and it depends only on the network's topology and
 * its series reactances, both of which ARE published. It is the quantity a
 * connection engineer wants first: not "what is flowing today", which
 * nobody publishes, but "where would my power go".
 *
 * ─────────────────────────────────────────────────────────────────────
 * THE DECLARED MODEL
 * ─────────────────────────────────────────────────────────────────────
 *
 *   Equations   DC approximation:  P = B' · θ,  and for each branch
 *               f_ij = (θ_i − θ_j) / x_ij
 *   Base        100 MVA, the base the product publishes R/X/B on.
 *   Reactance   x = x_pct_100mva / 100, per unit. Resistance is NOT used:
 *               the DC approximation neglects it, and saying so is part of
 *               the declaration.
 *   Voltages    Assumed flat at 1.0 per unit. Not published, not solved.
 *   Angles      Assumed small, so sin θ ≈ θ. Valid for a transmission
 *               network under normal conditions; it is an approximation
 *               and it is named as one.
 *   Losses      Zero, by construction of the DC approximation. Real losses
 *               are of order 1-2% and are not represented.
 *   Slack       DECLARED explicitly, never inferred silently. Every answer
 *               names the node the power is withdrawn at, because a
 *               transfer has two ends and quoting only one is meaningless.
 *   Taps        Not published, therefore not modelled. Transformers are
 *               represented by their series reactance alone.
 *   Shunts      b_pct_100mva is carried by the product and is NOT used:
 *               line charging does not appear in a DC model.
 *   Contingency None. This is the intact network.
 *
 * ─────────────────────────────────────────────────────────────────────
 * WHAT THE ANSWER IS NOT
 * ─────────────────────────────────────────────────────────────────────
 *
 * It is not a loading, and it is not headroom. It says what fraction of a
 * NEW injection would appear on each circuit. What is already flowing on
 * that circuit is not published anywhere in this product, so the sum of
 * the two - which is what determines whether the circuit is full - cannot
 * be computed here by anyone, including this module. A circuit carrying
 * 38% of a 500 MW injection is carrying 190 MW of it; whether that
 * circuit can accept 190 MW more depends on facts no appendix contains.
 *
 * ─────────────────────────────────────────────────────────────────────
 * ZERO-REACTANCE BRANCHES
 * ─────────────────────────────────────────────────────────────────────
 *
 * The product publishes circuits with x_pct_100mva of exactly 0 - zero
 * length spans, busbar couplers, some series devices. 1/x is undefined for
 * these, and substituting a small number would silently invent a
 * reactance. They are instead treated as what they physically are: a
 * short, meaning the two nodes are electrically the same bus. The nodes
 * are merged before the matrix is built, the merge is counted, and the
 * count is reported in the answer.
 *
 * ─────────────────────────────────────────────────────────────────────
 * WHAT THE FIRST VERSION GOT WRONG
 * ─────────────────────────────────────────────────────────────────────
 *
 * Codex reviewed this adversarially on request and found two defects that
 * the proof could not see, both of them the same shape: the proof tested a
 * case the production caller never takes.
 *
 * 1. NO ARBITRARY SLACK. The caller chose the first bus that was not the
 *    injection bus. The 400 kV induced graph is not connected - 573 buses,
 *    437 modelled edges, 238 components - so that bus is usually in a
 *    different component from the injection, and a transfer between two
 *    components does not exist. West Burton was paired with ABHA41, which
 *    is disconnected from 572 of the 573 buses; the solve ran 2,292
 *    iterations to a residual of about 1.7e13.
 *
 *    Worse, acceptance checked Kirchhoff at the INJECTION BUS ONLY, which
 *    a disconnected pair can satisfy while the solve has not converged at
 *    all. A page gated on that check could print an impossible transfer.
 *
 *    Now: the withdrawal bus must be in the same component as the
 *    injection, the component is computed and named, and where no sink is
 *    declared the rule that picks one is stated in the answer rather than
 *    left implicit. Acceptance requires convergence AND a global residual
 *    AND Kirchhoff at EVERY bus. Anything else is an explicit refusal.
 *
 * 2. PARALLEL CIRCUITS ARE NOT ONE CIRCUIT. Edges were de-duplicated by
 *    endpoints, kind and reactance, so two genuine parallel circuits that
 *    publish the same reactance collapsed into one - 22 groups covering 45
 *    published rows at 400 kV. Two parallel circuits carry twice what one
 *    carries at the same angle, so the collapse understated the network.
 *    Every landing is still visited twice, once from each end; the row
 *    ITSELF is now the identity, which distinguishes "seen twice" from
 *    "two rows that look alike".
 *
 *   node tools/proofs/modules/202609020015-injection-response.proof.mjs
 */
(() => {
  const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
  if (NS.injectionResponse) return;

  const SCHEMA = 'gridatlas.module.injection-response.v2';
  const REQUIRES = 'gridatlas.module.network-topology.graph.v1';

  const BASE_MVA = 100;

  const DECLARED_MODEL = Object.freeze({
    method: 'linear DC power flow (injection response / power transfer distribution factor)',
    equations: 'P = B′ · θ ; branch flow f_ij = (θ_i − θ_j) / x_ij',
    base_mva: BASE_MVA,
    reactance: 'x = x_pct_100mva / 100, per unit, as published',
    resistance: 'not used; the DC approximation neglects series resistance',
    shunt_susceptance: 'not used; line charging does not appear in a DC model',
    voltages: 'assumed flat at 1.0 per unit; not published and not solved',
    angles: 'assumed small, so sin θ ≈ θ',
    losses: 'zero by construction; real losses are of order 1-2% and are not represented',
    transformer_taps: 'not published, therefore not modelled; transformers are their series reactance only',
    contingencies: 'none; this is the intact network',
    slack: 'declared explicitly on every answer, never inferred silently'
  });

  const NOT_A_LOADING =
    'This is the response to a NEW injection, not a loading. What is '
    + 'already flowing on these circuits is published nowhere in this '
    + 'product, so the total flow - which is what decides whether a '
    + 'circuit is full - cannot be computed here by anyone.';

  const NOT_A_CONNECTION_OFFER =
    'A fraction of an injection appearing on a circuit is not permission '
    + 'to use that circuit. Queue position, committed connections, outage '
    + 'conditions, consent and commercial terms decide what a project may '
    + 'connect, and no published appendix contains any of them.';

  /* ── union-find, for shorting zero-reactance branches ──────────────── */
  function makeUnionFind() {
    const parent = new Map();
    function find(x) {
      if (!parent.has(x)) { parent.set(x, x); return x; }
      let root = x;
      while (parent.get(root) !== root) root = parent.get(root);
      let cursor = x;
      while (parent.get(cursor) !== cursor) {
        const next = parent.get(cursor);
        parent.set(cursor, root);
        cursor = next;
      }
      return root;
    }
    return {
      find,
      union(a, b) {
        const ra = find(a);
        const rb = find(b);
        if (ra === rb) return false;
        parent.set(ra, rb);
        return true;
      }
    };
  }

  /* The matrix assembly, taking an explicit node list so the caller
     decides the scope - one site, one voltage, or the whole product -
     without a second copy of this code existing for each case. */
  function assemble(graph, nodeNames, { voltageKv, includeTransformers }) {
    const inScope = new Set(nodeNames);
    const uf = makeUnionFind();
    for (const n of nodeNames) uf.find(n);

    const branches = [];
    const seen = new Set();
    let shorted = 0;
    let skippedNoReactance = 0;

    for (const name of nodeNames) {
      for (const entry of graph.edgesAt(name)) {
        if (entry.kind === 'transformer' && !includeTransformers) continue;
        const far = entry.row[entry.far];
        if (!inScope.has(far)) continue;
        /* The published ROW is the identity, not its values.
           ----------------------------------------------------------
           Keying on endpoints + kind + reactance collapsed genuine
           parallel circuits that happen to publish the same reactance:
           22 groups covering 45 rows at 400 kV. Two parallel circuits
           carry twice what one carries at the same angle, so collapsing
           them understates the network - and it understates it silently,
           which is worse. Every landing is visited twice, once from each
           end, and the row object distinguishes that from two rows that
           merely look alike. (Codex 202609020030, finding 2.) */
        if (seen.has(entry.row)) continue;
        seen.add(entry.row);

        const xPct = entry.row.x_pct_100mva;
        if (!Number.isFinite(xPct)) { skippedNoReactance += 1; continue; }
        if (xPct === 0) {
          /* physically a short: the two nodes are the same bus */
          if (uf.union(name, far)) shorted += 1;
          continue;
        }
        branches.push({
          from: name, to: far, kind: entry.kind,
          x_pu: xPct / 100,
          row: entry.row
        });
      }
    }

    /* After shorting, work in terms of bus representatives. */
    const busOf = (name) => uf.find(name);
    const buses = [...new Set(nodeNames.map(busOf))].sort();
    const busIndex = new Map(buses.map((b, i) => [b, i]));

    const edges = [];
    for (const b of branches) {
      const i = busIndex.get(busOf(b.from));
      const j = busIndex.get(busOf(b.to));
      if (i === undefined || j === undefined || i === j) continue;
      edges.push({ i, j, b: 1 / b.x_pu, meta: b });
    }

    /* Which buses can actually reach each other.
       --------------------------------------------------------------------
       A DC transfer between two components is not a transfer; it is a
       singular system, and asking a solver for it produces a large number
       rather than an error. So the components are computed here, once,
       and every answer names the one it was solved in. */
    const comp = makeUnionFind();
    for (const b of buses) comp.find(b);
    for (const e of edges) comp.union(buses[e.i], buses[e.j]);
    const componentOf = (bus) => comp.find(bus);
    const componentSizes = new Map();
    for (const b of buses) {
      const root = componentOf(b);
      componentSizes.set(root, (componentSizes.get(root) || 0) + 1);
    }
    /* the degree of each bus, for the declared sink rule below */
    const degree = new Map();
    for (const e of edges) {
      degree.set(buses[e.i], (degree.get(buses[e.i]) || 0) + 1);
      degree.set(buses[e.j], (degree.get(buses[e.j]) || 0) + 1);
    }

    return {
      schema: SCHEMA,
      declared_model: DECLARED_MODEL,
      componentOf,
      componentSize: (bus) => componentSizes.get(componentOf(bus)) || 0,
      degreeOf: (bus) => degree.get(bus) || 0,
      voltage_kv: voltageKv,
      includes_transformers: includeTransformers,
      buses, busIndex, busOf, edges,
      counts: {
        nodes: nodeNames.length,
        buses: buses.length,
        branches: edges.length,
        shorted_zero_reactance: shorted,
        skipped_no_published_reactance: skippedNoReactance,
        components: componentSizes.size,
        largest_component: Math.max(0, ...componentSizes.values())
      }
    };
  }

  /* ── sparse conjugate gradient on the reduced B' matrix ────────────── */
  function multiply(model, x, slackIndex) {
    const y = new Float64Array(x.length);
    for (const e of model.edges) {
      if (e.i === slackIndex || e.j === slackIndex) {
        /* the slack angle is pinned at zero, so its column contributes
           nothing and its row is not solved */
        if (e.i !== slackIndex) y[e.i] += e.b * x[e.i];
        if (e.j !== slackIndex) y[e.j] += e.b * x[e.j];
        continue;
      }
      const d = x[e.i] - x[e.j];
      y[e.i] += e.b * d;
      y[e.j] -= e.b * d;
    }
    return y;
  }

  function solve(model, injection, slackIndex, tolerance, maxIterations) {
    const n = model.buses.length;
    const x = new Float64Array(n);
    let r = new Float64Array(injection);
    r[slackIndex] = 0;
    let p = new Float64Array(r);
    let rr = 0;
    for (let k = 0; k < n; k += 1) rr += r[k] * r[k];
    const target = tolerance * tolerance * Math.max(rr, 1e-30);
    let iterations = 0;
    for (; iterations < maxIterations && rr > target; iterations += 1) {
      const ap = multiply(model, p, slackIndex);
      let pap = 0;
      for (let k = 0; k < n; k += 1) pap += p[k] * ap[k];
      if (!(Math.abs(pap) > 1e-30)) break;
      const alpha = rr / pap;
      let rrNext = 0;
      for (let k = 0; k < n; k += 1) {
        x[k] += alpha * p[k];
        r[k] -= alpha * ap[k];
        rrNext += r[k] * r[k];
      }
      const beta = rrNext / rr;
      for (let k = 0; k < n; k += 1) p[k] = r[k] + beta * p[k];
      rr = rrNext;
    }
    x[slackIndex] = 0;
    return { theta: x, iterations, residual: Math.sqrt(rr) };
  }

  const SINK_RULE =
    'Where no withdrawal bus is declared, the sink is the most connected '
    + 'bus in the SAME component as the injection - the bus with the most '
    + 'published branches landing on it. It is a stated rule, not a '
    + 'convenience: a transfer has two ends and the answer is meaningless '
    + 'without naming both. Declare a sink to override it.';

  /**
   * The withdrawal bus this model would choose, and why.
   *
   * Returns null when the injection bus has no one to transfer to, which
   * is a real answer about an isolated bus and not a failure.
   */
  function sinkFor(model, atNode) {
    if (!model || typeof model.componentOf !== 'function') return null;
    const atBus = model.busOf(atNode);
    const component = model.componentOf(atBus);
    let best = null;
    let bestDegree = -1;
    for (const bus of model.buses) {
      if (bus === atBus) continue;
      if (model.componentOf(bus) !== component) continue;
      const d = model.degreeOf(bus);
      if (d > bestDegree || (d === bestDegree && best !== null && bus < best)) {
        best = bus;
        bestDegree = d;
      }
    }
    return best;
  }

  /**
   * Inject `mw` at one node and withdraw it at the declared slack; report
   * the flow this puts on every branch that carries a meaningful share.
   *
   * @param model     from modelFor()
   * @param options   { atNode, slackNode, mw, minimumShare }
   */
  function respond(model, options) {
    const opts = options || {};
    const mw = Number.isFinite(opts.mw) ? opts.mw : 100;
    const atBus = model.busOf(opts.atNode);
    const slackBus = model.busOf(opts.slackNode);
    const i = model.busIndex.get(atBus);
    const s = model.busIndex.get(slackBus);
    if (i === undefined || s === undefined) return null;
    if (i === s) {
      return {
        schema: SCHEMA,
        declared_model: DECLARED_MODEL,
        injected_mw: mw,
        at_node: opts.atNode,
        slack_node: opts.slackNode,
        same_bus: true,
        reason: 'the injection point and the slack are the same electrical '
          + 'bus once zero-reactance branches are shorted, so there is no '
          + 'transfer to distribute',
        branches: [],
        not_a_loading: NOT_A_LOADING,
        not_a_connection_offer: NOT_A_CONNECTION_OFFER
      };
    }

    /* A transfer between two components does not exist. The solver would
       answer anyway - with a large number - so the refusal is here, before
       it is asked. (Codex 202609020030, finding 1.) */
    if (typeof model.componentOf === 'function'
      && model.componentOf(atBus) !== model.componentOf(slackBus)) {
      return {
        schema: SCHEMA,
        declared_model: DECLARED_MODEL,
        injected_mw: mw,
        at_node: opts.atNode,
        slack_node: opts.slackNode,
        same_bus: false,
        publishable: false,
        reason: 'the injection bus and the withdrawal bus are in different '
          + 'connected components of the published network at this voltage, '
          + 'so there is no transfer between them to distribute. The model '
          + 'has ' + (model.counts ? model.counts.components : 'several')
          + ' components at this voltage; a transfer must be solved within one.',
        branches: [],
        component: {
          injection: model.componentOf(atBus),
          slack: model.componentOf(slackBus),
          injection_component_buses: model.componentSize(atBus)
        },
        sink_rule: SINK_RULE,
        not_a_loading: NOT_A_LOADING,
        not_a_connection_offer: NOT_A_CONNECTION_OFFER
      };
    }

    const n = model.buses.length;
    const p = new Float64Array(n);
    p[i] = mw / BASE_MVA;      /* per unit on the declared base */
    p[s] = -mw / BASE_MVA;

    const solved = solve(model, p, s, 1e-10, Math.min(4 * n, 20000));

    const minimumShare = Number.isFinite(opts.minimumShare) ? opts.minimumShare : 0.01;