GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/modules

Single-Line Diagram (SLD) Without Layout (part 11)

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 407 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. Single-Line Diagram (SLD) Without Layout geodesy · gridatlas / atlas/modules/202611222130-sld-without-layout.js lines 7001–7700

Single-Line Diagram (SLD) Without Layout

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

Set aside from the main view: 100% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9961 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
  • sha256 6870cfb365c18b90363b664f89623c9217c3d0111a67b87fdd1b6b3a26aeba6b
  • target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202611222130-sld-without-layout.js · lines 7001–7700 of 8986 · version 2026-11-22 21:30 (continued from section 397) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 273 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
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
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
enableBoth, arrive, runArrivalSelection, arrivalHasVisibleOutcome, attemptArrival, attach, boot, bootOnce, PatchedMap, freshFinanceInputs, destinationPoint, initialBearingDeg, pathLengthKm, normBearing, localScaleKm, distanceToSegmentKm, rectPolygon, footOnSegment, activePhysicalInputs, applyDevelopmentStageDefaults, applyMountingBifacial, computeScreeningFinance, computeSldStats, fitToStatedCapacity, buildLayout
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/202611222130-sld-without-layout.js:7001-7700 · blob ab6fc6992aa26e51a3c82d7e2d26172a50798c60 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
        // Turn the substations on. Arriving from the MAP button in Pipeline
        // News, the whole point is to see the project against the network, and
        // a user who has to find a checkbox first has been handed a puzzle
        // rather than an answer. The engine owns the layer, so this ticks its
        // own control rather than reaching past it into the map.
        // The dashboard is built from the engine's own data and does not
        // exist yet on a cold load -- measured at zero checkboxes twenty
        // seconds in. Ticking a control that has not been rendered silently
        // did nothing, and the layers the arrival depends on stayed off.
        // Named, so Try again re-runs exactly the arrival rather than
        // reloading and paying for the whole engine a second time.
        let currentArrival = Object.freeze({ lon, lat, name, tech, stated, repdRef, suppliedStatus });
        const enableBoth = () => {
          if (!arrivalGate.isCurrent(epoch)) return false;
          enableSubstationLayer();
          if (technologyKnown) enableTechnologyLayer(currentArrival.tech);
          return true;
        };
        const arrive = async () => {
          clearStatus();
          const ready = await waitForLayerControls(12000);
          enableBoth();
          // Late is not never. If the dashboard turns up after the budget, the
          // layers still go on, without the user having to do anything.
          if (!ready) watchForLayerControls(enableBoth);
          return ready;
        };
        retryArrival = () => { runDeepLink(); };
        /* Measure first. The distances are arithmetic over substation
           coordinates and need no layer control, no dashboard and no
           painted basemap; only the layers need the engine's controls.
           Until v9.54 this awaited arrive() - up to twelve seconds - before
           the measurement was even attempted, and Vikram's West Burton
           journey on a phone showed exactly what that buys: a card, and
           nothing beside it, for long enough to conclude the map is
           broken. The layer switch-on runs alongside and finishes whenever
           the engine is ready. */
        const layersReady = arrive();
        async function runArrivalSelection(arrival, waitForOwnerCard = false,
          expectedArrivalEpoch = epoch) {
          if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
          /* A ref-only arrival already paid for canonical identity, so it can
             briefly yield to that owner's richer card. A supplied coordinate
             arrival must not wait for a card before it can measure: it creates
             the explicit link-provenance card below on the same turn. */
          if (waitForOwnerCard) {
            for (let i = 0; i < 40; i += 1) {
              if (document.querySelector('.maplibregl-popup-content')) break;
              const idStatus = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status;
              if (idStatus === 'FAILED' || idStatus === 'ABSENT') break;
              await new Promise(resolve => setTimeout(resolve, 250));
              if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
            }
          }
          /* The card must exist BEFORE the lines. The popup watcher enforces
             "the lines belong to the card" and clears any drawing standing
             with no card on screen - watched live: a register-absent arrival
             drew five links and the watcher wiped them in the same breath,
             because the fallback card was opened after the measurement.
             ensureArrivalCard is a no-op when a card is already up, so the
             resolved-register path is unchanged. */
          currentRepdRef = arrival.repdRef;
          ensureArrivalCard(arrival.lon, arrival.lat, arrival.name,
            arrival.tech, arrival.stated, arrival.repdRef, arrival.suppliedStatus);
          /* Answer now, measure next. Everything in this block came from
             the made Order and the link; nothing here waits on a network. */
          currentDeclared = provisionalDeclaredConnection(currentRepdRef);
          if (currentDeclared) injectDeclaredOnly();
          try {
            if (capturedMap) setPin(capturedMap,
              [arrival.lon, arrival.lat], arrival.name, arrival.tech);
          }
          catch (_) { /* the measurement will draw it */ }
          link.deep_linked = true;
          const selected = await selectAt([arrival.lon, arrival.lat], arrival.name,
            arrival.tech, false,
            Number.isFinite(arrival.stated) && arrival.stated > 0
              ? arrival.stated : null, expectedArrivalEpoch);
          /* `selected === true`, not `!== false`. selectAt used to return bare
             undefined on two silent paths, and `undefined !== false` is true,
             so a wholly silent arrival reported itself current, runDeepLink
             returned true, and the retry lane recorded RESOLVED for an arrival
             that had measured nothing at all. Those returns are now explicit
             booleans; this reads the success value rather than everything that
             is not the failure value. */
          return selected === true && arrivalGate.isCurrent(expectedArrivalEpoch);
        }
        const firstStarted = performance.now();
        const firstSelectionCurrent = await runArrivalSelection(currentArrival,
          Boolean(repdRef && !identityVerification), epoch);
        if (!firstSelectionCurrent) return;
        link.first_coordinate_answer_ms = Math.round((performance.now() - firstStarted) * 10) / 10;
        link.first_coordinate_origin = link.origin_source;

        if (identityVerification) {
          /* Attach reconciliation only after the supplied-point selection has
             completed. A warm identity can resolve on the first microtask;
             sequencing it here prevents two selections racing each other. */
          continueVerifiedArrival(arrivalGate, epoch, identityVerification,
            async ({ resolved, terminal, error }) => {
            if (!resolved) {
              const ownerState = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link || null;
              const message = error ? String(error?.message || error)
                : String(ownerState?.message || '');
              link.origin_source = terminal === 'NOT_IN_ACTIVE_REGISTER'
                ? 'link-supplied-not-in-active-register'
                : 'link-supplied-register-' + String(terminal).toLowerCase();
              link.deep_link_identity = 'terminal-' + String(terminal).toLowerCase();
              link.identity_verification = {
                status: terminal, repd_ref: repdRef,
                supplied_coordinates_kept: true,
                arrival_fields: {
                  name: currentArrival.name,
                  technology: currentArrival.tech,
                  capacity_mw: Number.isFinite(currentArrival.stated)
                    ? currentArrival.stated : null,
                  supplied_status: currentArrival.suppliedStatus || null
                },
                official_active_register_match: false,
                message: message || null
              };
              markArrivalIdentityState(terminal, repdRef, message);
              if (terminal === 'FAILED') {
                injectStatusStyle();
                retryArrival = retryIdentityOwnerThenArrival;
                showStatus('The active-register identity check failed'
                  + (message ? ': ' + message : '.')
                  + ' The supplied point and measurement remain on the map.',
                  'failed');
              }
              return;
            }

            const rLon = Number(resolved.longitude);
            const rLat = Number(resolved.latitude);
            const resolvedPointUsable = Number.isFinite(rLon) && Number.isFinite(rLat)
              && Math.abs(rLon) <= 180 && Math.abs(rLat) <= 90
              && !(Math.abs(rLon) < 1e-9 && Math.abs(rLat) < 1e-9);
            if (!resolvedPointUsable) {
              link.origin_source = 'link-supplied-register-without-point';
              link.deep_link_identity = 'resolved-without-usable-point';
              link.identity_verification = {
                status: 'RESOLVED_WITHOUT_USABLE_POINT', repd_ref: repdRef,
                supplied_coordinates_kept: true
              };
              return;
            }

            const discrepancyKm = Math.round(
              distanceKm(currentArrival.lon, currentArrival.lat, rLon, rLat) * 1000
            ) / 1000;
            link.origin_discrepancy_km = discrepancyKm;
            link.deep_link_identity = 'resolved-by-search-lane';
            if (discrepancyKm <= 0.001) {
              link.origin_source = 'link-supplied-register-verified';
              markArrivalIdentityState('VERIFIED', repdRef);
              link.identity_verification = {
                status: 'VERIFIED', repd_ref: repdRef,
                discrepancy_km: discrepancyKm, recomputed: false
              };
              return;
            }

            const rTech = typeof resolved.technology === 'string' && resolved.technology
              ? resolved.technology : currentArrival.tech;
            const rName = resolved.name ? String(resolved.name) : currentArrival.name;
            const rCap = Number(resolved.capacity_mw);
            const rStated = Number.isFinite(rCap) && rCap > 0 ? rCap : currentArrival.stated;
            const verifiedArrival = Object.freeze({
              lon: rLon, lat: rLat, name: rName, tech: rTech,
              stated: rStated, repdRef, suppliedStatus: currentArrival.suppliedStatus
            });
            currentArrival = verifiedArrival;
            technologyKnown = isProjectTech(verifiedArrival.tech);
            currentCapacityMw = Number.isFinite(verifiedArrival.stated)
              && verifiedArrival.stated > 0 ? verifiedArrival.stated : null;
            link.origin_source = 'register-corrected-after-link';
            link.identity_verification = {
              status: 'RECOMPUTING', repd_ref: repdRef,
              discrepancy_km: discrepancyKm, recomputed: false
            };
            try {
              map.flyTo({ center: [verifiedArrival.lon, verifiedArrival.lat],
                zoom: zoomUsable ? requestedZoom : 12,
                duration: 800, essential: true });
              await runArrivalSelection(verifiedArrival, false, epoch);
              enableBoth();
              link.identity_verification.status = 'RECOMPUTED';
              link.identity_verification.recomputed = true;
            } catch (reconcileError) {
              link.identity_verification.status = 'RECOMPUTE_FAILED';
              link.identity_verification.message =
                String(reconcileError?.message || reconcileError);
              noteFailure('deep link identity reconciliation: '
                + link.identity_verification.message);
            }
          }).catch((reconcileError) => {
            if (!arrivalGate.isCurrent(epoch)) return;
            link.identity_verification = {
              status: 'RECONCILIATION_FAILED', repd_ref: repdRef,
              supplied_coordinates_kept: true,
              message: String(reconcileError?.message || reconcileError)
            };
            noteFailure('deep link identity reconciliation: '
              + link.identity_verification.message);
          });
        }
        await layersReady;
        return arrivalGate.isCurrent(epoch);
      } catch (error) {
        /* `q` and `tech` are declared inside the try, so they are not in scope
           here and classifyEngine cannot be called - reading them would throw a
           ReferenceError inside the very handler that exists to stop an arrival
           disappearing. The query is still on the URL, so read the class from
           there instead of guessing onshore. */
        let engine = 'onshore';
        try {
          const q2 = new URLSearchParams(window.location.search);
          if (q2.get('interconnector') || String(q2.get('technology') || '') === 'interconnector') engine = 'interconnector';
          else if (coverage.policy(String(q2.get('technology') || ''))?.offshore) engine = 'offshore';
        } catch (_) { engine = 'onshore'; }
        try { answerArrival(engine, false, 'ARRIVAL_THREW', null); } catch (_) {}
        link.failures.push('deep link: ' + String(error?.message || error));
        return false;
      }
    }
    rerunDeepLink = runDeepLink;

    /* THE ARRIVAL MUST NEVER RUN WHILE NOBODY CAN SEE IT, AND MUST NEVER
       BE ONE-SHOT.
       --------------------------------------------------------------------
       Reported live by the architect on his own iPhone, twice, on two
       different projects: menu bar fine, attribution fine, basemap fully
       painted -- and the camera sat at the default UK-wide view, no card,
       no links. Both arrivals were opened from Pipeline News' MAP control,
       which carries target="_blank" on touch devices. An independent audit
       today reproduced the mechanism exactly: a deep link loaded with
       document.hidden === true drew zero layer controls at 40s, the camera
       never left its default position, and it recovered 2.5s after being
       made visible -- because MapLibre's flyTo() and the engine's own
       paint-driven boot both depend on requestAnimationFrame, which iOS
       Safari does not tick in a tab that is not composited. Calling
       map.flyTo() there does not throw and is not a failure this cartridge
       can see: the animation is simply never given a frame to advance, so
       the camera stays exactly where it started, forever, even once the
       tab is later brought to the front -- because this function had
       already run to its own conclusion and nothing called it again.

       So: never START the arrival until the document is actually visible,
       and never leave an arrival that has not produced a visible outcome
       stranded -- run it again the first time the tab is genuinely seen. */
    let arrivalAttempts = 0;
    const MAX_AUTO_ARRIVAL_ATTEMPTS = 5;   // a real, non-visibility failure must still stop retrying
    function arrivalHasVisibleOutcome() {
      // Both already-published, already-relied-upon fields: links_drawn is
      // read the same way by the electron-flow visibility listener just
      // below, and the not-in-active-register message is this cartridge's
      // own genuine "nothing more to show" terminal state.
      /* The sentinel belongs in this test. An offshore farm whose nearest
         substation lies beyond the draw radius is ANSWERED with a real
         distance and a real name, and it draws no line - so links_drawn is 0
         and, before this, every visibilitychange re-ran the whole arrival on a
         question that was already answered, up to five times. An answer is an
         outcome whether or not it put lines on the map. */
      return link.links_drawn > 0
        || link.declared_connection_framed === true
        || link.arrival_engine?.answered === true
        || link.origin_source === 'not-in-active-register-no-supplied-point';
    }
    function attemptArrival() {
      if (document.visibilityState !== 'visible') {
        /* Not a failure - the tab is not composited, so an arrival started here
           would fly a camera that never moves. It is still a state a reader can
           be sitting in, so it is named rather than left blank, and it is
           replaced the moment the tab is genuinely seen. */
        if (!link.arrival_engine) {
          try { answerArrival('onshore', false, 'DEFERRED_FOR_VISIBILITY', null); } catch (_) {}
        }
        return;
      }
      arrivalAttempts += 1;
      link.arrival_attempts = arrivalAttempts;
      void runDeepLink();
    }
    if (document.visibilityState === 'visible') {
      attemptArrival();
    } else {
      link.arrival_deferred_for_visibility = true;
    }
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState !== 'visible') return;
      if (arrivalHasVisibleOutcome()) return;
      if (arrivalAttempts >= MAX_AUTO_ARRIVAL_ATTEMPTS) {
        /* Five attempts spent and still no outcome. The arrival is now
           permanently over, and this is the last chance anything has to say so
           - after this the map simply sits there. */
        try { answerArrival('onshore', false, 'ARRIVAL_ATTEMPTS_EXHAUSTED', null); } catch (_) {}
        return;
      }
      link.arrival_resumed_on_visibility = (link.arrival_resumed_on_visibility || 0) + 1;
      attemptArrival();
    });

    // Escape clears, the way a game HUD does.
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') clearLinks();
    });

    installGbConditions();
    installVersionLedger();
    installMobileTray();

    window.addEventListener('resize', boundCardToMap);
    map.on('resize', boundCardToMap);
    boundCardToMap();

    // A backgrounded tab should not keep an animation frame loop alive.
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) stopAnimation();
      else if (link.links_drawn > 0 && capturedMap) startAnimation(capturedMap);
    });
  }

  /* ── capture the map ─────────────────────────────────────────────────── */

  function attach(map) {
    if (capturedMap) {
      /* A second map was constructed and the arrival is bound to the first.
         Whatever the reader is looking at, it is not the map this engine
         measures on, and that has to be said rather than left as silence. */
      if (!link.arrival_engine) recordArrivalEngine('onshore', false, 'SECOND_MAP_NOT_CAPTURED', null);
      return;
    }
    capturedMap = map;
    link.map_captured = true;
    const boot = () => {
      try { install(map); }
      catch (error) {
        /* install() throwing is the engine failing to exist: the click handler
           and the arrival scheduler are registered inside it, below the throw,
           so nothing downstream will ever answer. Without this the page looks
           like a map that simply found nothing. */
        recordArrivalEngine('onshore', false, 'ENGINE_INSTALL_THREW', null);
        link.failures.push(String(error?.message || error));
      }
      try { installSld(map); }
      catch (error) { link.failures.push('sld: ' + String(error?.message || error)); }
    };
    /* Boot when the style is ready, not when a frame has painted.
       ------------------------------------------------------------------
       This waited on map.once('load'), which maplibre fires only after the
       first frame is on screen -- and that needs basemap tiles. Watched live:
       the CARTO style.json, tiles.json and sprite all returned 200 and then
       not one vector tile was fetched, so the map stayed black, 'load' never
       came, and the whole grid-maths layer never installed. The bare shell
       failed identically, which is how the cartridge was ruled out.

       Nothing here needs a painted frame. Sources and layers need a parsed
       STYLE, and the distances need no map at all: they are arithmetic over
       substation coordinates. Tying them to the basemap made an unrelated CDN
       a single point of failure for the measurement.

       So: whichever of style.load or load arrives first, and failing both, a
       timer. A basemap that never paints is a bad map, not a reason to have
       no maths. */
    if (map.isStyleLoaded?.()) { link.boot_trigger = 'already-loaded'; boot(); }
    else {
      let booted = false;
      const bootOnce = (trigger) => {
        if (booted) return;
        booted = true;
        link.boot_trigger = trigger;
        boot();
      };
      map.once('style.load', () => bootOnce('style.load'));
      map.once('load', () => bootOnce('load'));
      setTimeout(() => {
        // Only if a style is actually there to hang layers on. Booting without
        // one would fail on the first addSource and lose the real reason.
        if (booted) return;
        let hasStyle = false;
        try { hasStyle = Boolean(map.getStyle?.()); } catch (error) { hasStyle = false; }
        if (hasStyle) {
          link.failures.push('basemap never finished painting; booted on the style alone');
          bootOnce('timeout');
        } else {
          /* This is the literal "the engine did not launch": install() is never
             called, so the click handler, the arrival scheduler and the helper
             that would name a failure do not exist. Everything downstream is
             structurally incapable of reporting, which is why this one has to
             be written here, at module scope, by hand. */
          recordArrivalEngine('onshore', false, 'ENGINE_NEVER_INSTALLED_NO_STYLE', null);
          link.failures.push('no style after 8s; the grid maths cannot install');
        }
      }, 8000);
    }
  }

  // The engine keeps its map in a closure and returns nothing, so the only
  // clean handle is the constructor -- and the engine builds its map inside
  // initVentusMap, which runs after this file, so it is still ours to wrap.
  try {
    const gl = window.maplibregl;
    if (gl && typeof gl.Map === 'function' && !gl.Map.__gridatlasNeonWrapped) {
      const OriginalMap = gl.Map;
      function PatchedMap(...args) {
        const instance = new OriginalMap(...args);
        try { attach(instance); }
        catch (error) { link.failures.push(String(error?.message || error)); }
        return instance;
      }
      PatchedMap.prototype = OriginalMap.prototype;
      PatchedMap.__gridatlasNeonWrapped = true;
      Object.setPrototypeOf(PatchedMap, OriginalMap);
      gl.Map = PatchedMap;
    } else if (!gl) {
      link.failures.push('maplibregl unavailable when the neon cartridge loaded');
    }
  } catch (error) {
    link.failures.push(String(error?.message || error));
  }

  /* ══════════════════════════════════════════════════════════════════════
     PART 3 — the SLD sandbox, ported from
     globalgrid2050/solar-bess-topology-v7/gis-sld-financial-sandbox.

     WHAT CHANGED IN THE PORT, AND WHY
     ---------------------------------
     The sandbox is a working engine and the arithmetic below is its
     arithmetic, carried across unchanged. Three things are deliberately
     different.

     1. ONE EARTH RADIUS. The sandbox measures cable length with
        atlasHaversineKm on R = 6378.137 but builds every rectangle, offset
        and projection with turf.destination, whose default is 6371.0088. It
        therefore mixes two radii inside one drawing: a 0.112% disagreement
        between where a thing IS and how far away it is said to be. That is
        the exact defect Ventusltd/grid-distance-maths was created to end.
        The Atlas ships no turf, so every geometric operation here is the
        canonical one on R_ATLAS and the mixture cannot recur.

     2. GRAB, DO NOT MODE-SWITCH. The sandbox moves the array by arming a
        mode and clicking a destination, and edits a route by dropping pins
        and committing them. Here the array is dragged by grabbing it, the
        rotation has a handle on its boundary, and route vertices are
        dragged, inserted on a segment and removed with a double click.
        Everything recomputes live while the pointer is down.

     3. THE ELECTRON FLOW CARRIES THROUGH. The travelling pulse used for the
        substation links runs along the 33 kV collectors and the export cable
        too, in the direction power actually flows: block, to customer
        substation, to grid node.

     WHAT IT STILL IS NOT
     --------------------
     A layout, not a design. Straight-line geometry with no wayleave,
     crossing, terrain, ground condition or consent content, and no
     confirmation that any of it can connect. The caveat block travels with
     it.
     ══════════════════════════════════════════════════════════════════════ */

  const SLD = {
    M2_PER_ACRE: 4046.86,
    BESS_M2_PER_MWH: 85,
    BESS_ASPECT: 2.5,
    BLOCK_SPACING_KM: 0.01,
    BOUNDARY_BUFFER_KM: 0.02,
    ARRAY_OFFSET_KM: 0.2
  };

  const SRC_SLD = 'gridatlas-sld';
  const SLD_LAYERS = {
    boundary: 'l-sld-boundary',
    boundaryLine: 'l-sld-boundary-line',
    block: 'l-sld-block',
    bess: 'l-sld-bess',
    radial: 'l-sld-radial',
    radialFlow: 'l-sld-radial-flow',
    cable: 'l-sld-cable',
    cableGlow: 'l-sld-cable-glow',
    cableFlow: 'l-sld-cable-flow',
    cableFlowB: 'l-sld-cable-flow-b',
    node: 'l-sld-node',
    pin: 'l-sld-pin',
    handle: 'l-sld-handle',
    label: 'l-sld-label'
  };

  // Muted SCADA, same family as the substation links.
  const SLD_COLOUR = {
    boundary: '#3f7fbf',
    block: '#5fbdc2',
    bess: '#b06ac0',
    radial: '#6fb582',
    cable: '#d9963c',
    node: '#e0b050',
    pin: '#bfe9ee',
    handle: '#d8c96a'
  };

  /* Financial inputs are kept per topology because that is how the original
     sandbox works. These are its post-migration defaults: the old HTML stores
     several development values as GBP/MW and migrateFinanceUnitsToWp converts
     them to GBP/Wp before the first calculation. Keeping the converted values
     here makes the units visible and avoids a hidden one-million multiplier. */
  const FINANCE_DEFAULTS = Object.freeze({
    price: 65, other: 0, yield: 1000, bifacial: 5, losses: 2, deg: 0.4,
    opex: 25000, epc_ex: 0.30, flood: false, flood_rate: 0.03,
    modules: 0.15, other_capex: 0.20, fixed_capex: 1500000, cont: 7,
    loss_dc_string: 0, loss_lv_dc: 0, loss_lv_ac: 0, loss_tx: 0,
    loss_other: 0, bess_mw: 0, bess_mwh: 0, bess_capex: 0,
    bess_cycles: 0, bess_spread: 0, bess_eff: 88,
    dev_stage: '0.100', dev_cost_mw: 0.1, dev_module_mwp: 0.15,
    dev_epc_mw: 0.5, dev_owner_mw: 0.1, dev_grid_mw: 0.1,
    dev_exit_mwp: 1.35, dev_npv_mwp: 1.2, dev_success: 15, dev_years: 4,
  });
  const freshFinanceInputs = () => ({ ...FINANCE_DEFAULTS });

  const sld = {
    active: false,
    gridNode: null,          // the substation the scheme connects to
    gridNodeName: '',
    gridNodeVoltage: '',
    arrayCentre: null,       // null = derived from the grid node and array size
    rotationDeg: 0,
    routePins: [],           // user vertices between customer substation and grid node
    stats: null,
    projectName: null,
    // The capacity the register states for this project, and what that figure
    // is taken to mean. REPD does not reliably distinguish, which is why the
    // basis is a user choice and not an assumption.
    targetMw: null,
    targetBasis: 'unstated',
    fitResidualPct: null,
    financeOpen: false,
    cableKm: 0,
    straightKm: 0,
    dragging: null,
    inputs: {
      mode: 'string',
      mod_wp: 660, mod_l: 2.38, mod_w: 1.30, gcr: 0.45, gross_factor: 1.35,
      // 18 strings, which is the ORIGINAL sandbox's own default. It was briefly
    // changed to 23 here on the reasoning that 18 gives a block DC/AC of
    // 0.945 - an array smaller than its inverters. That reasoning was applied
    // without checking the reference, and the reference is explicit: "28
    // string inverters rated at 352 kVA create a skid block of approximately
    // 9,856 kVA BEFORE TRANSFORMER AND GRID LIMITATIONS". Oversizing the
    // inverters against an 8.96 MVA skid is the design, not an error in it.
    // A port does not get to improve its reference by guessing.
    x_mods: 28, z_strings: 18, y_invs: 28, s_subs: 5, b_cols: 6,
      dc_ac_ratio: 1.20, string_inv_kva: 352, string_skid_mva: 8.96,
      // The original has a complete second physical-input set for central
      // topology. Editing one tab must not rewrite the other tab's module,
      // mounting, land or BESS case.
      mod_wp_c: 660, mod_l_c: 2.38, mod_w_c: 1.30, gcr_c: 0.45,
      gross_factor_c: 1.35,
      inv_ac_mw_c: 4.4, inv_dc_mw_c: 5.28, central_skid_mva_c: 4.4,
      x_mods_c: 28, str_per_cb_c: 24, inv_per_mv_c: 1, mv_per_ring_c: 4, rings_c: 4
    },
    finance: {
      string: freshFinanceInputs(),
      central: freshFinanceInputs(),
    }
  };
  window.__GRIDATLAS_SLD__ = sld;

  /* ── geodesy the layout needs, all on R_ATLAS ────────────────────────── */

  /* Both moved into the geodesy module, where the radius lives. Delegated
     here so every existing caller in the layout is untouched. */
  function destinationPoint(lon, lat, km, bearingDeg) {
    return GEODESY.destinationPoint(lon, lat, km, bearingDeg);
  }

  function initialBearingDeg(lon1, lat1, lon2, lat2) {
    return GEODESY.initialBearingDeg(lon1, lat1, lon2, lat2);
  }

  function pathLengthKm(coords) {
    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]);
    }
    return total;
  }

  function normBearing(deg) { return ((deg % 360) + 360) % 360; }

  // Scale factors from the WGS84 radii of curvature at a latitude, so a local
  // tangent plane is correct rather than merely convenient.
  function localScaleKm(latDeg) {
    /* The semi-major axis, taken from the module rather than written again.
       It is the same number as the haversine radius for a good reason - the
       estate measures on the WGS-84 equatorial axis - and writing it twice
       is how the two stop being the same number. */
    const a = R_ATLAS;
    const e2 = (1 / 298.257223563) * (2 - 1 / 298.257223563);
    const s = Math.sin(latDeg * DEG);
    const t = 1 - e2 * s * s;
    return {
      kx: (a / Math.sqrt(t)) * Math.cos(latDeg * DEG) * DEG,
      ky: ((a * (1 - e2)) / t ** 1.5) * DEG
    };
  }

  // Perpendicular distance to a SEGMENT, and the foot of that perpendicular.
  // Measuring to an endpoint instead can only overstate; this is the function
  // whose absence caused the original circuit_km defect, and it is what
  // replaces turf.nearestPointOnLine in the ported layout.
  function distanceToSegmentKm(lon, lat, aLon, aLat, bLon, bLat) {
    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]), foot, t };
  }

  // The sandbox's getRectPolygon, on one radius.
  function rectPolygon(centre, widthKm, lengthKm, rotationDeg) {
    const axis = normBearing(rotationDeg);
    const n = destinationPoint(centre[0], centre[1], lengthKm / 2, axis);
    const s = destinationPoint(centre[0], centre[1], lengthKm / 2, axis + 180);
    const nw = destinationPoint(n[0], n[1], widthKm / 2, axis - 90);
    const ne = destinationPoint(n[0], n[1], widthKm / 2, axis + 90);
    const se = destinationPoint(s[0], s[1], widthKm / 2, axis + 90);
    const sw = destinationPoint(s[0], s[1], widthKm / 2, axis - 90);
    return [[nw, ne, se, sw, nw]];
  }

  // The sandbox uses turf.nearestPointOnLine to drop each block onto the
  // collector trunk. distanceToSegmentKm already returns that foot.
  function footOnSegment(lon, lat, a, b) {
    return distanceToSegmentKm(lon, lat, a[0], a[1], b[0], b[1]).foot;
  }

  /* ── the sizing arithmetic, in its module ────────────────────────────
     Lifted out at 202609012205 into atlas/modules/202609012205-sizing-
     arithmetic.js, proven value-for-value against the last inline copy.
     These delegations keep every caller's name; the module is handed the
     state and the defaults the body used to close over. Absent module:
     fail by name, never quietly compute nothing. */
  const SIZING = (window.__GRIDATLAS_MODULES__ || {}).sizingArithmetic;
  if (!SIZING) throw new Error('sld-sandbox: the sizing-arithmetic module is not composed');
  const { DEVELOPMENT_STAGES, financeNumber } = SIZING;

  function activePhysicalInputs() { return SIZING.physicalInputs(sld.inputs); }
  function applyDevelopmentStageDefaults(financeInputs, stageValue) {
    return SIZING.applyDevelopmentStageDefaults(financeInputs, stageValue);
  }
  function applyMountingBifacial(mode, gcrValue) {
    return SIZING.applyMountingBifacial(sld.finance, mode, gcrValue);
  }
  function computeScreeningFinance(financeInputs, stats) {
    return SIZING.screeningFinance(financeInputs, stats,
      { fallbackMode: sld.inputs.mode, defaults: FINANCE_DEFAULTS });
  }
  const computeSldStats = () => SIZING.computeStats(sld.inputs, sld.finance, FINANCE_DEFAULTS);
  sld.computeFinance = computeScreeningFinance;
  sld.applyDevelopmentStage = applyDevelopmentStageDefaults;
  sld.applyMountingBifacial = applyMountingBifacial;

  function fitToStatedCapacity() { return SIZING.fitToStatedCapacity(sld, computeSldStats); }
  sld.fitToStatedCapacity = fitToStatedCapacity;

  /* ── the layout ──────────────────────────────────────────────────────── */

  function buildLayout() {
    const stats = computeSldStats();
    sld.stats = stats;
    if (!sld.gridNode || stats.total_blocks === 0) {
      return { type: 'FeatureCollection', features: [] };
    }

    const axis = normBearing(sld.rotationDeg);
    const N = stats.total_blocks;
    const cols = Math.ceil(Math.sqrt(N));
    const rows = Math.ceil(N / cols);
    const blockAreaKm2 = stats.block_ground_area_m2 / 1e6;
    const physical = activePhysicalInputs();
    const aspect = physical.gcr === 0.45 ? 1 / 1.4 : physical.gcr === 0.75 ? 1.0 : 1.4;
    const blockW = Math.sqrt(blockAreaKm2 / aspect);
    const blockL = blockW * aspect;
    const gap = SLD.BLOCK_SPACING_KM;
    const gridW = cols * blockW + (cols - 1) * gap;
    const gridL = rows * blockL + (rows - 1) * gap;

    const gridNode = sld.gridNode;
    const offset = gridL / 2 + SLD.ARRAY_OFFSET_KM;
    const centre = sld.arrayCentre
      || destinationPoint(gridNode[0], gridNode[1], offset, axis);
    // The customer substation sits on the array edge nearest the grid node.
    const customerSub = destinationPoint(centre[0], centre[1], gridL / 2, axis + 180);