GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot Estate

A JavaScript file in the theme folder of Cosmic covering substations and solar, using SHA-256 and haversine, and uses data from the GridAtlas repository.

700 lines of JavaScript from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1145 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. Pilot Estate geodesy · cosmic / tools/explore/theme/pilot-estate.js lines 1–700

Pilot Estate

A JavaScript file in the theme folder of Cosmic covering substations and solar, using SHA-256 and haversine, and uses data from the GridAtlas repository.

geodesycosmic / tools/explore/theme/pilot-estate.js · lines 1–700 of 1185 · Entry point · pattern circleApproximationError (shared by 2 files)

What it does
It lists and searches substations, solar, the REPD register and cables. Defines 41 functions or classes, including curvatureKm, localScaleKm, distanceKm, distanceEllipsoidalKm, pathLengthKm. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: substations, solar, the REPD register, cables, 750kV, 400kV.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 2 files: Pilot Vicinity (cosmic); Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It audits project rows (`auditProjectRows`), builds deep link (`buildDeepLink`) and parses deep link (`parseDeepLink`). Pilot module "estate" (W10 / CAPSTAN-41): estate originals vendored VERBATIM, as PILOT.estate. Its code works with 750 kV.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html. Also imported by Pilot Vicinity.
Application
cosmic · tools/explore/theme · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
BEARING (GG2050-VEDIC-000005): GridAtlas / Geodesy · Mathematics / Trigonometry. coordinate_pair, coordinate_pair → bearing_deg
VEDIC
DESTINATION (GG2050-VEDIC-000004): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, distance_km, bearing_deg → coordinate_pair
Uses
GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
required by Pilot Vicinity (require), loaded by Pilot (script src)
Produces
curvatureKm, localScaleKm, distanceKm, distanceEllipsoidalKm, pathLengthKm, initialBearingDeg, destinationPoint, distanceToSegmentKm, distanceToLineKm, geodesicCircle, circleApproximationError, polygonAreaKm2
Defines here
curvatureKm, localScaleKm, distanceKm, distanceEllipsoidalKm, pathLengthKm, initialBearingDeg, destinationPoint, distanceToSegmentKm, distanceToLineKm, geodesicCircle, circleApproximationError, polygonAreaKm2, areaUnits, SpatialIndex, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, normalise, index
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-estate.js:1-700 · blob 03c3ac3fbe5e2ea2e16c065b91b47684889b4c46 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "estate" (W10 / CAPSTAN-41): estate originals vendored VERBATIM, as PILOT.estate. GENERATED by
   theme/pilot_estate.py; do not edit by hand. Each block below is the pinned source with only the leading
   `export ` keyword removed and each `import {..} from` turned into `const {..} = <earlier block>` (identity kept for
   Modular Star / Spiders); test_pilot_geo.py checks it byte for byte.
   PILOT.geo = PILOT.estate.geo: the ONE geodesy for Drone View. Earth model R_ATLAS = 6378.137 km, as GridAtlas, the
   Ventus Grid Engine and Pipeline News, so the same two points give the same number everywhere; a screening
   approximation (about 0.1 % from the ellipsoid in the UK). Every distance is straight-line, never a route.
   geo: Ventusltd/grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a src/geodesy.mjs (file sha256 69234c6996c547551237284f87f29d47f05e85916c463f91dc6928f34aaeede3, Apache-2.0, Ventus Ltd)
   engine: Ventusltd/ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/v9-geodesy.js (file sha256 af9b5a8796b51a1e4368491b98961a197adec539f2fa0f3ed226552a876864bb, Apache-2.0, Ventus Ltd)
   nearest: Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 engine/v9-nearest-search.js (file sha256 28cc8b973f9c294882ceffa9e27c3a2f14062e5263a8f82a08f5a861fb2b43fc, Apache-2.0, Ventus Ltd)
   deeplink: Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 deeplink/contract.js (file sha256 ed436968f622c865b8457a6d99d546fa6a84d8f5e056c78b2761c9e4187e7ad7, Apache-2.0, Ventus Ltd)
   lightning: Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 engine/lightning-click-context.js (file sha256 a4375943d9fa1cc429ec31667ddaad5987dad1f069871691e591727a8655a229, Apache-2.0, Ventus Ltd)
*/
(function () {
  'use strict';
  // ==== geo: Ventusltd/grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a src/geodesy.mjs (verbatim, export keywords removed)
  var geo = (function () {
// >>> geo begin
/**
 * Grid Distance Maths — canonical geodesy.
 *
 * Every Ventus tool that measures a distance on the grid should call this, so
 * that the same two points always produce the same number. See
 * docs/EARTH-MODEL.md for why R_ATLAS is the default and when to reach past it.
 *
 * Nothing here returns a cable route. Every function returns straight-line or
 * great-circle geometry, with no wayleave, crossing, terrain or consent
 * content. Consumers must carry that caveat to the user.
 */

/* ---- constants ---------------------------------------------------------- */

/** WGS84 semi-major axis. The constant every deployed Ventus tool already uses. */
const R_ATLAS = 6378.137;

/** IUGG mean radius. Turf.js default. Reads 0.112% shorter than R_ATLAS. */
const R_MEAN = 6371.0088;

/**
 * Gaussian mean radius of curvature at 54°N, the UK centroid. The most accurate
 * single sphere for these latitudes: mean error 46 ppm against the ellipsoid,
 * against 1,078 ppm for R_ATLAS. Opt in where accuracy matters more than
 * agreeing with already-published numbers.
 */
const R_UK = 6384.7272;

const WGS84 = Object.freeze({
  a: 6378.137,
  f: 1 / 298.257223563,
  get b() { return this.a * (1 - this.f); },
  get e2() { return this.f * (2 - this.f); },
});

const DEG = Math.PI / 180;

/* ---- curvature ---------------------------------------------------------- */

/**
 * Meridional (north–south) and prime-vertical (east–west) radii of curvature
 * at a latitude. These are what make a local tangent plane correct rather than
 * merely convenient.
 */
function curvatureKm(latDeg) {
  const s = Math.sin(latDeg * DEG);
  const t = 1 - WGS84.e2 * s * s;
  return {
    meridional: (WGS84.a * (1 - WGS84.e2)) / t ** 1.5,
    primeVertical: WGS84.a / Math.sqrt(t),
  };
}

/** Scale factors converting a degree of lon/lat to km at this latitude. */
function localScaleKm(latDeg) {
  const { meridional, primeVertical } = curvatureKm(latDeg);
  return {
    kx: primeVertical * Math.cos(latDeg * DEG) * DEG,
    ky: meridional * DEG,
  };
}

/* ---- distance ----------------------------------------------------------- */

/**
 * Great-circle distance in km. The atan2 form, which stays stable at both very
 * small and near-antipodal separations where the asin form loses precision.
 *
 * Identical in form and default constant to ventus-corev8engine.js haversine()
 * and gis-sld-v5-drawing.js atlasHaversineKm().
 */
function distanceKm(lon1, lat1, lon2, lat2, radius = R_ATLAS) {
  const dLat = (lat2 - lat1) * DEG;
  const dLon = (lon2 - lon1) * DEG;
  const x =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
  return radius * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
}

/**
 * Vincenty inverse solution on the WGS84 ellipsoid — the reference this
 * repository measures its spheres against. Millimetre-grade, ~30x slower than
 * the sphere, and non-convergent for near-antipodal pairs (returns NaN rather
 * than a wrong answer). Use it to validate, or where a number will be quoted.
 */
function distanceEllipsoidalKm(lon1, lat1, lon2, lat2) {
  const { a, f, b } = WGS84;
  const L = (lon2 - lon1) * DEG;
  const U1 = Math.atan((1 - f) * Math.tan(lat1 * DEG));
  const U2 = Math.atan((1 - f) * Math.tan(lat2 * DEG));
  const sU1 = Math.sin(U1); const cU1 = Math.cos(U1);
  const sU2 = Math.sin(U2); const cU2 = Math.cos(U2);
  let lambda = L; let prev; let iter = 0;
  let sinSigma; let cosSigma; let sigma; let cos2Alpha; let cos2SigmaM;
  do {
    const sl = Math.sin(lambda); const cl = Math.cos(lambda);
    sinSigma = Math.sqrt((cU2 * sl) ** 2 + (cU1 * sU2 - sU1 * cU2 * cl) ** 2);
    if (sinSigma === 0) return 0;
    cosSigma = sU1 * sU2 + cU1 * cU2 * cl;
    sigma = Math.atan2(sinSigma, cosSigma);
    const sinAlpha = (cU1 * cU2 * sl) / sinSigma;
    cos2Alpha = 1 - sinAlpha * sinAlpha;
    cos2SigmaM = cos2Alpha === 0 ? 0 : cosSigma - (2 * sU1 * sU2) / cos2Alpha;
    const C = (f / 16) * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha));
    prev = lambda;
    lambda = L + (1 - C) * f * sinAlpha
      * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2)));
  } while (Math.abs(lambda - prev) > 1e-12 && ++iter < 200);
  if (iter >= 200) return NaN;
  const u2 = (cos2Alpha * (a * a - b * b)) / (b * b);
  const A = 1 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2)));
  const B = (u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2)));
  const dSigma = B * sinSigma * (cos2SigmaM + (B / 4)
    * (cosSigma * (-1 + 2 * cos2SigmaM ** 2)
      - (B / 6) * cos2SigmaM * (-3 + 4 * sinSigma ** 2) * (-3 + 4 * cos2SigmaM ** 2)));
  return b * A * (sigma - dSigma);
}

/** Cumulative length of a polyline, in km. */
function pathLengthKm(coords, radius = R_ATLAS) {
  if (!Array.isArray(coords) || coords.length < 2) return 0;
  let total = 0;
  for (let i = 1; i < coords.length; i += 1) {
    total += distanceKm(coords[i - 1][0], coords[i - 1][1], coords[i][0], coords[i][1], radius);
  }
  return total;
}

/* ---- bearing and destination -------------------------------------------- */

function initialBearingDeg(lon1, lat1, lon2, lat2) {
  const p1 = lat1 * DEG; const p2 = lat2 * DEG;
  const dl = (lon2 - lon1) * DEG;
  const y = Math.sin(dl) * Math.cos(p2);
  const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
  return (Math.atan2(y, x) / DEG + 360) % 360;
}

/** Direct spherical destination: travel `km` from a point on `bearingDeg`. */
function destinationPoint(lon, lat, km, bearingDeg, radius = R_ATLAS) {
  const ad = km / radius;
  const brg = bearingDeg * DEG;
  const p1 = lat * DEG;
  const p2 = Math.asin(Math.sin(p1) * Math.cos(ad) + Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
  const l2 = lon * DEG + Math.atan2(
    Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
    Math.cos(ad) - Math.sin(p1) * Math.sin(p2),
  );
  return [l2 / DEG, p2 / DEG];
}

/* ---- point to line ------------------------------------------------------ */

/**
 * Perpendicular distance from a point to a single segment, and the foot of that
 * perpendicular.
 *
 * This is the function whose absence caused the circuit_km defect: measuring to
 * a segment's endpoints instead of to the segment can only overstate, and by up
 * to half the vertex spacing.
 *
 * The projection runs on a local tangent plane built from the WGS84 radii of
 * curvature at the query point's own latitude, so the foot is geometrically
 * right; the returned distance is then measured with `distanceKm`, so it is
 * directly comparable with every other number this module produces.
 */
function distanceToSegmentKm(lon, lat, aLon, aLat, bLon, bLat, radius = R_ATLAS) {
  const { kx, ky } = localScaleKm(lat);
  const ax = (aLon - lon) * kx; const ay = (aLat - lat) * ky;
  const bx = (bLon - lon) * kx; const by = (bLat - lat) * ky;
  const dx = bx - ax; const dy = by - ay;
  const len2 = dx * dx + dy * dy;
  let t = 0;
  if (len2 > 0) {
    t = -(ax * dx + ay * dy) / len2;
    t = t < 0 ? 0 : t > 1 ? 1 : t;
  }
  const foot = [aLon + (bLon - aLon) * t, aLat + (bLat - aLat) * t];
  return { km: distanceKm(lon, lat, foot[0], foot[1], radius), foot, t };
}

/** The nearest point on a polyline, and how far away it is. */
function distanceToLineKm(lon, lat, coords, radius = R_ATLAS) {
  let best = null;
  for (let i = 0; i < coords.length - 1; i += 1) {
    const hit = distanceToSegmentKm(
      lon, lat, coords[i][0], coords[i][1], coords[i + 1][0], coords[i + 1][1], radius,
    );
    if (!best || hit.km < best.km) best = { ...hit, segmentIndex: i };
  }
  return best;
}

/* ---- circles and area --------------------------------------------------- */

/**
 * A geodesic circle as a closed ring. The ring is INSCRIBED, so it understates:
 * at n vertices the worst radial error is R(1 − cos(π/n)) and the area is short
 * by 1 − (n/2π)·sin(2π/n).
 *
 *   n = 24   85.6 m inward at 10 km, area short 1.138%   (the zonedraw default)
 *   n = 64   12.0 m inward at 10 km, area short 0.161%
 *   n = 128   3.0 m inward at 10 km, area short 0.040%
 *
 * Default 128: the cost is trivial and it keeps the drawn ring honest against
 * the number printed beside it.
 */
function geodesicCircle(lon, lat, radiusKm, vertices = 128, radius = R_ATLAS) {
  const ring = [];
  for (let i = 0; i < vertices; i += 1) {
    ring.push(destinationPoint(lon, lat, radiusKm, (i / vertices) * 360, radius));
  }
  ring.push(ring[0]);
  return ring;
}

/** Inscribed-polygon error for a given vertex count, so callers can report it. */
function circleApproximationError(vertices) {
  return {
    radialFraction: 1 - Math.cos(Math.PI / vertices),
    areaShortFraction: 1 - (vertices / (2 * Math.PI)) * Math.sin((2 * Math.PI) / vertices),
  };
}

/** Spherical polygon area (km²) and perimeter (km) for a closed or open ring. */
function polygonAreaKm2(coords, radius = R_ATLAS) {
  if (!Array.isArray(coords) || coords.length < 3) return { areaKm2: 0, perimeterKm: 0 };
  let sum = 0;
  for (let i = 0; i < coords.length; i += 1) {
    const j = (i + 1) % coords.length;
    const xi = coords[i][0] * DEG; const yi = coords[i][1] * DEG;
    const xj = coords[j][0] * DEG; const yj = coords[j][1] * DEG;
    sum += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
  }
  const areaKm2 = (Math.abs(sum) * radius * radius) / 2;
  return { areaKm2, perimeterKm: pathLengthKm([...coords, coords[0]], radius) };
}

/** Familiar units for an area, for panels that report land take. */
function areaUnits(areaKm2) {
  const m2 = areaKm2 * 1e6;
  return {
    km2: areaKm2,
    hectares: m2 / 1e4,
    acres: m2 / 4046.85642,
    squareMiles: areaKm2 * 0.386102,
    squareMetres: m2,
  };
}

/* ---- nearest-feature search --------------------------------------------- */

/**
 * A uniform-cell spatial index. Built once over the network, it turns a
 * whole-layer sweep into a ring search over a handful of cells.
 *
 * The ring expands until the best hit found is provably inside the swept area —
 * stopping earlier is the bug that left ten projects reporting a circuit tens of
 * kilometres further away than the one actually nearest them.
 */
class SpatialIndex {
  constructor(cellDegrees = 0.1) {
    this.cell = cellDegrees;
    this.buckets = new Map();
  }

  static key(i, j) { return `${i}|${j}`; }

  cellOf(lon, lat) {
    return [Math.floor(lat / this.cell), Math.floor(lon / this.cell)];
  }

  add(id, lon, lat) {
    const [i, j] = this.cellOf(lon, lat);
    const k = SpatialIndex.key(i, j);
    if (!this.buckets.has(k)) this.buckets.set(k, []);
    this.buckets.get(k).push(id);
  }

  /**
   * Register a segment in EVERY cell its bounding box covers.
   *
   * Indexing only the two endpoint cells is not enough: a segment that enters a
   * cell and leaves it again without either end landing inside is invisible
   * from that cell, so a query sitting right beside the conductor misses it
   * until the ring search happens to reach an endpoint. That is a silent
   * overstatement, which is the one failure mode this whole module exists to
   * prevent.
   *
   * The bounding box is deliberately conservative rather than an exact
   * supercover walk: it can add a diagonal segment to a few cells it does not
   * actually cross, which costs one extra distance measurement each and can
   * never cost correctness, because `nearest` measures true distance to every
   * candidate it pulls out.
   */
  addSegment(id, aLon, aLat, bLon, bLat) {
    const [i1, j1] = this.cellOf(aLon, aLat);
    const [i2, j2] = this.cellOf(bLon, bLat);
    const iLo = Math.min(i1, i2); const iHi = Math.max(i1, i2);
    const jLo = Math.min(j1, j2); const jHi = Math.max(j1, j2);
    for (let i = iLo; i <= iHi; i += 1) {
      for (let j = jLo; j <= jHi; j += 1) {
        const k = SpatialIndex.key(i, j);
        if (!this.buckets.has(k)) this.buckets.set(k, []);
        this.buckets.get(k).push(id);
      }
    }
  }

  /**
   * @param {(id:number)=>number} measure distance in km for a candidate id
   * @returns {{id:number, km:number}|null}
   */
  nearest(lon, lat, measure, maxRings = 90) {
    const [ci, cj] = this.cellOf(lon, lat);
    let best = null;
    const seen = new Set();
    for (let ring = 0; ring < maxRings; ring += 1) {
      for (let i = ci - ring; i <= ci + ring; i += 1) {
        for (let j = cj - ring; j <= cj + ring; j += 1) {
          if (ring && Math.abs(i - ci) !== ring && Math.abs(j - cj) !== ring) continue;
          const bucket = this.buckets.get(SpatialIndex.key(i, j));
          if (!bucket) continue;
          for (const id of bucket) {
            // A segment spans several cells, so the same id surfaces more than
            // once. Measuring it once is the same answer for less work.
            if (seen.has(id)) continue;
            seen.add(id);
            const km = measure(id);
            if (best === null || km < best.km) best = { id, km };
          }
        }
      }
      if (best && best.km <= this.sweptClearanceKm(lon, lat, ring)) return best;
    }
    return best;
  }

  /**
   * The radius around the query point that a Chebyshev ring sweep has PROVABLY
   * covered. Stopping before the best hit is inside this is the bounded-search
   * defect; stopping later is merely slow.
   *
   * Two things make this subtler than `ring * cell`:
   *
   * 1. A cell is `cell` DEGREES on both axes, but a degree of longitude is
   *    shorter than a degree of latitude and narrows towards the pole -- 0.588
   *    of it at 54N, 0.500 at 60N. Converting both axes with ky, as this did
   *    until it was measured, permits stopping up to twice as early as the box
   *    justifies. A randomised sweep over 6,000 layouts then returned the wrong
   *    nearest feature in 10.95% of them, the worst reporting 65.4 km for a
   *    circuit 35.8 km away. Every such error overstates distance.
   *
   * 2. Sweeping to Chebyshev distance `ring` covers an axis-aligned box of
   *    cells, not a disc. The query point sits somewhere inside its own cell,
   *    not at its centre, so the guaranteed radius is the distance to the
   *    NEAREST edge of that box -- which can be almost a whole cell less than
   *    ring * cell on the side the point is closest to.
   *
   * Taking the true distance to each of the four edges, rather than assuming
   * the worst corner, is both correct and tighter: it terminates in fewer rings
   * than a conservative bound while never terminating too early. This mirrors
   * `swept_radius_km` in the pipelinenews grid-proximity builder, which reached
   * the better formulation first; the canonical module should not be behind its
   * own consumer.
   *
   * kx is evaluated at the highest latitude the box reaches, where a degree of
   * longitude is narrowest, so the east-west guarantee holds across the whole
   * box rather than only at the query latitude.
   */
  sweptClearanceKm(lon, lat, ring) {
    if (ring <= 0) return 0;
    const [ci, cj] = this.cellOf(lon, lat);
    const latLo = (ci - ring) * this.cell;
    const latHi = (ci + ring + 1) * this.cell;
    const lonLo = (cj - ring) * this.cell;
    const lonHi = (cj + ring + 1) * this.cell;
    const ky = localScaleKm(lat).ky;
    const worstLat = Math.min(Math.max(Math.abs(latLo), Math.abs(latHi)), 89.9);
    const kx = localScaleKm(worstLat).kx;
    return Math.min(
      (lat - latLo) * ky, (latHi - lat) * ky,
      (lon - lonLo) * kx, (lonHi - lon) * kx,
    );
  }
}

/* ---- guardrail ---------------------------------------------------------- */

/**
 * The caveat every consumer must show. Exported so no tool has to reword it,
 * and so a tool cannot quietly ship without it.
 *
 * `headroom` is the one a distance cannot answer at all. Fault level and
 * thermal headroom are a property of the network, not of the geometry, and the
 * only honest thing a proximity number can say about them is that they require
 * DNO data and a study.
 */
const STRAIGHT_LINE_CAVEAT = Object.freeze({
  distance: "Straight-line distance to mapped geometry. Not a cable route, not a "
    + "connection length, and no wayleave, crossing, terrain or consent content.",
  substation: "A mapped substation point does not confirm capacity, voltage "
    + "suitability, connection rights, queue position or acceptance by any network party.",
  coverage: "Absence from a mapped layer is not absence on the ground.",
  headroom: "Fault level and thermal headroom cannot be inferred from distance. "
    + "They depend on DNO network data such as source impedance, fault infeed and "
    + "existing committed connections, and are established by a connection study, "
    + "not by geometry.",
});

// <<< geo end
    return { R_ATLAS: R_ATLAS, R_MEAN: R_MEAN, R_UK: R_UK, WGS84: WGS84, curvatureKm: curvatureKm, localScaleKm: localScaleKm, distanceKm: distanceKm, distanceEllipsoidalKm: distanceEllipsoidalKm, pathLengthKm: pathLengthKm, initialBearingDeg: initialBearingDeg, destinationPoint: destinationPoint, distanceToSegmentKm: distanceToSegmentKm, distanceToLineKm: distanceToLineKm, geodesicCircle: geodesi  … [line shortened here: 588 characters; full line on GitHub]
  })();
  // ==== engine: Ventusltd/ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/v9-geodesy.js (verbatim, export keywords removed)
  var engine = (function () {
// >>> engine begin
/**
 * Module: geodesy
 *
 * Extracted verbatim (formula and constant unchanged) from
 * gridatlas/atlas/modules/202609011950-geodesy.js.
 *
 * One Earth radius for the whole estate, and the three operations every
 * measurement here is built from. This existed three times tonight - in
 * the sandbox, in the substation cartridge and in the data repository -
 * which is exactly how two of them end up on different radii without
 * anyone noticing.
 *
 * Radius 6378.137 km, matching Ventusltd/grid-distance-maths. Haversine.
 * No projection, no turf, no second radius for geometry.
 *
 * Pure functions. No DOM, no network, no state.
 *
 * CHANGED: source wraps this in `(() => { ... NS.geodesy = Object.freeze({...}) })()`
 * and registers itself on `window.__GRIDATLAS_MODULES__.geodesy`. That
 * closure/global-namespace wiring is removed; every function below is
 * otherwise byte-identical to the source, including the atan2 argument
 * order that the source's own comment insists on for numerical parity
 * with ventus-corev8engine.js haversine() (see distanceKm below).
 */

const EARTH_RADIUS_KM = 6378.137;
const DEG = Math.PI / 180;

function distanceKm(lon1, lat1, lon2, lat2) {
  const dLat = (lat2 - lat1) * DEG;
  const dLon = (lon2 - lon1) * DEG;
  const a = Math.sin(dLat / 2) ** 2
    + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
  /* atan2, in this operand order, because that is the form every version
     of this estate has shipped - ventus-corev8engine.js haversine() and
     every cartridge carried from it.
     -------------------------------------------------------------------
     The extraction wrote 2 * R * asin(sqrt(a)) instead. Algebraically the
     same; numerically one unit in the last place apart, which the
     all-versions proof caught on West Burton Solar to Cottam:
     7.050150827184836 shipped, 7.050150827184837 from the module. It is
     1e-15 km and changes no figure any reader will ever see - and it is
     still wrong, because the claim being made is PARITY. A module that is
     nearly the incumbent is a module that has to be argued about every
     time a digit differs. */
  return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

/* A polygon reduces to the mean of its outer ring, not its first corner.
   A substation drawn as a compound outline would otherwise be measured
   from whichever vertex the mapper happened to start at.

   Point, Polygon and MultiPolygon, and NOTHING ELSE. The first draft of
   this module accepted any nested coordinate array and so returned a
   mean for a LineString where the incumbent returns null; the parity
   proof caught it against the live cartridge. Extraction is not the
   moment to change behaviour, so the behaviour is pinned here and any
   widening becomes its own version with its own reasoning.

   One deliberate difference, on malformed input only: this returns null
   where the incumbent would throw on a Point with no coordinates. No
   real geometry reaches that path, and a proof asserts it. */
function representativePoint(geometry) {
  if (!geometry) return null;
  const { type, coordinates } = geometry;
  if (type === 'Point') {
    return Array.isArray(coordinates) && coordinates.length >= 2
      ? [coordinates[0], coordinates[1]] : null;
  }
  const ring = type === 'Polygon' ? coordinates && coordinates[0]
    : type === 'MultiPolygon' ? coordinates && coordinates[0] && coordinates[0][0]
      : null;
  if (!Array.isArray(ring) || !ring.length) return null;
  let sumLon = 0;
  let sumLat = 0;
  for (const point of ring) {
    sumLon += point[0];
    sumLat += point[1];
  }
  return [sumLon / ring.length, sumLat / ring.length];
}

/* OpenStreetMap's `voltage` is VOLTS at every magnitude, and a feature
   may carry several separated by a semicolon. Magnitude is not the unit:
   750 is a DC traction supply at a railway depot, not 750 kV. An audit
   of the served payload found 229 features (3.95%) carrying a token
   below 1,000, every one of which had been misread. An explicit `kv`
   property is already kilovolts and is trusted as such. */
function voltagesKv(properties) {
  if (!properties) return [];
  const out = [];
  const explicit = properties.kv ?? properties.KV;
  if (explicit != null && String(explicit).trim() !== '') {
    for (const token of String(explicit).match(/\d+(?:\.\d+)?/g) || []) {
      const value = Number(token);
      if (Number.isFinite(value) && value > 0) out.push(value);
    }
  }
  const volts = properties.voltage ?? properties.VOLTAGE;
  if (volts != null) {
    for (const token of String(volts).match(/\d+(?:\.\d+)?/g) || []) {
      const value = Number(token);
      if (Number.isFinite(value) && value > 0) out.push(value / 1000);
    }
  }
  return [...new Set(out)].sort((a, b) => b - a);
}

/* Projection and bearing, carried in from the sandbox verbatim.
   ----------------------------------------------------------------------
   The deep scan found the body carrying a SECOND geodesy section - "the
   geodesy the layout needs, all on R_ATLAS" - four hundred lines away
   from the first. Two geodesies in one file, on a constant that must
   never differ, is the configuration that produced the divergence the
   all-versions proof caught. Both belong here, on the one radius, and
   the body now delegates rather than defining.

   The bodies below are the incumbent's, character for character apart
   from the radius identifier, so parity is a property of the move rather
   than something to argue about afterwards. */
function destinationPoint(lon, lat, km, bearingDeg) {
  const ad = km / EARTH_RADIUS_KM;
  const brg = bearingDeg * DEG;
  const p1 = lat * DEG;
  const p2 = Math.asin(Math.sin(p1) * Math.cos(ad)
    + Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
  const l2 = lon * DEG + Math.atan2(
    Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
    Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
  return [l2 / DEG, p2 / DEG];
}

function initialBearingDeg(lon1, lat1, lon2, lat2) {
  const p1 = lat1 * DEG; const p2 = lat2 * DEG;
  const dl = (lon2 - lon1) * DEG;
  const y = Math.sin(dl) * Math.cos(p2);
  const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
  return (Math.atan2(y, x) / DEG + 360) % 360;
}

const schema = 'gridatlas.module.geodesy.v1';

// <<< engine end
    return { EARTH_RADIUS_KM: EARTH_RADIUS_KM, distanceKm: distanceKm, representativePoint: representativePoint, voltagesKv: voltagesKv, destinationPoint: destinationPoint, initialBearingDeg: initialBearingDeg, schema: schema };
  })();
  // ==== nearest: Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 engine/v9-nearest-search.js (verbatim, export keywords removed)
  var nearest = (function () {
// >>> nearest begin
/**
 * Module: nearest-search (substation-lookup)
 *
 * Extracted from gridatlas/atlas/modules/202609011950-substation-lookup.js.
 *
 * IMPORTANT PROVENANCE NOTE (see ../duplication.md 2(a)):
 * This module is committed to the gridatlas repo but is NOT referenced by
 * any composition/parts manifest and is NOT loaded by the live Atlas. The
 * nearest-substation search that actually runs in production is a
 * byte-different inline duplicate inside
 * atlas/cartridges/202609041330-substation-intelligence-v9-63.js
 * (state.nearest, lines 6083-6092 of that file). Both implementations do a
 * full exhaustive O(n) scan with no bbox/ring pre-filter, so neither has
 * the ring-search-excludes-true-nearest bug; the divergence is purely
 * architectural (dead module vs. hand-rolled duplicate), documented in
 * duplication.md.
 *
 * Finding a substation by the name someone wrote, and by position. Two
 * jobs, one boundary:
 *
 *   normalise(name)   the lookup key, matching the one data-grid-gb's own
 *                     join uses, so a name that matched there matches here
 *   index(points)     a name map and a located list, built once
 *   nearest(...)      the closest located sites, measured on the estate's
 *                     single radius via the geodesy module
 *
 * It does NOT fetch, render, summarise or decide. The cartridge fetches;
 * the summary module writes sentences; this only finds.
 *
 * CHANGED: source is an IIFE that reads its geodesy dependency off
 * `window.__GRIDATLAS_MODULES__.geodesy` and throws at load time if it is
 * absent. Replaced with a static ES import of ./geodesy.mjs. No formula or
 * control flow changed otherwise.
 */
const { distanceKm } = engine;

/* Deliberately dull. This is a lookup key, not a search engine, and it
   must stay byte-compatible with the normalisation the owner product's
   join uses - if the two drift, a name that joined upstream stops
   resolving downstream and nobody sees it happen. */
const NOISE = /\b(SUBSTATION|SUB STATION|SUBSTN|GRID|SUPPLY|POINT|GSP|NATIONAL|POWER|STATION|WIND|FARM|WINDFARM|OFFSHORE|ONSHORE|EXTENSION|400KV|275KV|132KV|66KV|33KV|11KV|NGET|SSE|SP|SHE)\b/g;

function normalise(name) {
  return String(name || '').toUpperCase()
    .replace(/[^A-Z0-9 ]/g, ' ')
    .replace(NOISE, ' ')
    .split(/\s+/).filter(Boolean).join(' ');
}

function index(points) {
  const byName = new Map();
  const located = [];
  for (const point of points || []) {
    const key = normalise(point && point.name);
    if (key && !byName.has(key)) byName.set(key, point);
    if (point && point.location) located.push(point);
  }
  return {
    size: byName.size,
    located: located.length,
    byName: (name) => byName.get(normalise(name)) || null,
    /* Nearest by measurement, not by guess. minimumKv filters on the
       highest voltage the site declares; limit 1 returns one match or
       null, anything else returns a sorted list.

       NOTE: this is an exhaustive scan over every located point -- no
       bbox/ring pre-filter -- so it cannot exhibit the ring-search bug
       (a pre-filter that excludes the true nearest node). It is O(n) per
       call; grid-distance-maths' SpatialIndex.nearest() is the estate's
       answer for when that stops being fast enough, with a proven
       early-termination bound (see ./nearest-search-spatial-index.mjs). */
    nearest: (lon, lat, options) => {
      const minimumKv = (options && options.minimumKv) || 0;
      const limit = (options && options.limit) || 1;
      const found = [];
      for (const point of located) {
        const voltages = point.voltages_kv || [];
        if (!voltages.length || Math.max(...voltages) < minimumKv) continue;
        found.push({
          point,
          km: distanceKm(lon, lat, point.location.lon, point.location.lat)
        });
      }
      found.sort((a, b) => a.km - b.km);
      return limit === 1 ? (found[0] || null) : found.slice(0, limit);
    }
  };
}

const schema = 'gridatlas.module.substation-lookup.v1';

// <<< nearest end
    return { normalise: normalise, index: index, schema: schema };
  })();
  // ==== deeplink: Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 deeplink/contract.js (verbatim, export keywords removed)
  var deeplink = (function () {
// >>> deeplink begin
/* deeplink/contract.js — the MAP-button deep link, as one testable thing.
 *
 * Before this repo, the contract existed only as an agreement between two
 * codebases that never imported each other: Pipeline News built a URL, and
 * GridAtlas parsed it, and nothing checked that the two still matched. They
 * stopped matching, and it cost a third of the register (see BUCKETS below).
 *
 * So the contract lives here once, as data plus two pure functions. The
 * emitter and the receiver are both meant to import it. Until they do, the
 * proof in proofs/deeplink.proof.mjs at least holds it to itself.
 *
 * Sources, all at their committed HEADs at extraction time:
 *   emitter   pipelinenews @ ade103ae
 *             releases/.../assets/202608312037-atlas-pointer-deep-link.mjs
 *   receiver  gridatlas @ 64268fd0
 *             atlas/parts/.../sld-sandbox-technology-buckets.js  (runDeepLink)
 *             ventus-corev8engine-exact-repd-delegation.js:66    (REPD_IDS)
 */

/* ── Identity ─────────────────────────────────────────────────────────────