GLOBALGRID2050 / EXPLORE CODE

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

Electrical Distance and 2 more files

A JavaScript file in the atlas folder of GridAtlas that starts nodes (`startNodes`) (units: kV, MVA), covering transformers and substations.

659 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 523 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. Sizing Arithmetic render · gridatlas / atlas/modules/202609012205-sizing-arithmetic.js lines 443–573
  2. Electrical Distance geodesy · gridatlas / atlas/modules/202609012245-electrical-distance.js lines 1–365
  3. Source Registry render · gridatlas / atlas/modules/202609012245-source-registry.js lines 1–163

Sizing Arithmetic

A JavaScript module in the atlas folder of GridAtlas that builds stats (`buildStats`) and applies development stage defaults (`applyDevelopmentStageDefaults`) and mounting bifacial (`applyMountingBifacial`) (units: MW, MVA, MWh).

rendergridatlas / atlas/modules/202609012205-sizing-arithmetic.js · lines 443–573 of 573 · version 2026-09-01 22:05 (continued from section 522) · pattern screeningFinance (shared by 7 files)

What it does
Defines 12 functions or classes, including physicalInputs, buildStats, consistency, stringStats, centralStats. Side effects: changes the web page (DOM).
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: transformers, cables.
Downstream impact
Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It builds stats (`buildStats`), applies development stage defaults (`applyDevelopmentStageDefaults`) and applies mounting bifacial (`applyMountingBifacial`). The screening arithmetic of the single-line diagram (SLD) sandbox: physical inputs to array statistics, the three named ratios (design, export, headroom), the string and central topologies with their corrected nameplates, the finance port of `gis-sld-v5-finance.js`. Its code works with 4.4 MVA, 352 kVA and 44.8 MW.
Why it matters
Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
Application
gridatlas · atlas/modules · JavaScript module
Uses
none found
Used by
named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
physicalInputs, buildStats, consistency, stringStats, centralStats, financeNumber, applyDevelopmentStageDefaults, applyMountingBifacial, screeningFinance, computeStats, fitToStatedCapacity, oneMore
Defines here
fitToStatedCapacity, oneMore
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/202609012205-sizing-arithmetic.js:443-573 · blob 19cef31fbf8abdd7c1beb5106b56afe091be9916 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
    // whether the capacities agree with each other.
    stats.mode = inputs.mode;
    stats.consistency = consistency(inputs, stats);
    stats.finance = screeningFinance((financeByMode || {})[inputs.mode], stats,
      { fallbackMode: inputs.mode, defaults });
    return stats;
  }

  /**
   * Size the array so its capacity lands on the figure the register states.
   *
   * WHAT IS ADJUSTED, AND WHAT IS NOT
   * Two integer topology counts move -- circuits and skids per circuit in
   * string mode, rings and MV skids per ring in central mode. Everything a
   * supplier fixes stays where the user put it:
   * module rating, string length, inverter and skid ratings. That keeps the
   * result buildable rather than a number reverse-engineered into nonsense.
   *
   * Blocks are integers, so an exact hit is usually impossible. The residual
   * is reported rather than hidden, because a layout that quietly lands 7%
   * off the stated capacity is worse than one that says so.
   *
   * WHICH CAPACITY IS BEING MATCHED
   * That is the caller's declared basis, never a guess. REPD's figure is
   * nominally MWelec, but it is reported inconsistently: some schemes state
   * DC, some AC, and the register does not carry the distinction reliably.
   * Matching AC when the figure was DC oversizes the connection by the DC/AC
   * ratio, which is exactly the error that matters for export limitation.
   */
  /* Fit on two variables, because one cannot reach a small project.
     ----------------------------------------------------------------------
     Reported: the numbers do not change when the headline capacity changes.
     Measured, and they do not:

       string   5, 10, 20, 30, 40, 49.9 and 50 MW all produced 44.80 MW
       central  5, 10 and 20 MW all produced 17.60 MW

     The fit moved ONE variable. In string mode that is b_cols, and because
     total_blocks is b_cols x s_subs with s_subs pinned at five, one step of
     b_cols is five blocks — 44.8 MW at the default skid rating. Nothing below
     that is reachable, so a 30 MW solar farm was drawn as a 44.8 MW one, an
     overstatement of half as much again, and every target under 50 MW
     collapsed onto the same layout. The register starts at 1 MW.

     A block is 8.96 MW in string mode and a skid is 4.4 MVA in central. Those
     are the real quanta, and they are reachable as soon as the inner variable
     is allowed to move too. So the search is over both, and it prefers the
     candidate that stays closest to the shape the user already had — a fit
     that reaches the right capacity by rearranging the whole plant is a worse
     answer than one that reaches it by adding a column.

     Bounds are physical rather than generous: a ring main carries a handful of
     skids, not four hundred, so the inner variable stops at twelve. */
  const FIT_OUTER_MAX = 120;
  const FIT_INNER_MAX = 12;

  function fitToStatedCapacity(sld, computeSldStats) {
    sld.fitResidualPct = null;
    sld.fitQuantumMw = null;
    const target = Number(sld.targetMw);
    if (!Number.isFinite(target) || target <= 0) return;
    if (sld.targetBasis !== 'ac' && sld.targetBasis !== 'dc') return;

    const string = sld.inputs.mode === 'string';
    const outerKey = string ? 'b_cols' : 'rings_c';
    const innerKey = string ? 's_subs' : 'mv_per_ring_c';
    const outer0 = sld.inputs[outerKey];
    const inner0 = sld.inputs[innerKey];

    let best = null;
    for (let inner = 1; inner <= FIT_INNER_MAX; inner += 1) {
      sld.inputs[innerKey] = inner;
      for (let outer = 1; outer <= FIT_OUTER_MAX; outer += 1) {
        sld.inputs[outerKey] = outer;
        const s = computeSldStats();
        const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
        if (!Number.isFinite(got) || got <= 0) continue;
        const error = Math.abs(got - target);
        // Ties, and near-ties, go to the layout closest to the one already on
        // screen. Without this the fit rearranges the plant for a rounding
        // difference and the drawing jumps for no reason the user can see.
        const drift = Math.abs(inner - inner0) + Math.abs(outer - outer0) / 100;
        if (!best
            || error < best.error - 1e-9
            || (Math.abs(error - best.error) <= 1e-9 && drift < best.drift)) {
          best = { outer, inner, error, got, drift };
        }
      }
    }
    if (!best) {
      sld.inputs[outerKey] = outer0;
      sld.inputs[innerKey] = inner0;
      return;
    }
    sld.inputs[outerKey] = best.outer;
    sld.inputs[innerKey] = best.inner;
    sld.fitResidualPct = ((best.got - target) / target) * 100;

    // What one more block would have added. A residual means nothing without
    // it: 10% off a plant whose smallest step is 9 MW is exact, and 10% off
    // one whose step is 0.5 MW is a miss.
    const oneMore = (() => {
      sld.inputs[outerKey] = best.outer + 1;
      const s = computeSldStats();
      sld.inputs[outerKey] = best.outer;
      const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
      return Number.isFinite(got) ? Math.abs(got - best.got) : null;
    })();
    sld.fitQuantumMw = oneMore;
  }

  NS.sizingArithmetic = Object.freeze({
    generation: '202609012205',
    DEVELOPMENT_STAGES,
    DEVELOPMENT_SUCCESS,
    BIFACIAL_BY_GCR,
    FIT_OUTER_MAX,
    FIT_INNER_MAX,
    financeNumber,
    physicalInputs,
    buildStats,
    consistency,
    stringStats,
    centralStats,
    applyDevelopmentStageDefaults,
    applyMountingBifacial,
    screeningFinance,
    computeStats,
    fitToStatedCapacity
  });
})();

Electrical Distance

A JavaScript file in the atlas folder of GridAtlas that starts nodes (`startNodes`) (units: kV, MVA), covering transformers and substations.

geodesygridatlas / atlas/modules/202609012245-electrical-distance.js · lines 1–365 of 365 · version 2026-09-01 22:45 · pattern startNodes (shared by 10 files)

What it does
It lists and searches transformers and substations. Defines 6 functions or classes, including crossing, describe, legality, startNodes, between. Side effects: changes the web page (DOM).
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: transformers, substations.
Downstream impact
Used directly by 3 files: Route Plan Test (gridatlas); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Genome Workflow (ventus-grid-engine).
What it achieves
It starts nodes (`startNodes`) and is built from the crossing step (`crossing`) and the describe step (`describe`). How far away a substation is, measured in the network operator's own published circuits rather than in kilometres. Its code works with 100 MVA.
Why it matters
Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine. Checked by Route Plan Test.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
referenced by Route Plan Test (new URL import.meta.url), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
crossing, describe, legality, startNodes, between, within
Defines here
crossing, describe, legality, startNodes, between, within
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/202609012245-electrical-distance.js:1-365 · blob fa28aad7c034e26e7bc3a23350c158fd31d7df41 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
 * Module: electrical-distance
 *
 * How far away a substation is, measured in the network operator's own
 * published circuits rather than in kilometres.
 *
 * WHY THIS EXISTS
 * ---------------
 * Everything this estate has measured until now has been geometry. The
 * geodesy module answers "how many kilometres from this project to that
 * substation", and it answers it correctly, to the last place. But a
 * kilometre is not a connection. Two substations 7 km apart can be on
 * opposite sides of a network boundary with no circuit between them; two
 * substations 90 km apart can be the two ends of a single published
 * circuit. A map that shows only the first number invites the reader to
 * infer the second, and that inference is wrong often enough to be
 * dangerous in a document someone spends money on.
 *
 * So this module answers a different question, from a different source:
 * on the network Appendix B actually publishes, how many circuits lie
 * between these two sites, and which ones? Every hop is a published row
 * with an identity. The answer is a citation, not an estimate.
 *
 * WHAT IT IS NOT
 * --------------
 * A hop count is not a distance. Two hops is not "twice as far" as one,
 * and a site one hop away is not thereby available to connect to. It is
 * not an impedance either: R, X and B are carried on every hop exactly as
 * published, and this module contains no arithmetic over them at all -
 * summing impedance along a path is the first step of a load flow, and a
 * load flow needs a declared model, base values, taps, generation and load
 * assumptions, contingencies and validation against a trusted solver. None
 * of those are in this file, so neither is the sum.
 *
 * THE ONE RULE THAT SHAPES THE TRAVERSAL
 * --------------------------------------
 * A voltage may only change across a transformer, and when it does the
 * transformer is named in the path. A circuit whose two ends carry
 * different declared voltages is not a voltage change - it is a
 * contradiction in the data, and the traversal refuses it and says so
 * rather than quietly walking through. Undeclared voltages are carried as
 * undeclared and never guessed from a node code.
 *
 *   node tools/proofs/modules/202609012245-electrical-distance.proof.mjs
 */
(() => {
  const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
  if (NS.electricalDistance) return;

  const SCHEMA = 'gridatlas.module.electrical-distance.v1';
  const REQUIRES = 'gridatlas.module.network-topology.graph.v1';

  const NOT_A_DISTANCE =
    'Hops are published circuits between two sites, not a distance. A site '
    + 'one hop away may be a hundred kilometres away, and a site ten '
    + 'kilometres away may be on no shared circuit at all.';

  const NOT_A_CAPACITY =
    'A path existing on the published network says nothing about whether '
    + 'anything can flow along it for a new project. Ratings are the '
    + 'circuit\'s, not a spare allowance, and queue position, committed '
    + 'connections, consent and commercial terms appear in no appendix.';

  const IMPEDANCE_CARRIED =
    'R, X and B are reproduced on each hop exactly as published, on a '
    + '100 MVA base. They are not added, scaled or combined anywhere in '
    + 'this module. A sum of them would be the beginning of a load flow, '
    + 'which needs a declared model this data does not contain.';

  const UNDECLARED = 'undeclared';

  /* A traversal must not invent a voltage, so the two ends of an edge are
     compared only when BOTH are declared. */
  function crossing(graph, nearNode, farNode) {
    const near = graph.nodeVoltageKv(nearNode);
    const far = graph.nodeVoltageKv(farNode);
    return {
      near_kv: near,
      far_kv: far,
      both_declared: near != null && far != null,
      changes: near != null && far != null && near !== far
    };
  }

  function describe(graph, entry, nearNode) {
    const farNode = entry.row[entry.far];
    const cross = crossing(graph, nearNode, farNode);
    return {
      kind: entry.kind,
      from_node: nearNode,
      to_node: farNode,
      from_site_code: graph.nodeSiteCode(nearNode) || null,
      to_site_code: graph.nodeSiteCode(farNode) || null,
      from_voltage_kv: cross.near_kv,
      to_voltage_kv: cross.far_kv,
      voltage_changed: cross.changes,
      /* The transformer's own published ratio, where it has one. Only 140
         of 1,472 transformers carry it, so it is reported when present and
         never reconstructed from the two node voltages when absent - a
         reconstructed ratio would be this module's opinion wearing the
         product's authority. */
      voltage_ratio_kv: entry.kind === 'transformer'
        && typeof entry.row.voltage_ratio_kv === 'string'
        ? entry.row.voltage_ratio_kv : null,
      /* carried, never computed with */
      ratings_mva: graph.ratingsOf(entry.row),
      transformer_rating_mva: entry.kind === 'transformer'
        && Number.isFinite(entry.row.rating_mva) ? entry.row.rating_mva : null,
      parameters_pct_100mva: graph.parametersOf(entry.row)
    };
  }

  /**
   * Is this edge legal to walk?
   *
   * A transformer is the only thing that may change voltage. A circuit
   * that appears to change voltage is a contradiction between two
   * published node records, and it is refused and reported rather than
   * traversed - a silent walk through it would mix voltages, which is the
   * exact failure this estate holds itself to never repeating.
   */
  function legality(kind, cross) {
    if (!cross.changes) return { legal: true, refusal: null };
    if (kind === 'transformer') return { legal: true, refusal: null };
    return {
      legal: false,
      refusal: 'a ' + kind + ' whose two ends carry different declared '
        + 'voltages (' + cross.near_kv + ' kV and ' + cross.far_kv + ' kV); '
        + 'only a transformer may change voltage, so this edge is not walked'
    };
  }

  function startNodes(graph, site, voltageKv) {
    const nodes = graph.nodesOfSite(site.code);
    if (voltageKv == null) return nodes;
    return nodes.filter((name) => graph.nodeVoltageKv(name) === voltageKv);
  }

  /**
   * The shortest published path between two sites, in circuits.
   *
   * Breadth-first, so the first arrival is a fewest-hop path. Where
   * several paths tie, the one found first by sorted node order is
   * returned and `ties` says how many others arrived at the same depth,
   * because "the" path implies a uniqueness the network does not have.
   *
   * @param index      a network-topology index (must expose graph())
   * @param fromKey    site code or exact site name
   * @param toKey      site code or exact site name
   * @param options    { voltageKv, maxHops }
   * @returns a result object, or null if either site is unknown
   */
  function between(index, fromKey, toKey, options) {
    if (!index || typeof index.graph !== 'function') return null;
    const graph = index.graph();
    if (!graph || graph.schema !== REQUIRES) return null;

    const from = index.site(fromKey);
    const to = index.site(toKey);
    if (!from || !to) return null;

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

    const targets = new Set(graph.nodesOfSite(to.code));
    const origins = startNodes(graph, from, voltageKv);

    const base = {
      schema: SCHEMA,
      from: { code: from.code, name: from.name },
      to: { code: to.code, name: to.name },
      requested_voltage_kv: voltageKv,
      max_hops: maxHops,
      not_a_distance: NOT_A_DISTANCE,
      not_a_capacity: NOT_A_CAPACITY,
      impedance_basis: IMPEDANCE_CARRIED
    };

    if (!origins.length) {
      return Object.assign({}, base, {
        reached: false,
        reason: voltageKv == null
          ? 'the origin site publishes no nodes in this product'
          : 'the origin site publishes no node at ' + voltageKv + ' kV',
        hops: null, path: [], refusals: [], ties: 0, explored_nodes: 0
      });
    }

    if (from.code === to.code) {
      return Object.assign({}, base, {
        reached: true, hops: 0, path: [], refusals: [], ties: 0,
        explored_nodes: origins.length,
        reason: 'the same site'
      });
    }

    const seen = new Map();
    const refusals = [];
    let frontier = [];
    for (const name of origins.slice().sort()) {
      if (targets.has(name)) {
        return Object.assign({}, base, {
          reached: true, hops: 0, path: [], refusals: [], ties: 0,
          explored_nodes: 1,
          reason: 'both site codes resolve to the same node'
        });
      }
      seen.set(name, null);
      frontier.push(name);
    }

    for (let depth = 1; depth <= maxHops; depth += 1) {
      const next = [];
      const arrivals = [];
      for (const nearNode of frontier) {
        for (const entry of graph.edgesAt(nearNode)) {
          const farNode = entry.row[entry.far];
          if (!farNode || !graph.has(farNode)) continue;
          const cross = crossing(graph, nearNode, farNode);
          const verdict = legality(entry.kind, cross);
          if (!verdict.legal) {
            refusals.push({
              at_node: nearNode, to_node: farNode,
              kind: entry.kind, reason: verdict.refusal
            });
            continue;
          }
          if (seen.has(farNode)) continue;
          seen.set(farNode, { via: entry, from: nearNode });
          if (targets.has(farNode)) arrivals.push(farNode);
          else next.push(farNode);
        }
      }

      if (arrivals.length) {
        arrivals.sort();
        const path = [];
        let cursor = arrivals[0];
        while (cursor) {
          const step = seen.get(cursor);
          if (!step) break;
          path.unshift(describe(graph, step.via, step.from));
          cursor = step.from;
        }
        return Object.assign({}, base, {
          reached: true,
          hops: path.length,
          path,
          transformers_crossed: path.filter((h) => h.kind === 'transformer').length,
          voltage_changes: path.filter((h) => h.voltage_changed).length,
          ties: arrivals.length - 1,
          refusals,
          explored_nodes: seen.size,
          arrival_node: arrivals[0]
        });
      }

      if (!next.length) break;
      frontier = next.sort();
    }

    return Object.assign({}, base, {
      reached: false,
      reason: 'no published path within ' + maxHops + ' hops'
        + (voltageKv == null ? '' : ' from a ' + voltageKv + ' kV node')
        + '; this is a statement about the published network, not about '
        + 'whether the two sites are connected in reality',
      hops: null, path: [], refusals, ties: 0, explored_nodes: seen.size
    });
  }

  /**
   * Every site reachable within N hops, with the hop count at which it was
   * first reached. The neighbourhood a click is actually in, electrically.
   *
   * @param index    a network-topology index
   * @param key      site code or exact site name
   * @param options  { hops, voltageKv }
   */
  function within(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 limit = Number.isFinite(opts.hops) ? opts.hops : 2;

    const origins = startNodes(graph, site, voltageKv);
    const seen = new Set(origins);
    const bySite = new Map();
    const refusals = [];
    let frontier = origins.slice().sort();

    for (let depth = 1; depth <= limit; depth += 1) {
      const next = [];
      for (const nearNode of frontier) {
        for (const entry of graph.edgesAt(nearNode)) {
          const farNode = entry.row[entry.far];
          if (!farNode || !graph.has(farNode) || seen.has(farNode)) continue;
          const cross = crossing(graph, nearNode, farNode);
          const verdict = legality(entry.kind, cross);
          if (!verdict.legal) {
            refusals.push({ at_node: nearNode, to_node: farNode,
              kind: entry.kind, reason: verdict.refusal });
            continue;
          }
          seen.add(farNode);
          next.push(farNode);
          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
  });
})();

Source Registry

A JavaScript file in the atlas folder of GridAtlas covering substations and transformers. It is built from the survey step (`survey`) and the ready step (`ready`).

rendergridatlas / atlas/modules/202609012245-source-registry.js · lines 1–163 of 163 · version 2026-09-01 22:45 · Not reached from any entry point (candidate for review) · pattern survey (shared by 9 files)

What it does
It lists and searches substations and transformers. Defines survey, ready. Side effects: changes the web page (DOM).
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: substations, transformers.
What it achieves
"Click anywhere on a map and the neons that already work via Pipeline News look for cartridges and code." — Vikram, .
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
survey, ready
Defines here
survey, ready
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202609012245-source-registry.js:1-163 · blob d282443dac625724b4d04aaeb39cc72d251f00cd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Module: source-registry
 *
 * "Click anywhere on a map and the neons that already work via Pipeline News
 * look for cartridges and code." — Vikram, 2026-09-01.
 *
 * The looking is this module. The Atlas is a composition of cartridges that
 * find each other through `window.__GRIDATLAS_*` globals, and the deep scan
 * of 1 Sep 2026 found fifteen such surfaces ever registered, thirteen live,
 * and nothing anywhere that documents them. Every consumer therefore does
 * its own `window.__GRIDATLAS_NETWORK__?.something` and quietly does less
 * when the answer is undefined. That is how a click on blank space came to
 * report only what OpenStreetMap has mapped, while the cartridge holding
 * NESO's 886 published connection points sat loaded in the same page.
 *
 * So: one registry, declared once, that answers three questions.
 *
 *   WHAT COULD ANSWER      the sources this estate knows about, each with
 *                          what it contributes and whether it is required.
 *   WHAT IS ANSWERING NOW  probed live, by looking for the surface AND the
 *                          specific capability, because a cartridge that
 *                          has loaded but not yet fetched is present and
 *                          not yet useful, and those are different states.
 *   WHAT DID NOT           named, with the reason, in the result itself.
 *
 * The third is the point. A reader who is told "3 of 4 sources answered;
 * NESO's published network did not, because its payload had not loaded" can
 * judge the answer. A reader shown a shorter answer cannot, and will
 * reasonably assume the map has told them everything it knows.
 *
 * It reads. It never fetches, never renders, and never decides what a
 * finding means.
 *
 * Depends on: nothing.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.sourceRegistry) return;

  /* The registry is DECLARED, not discovered by scanning window.
     ----------------------------------------------------------------------
     Enumerating every __GRIDATLAS_* global would report whatever happens to
     be there, including surfaces this estate has never agreed to consume,
     and would silently start using a new one the day someone adds it. A
     declared list is a contract: adding a source is an edit here, with a
     reason, and a proof that the probe actually works. */
  const SOURCES = [
    {
      id: 'map',
      surface: '__GRIDATLAS_V9_MAP__',
      contributes: 'the map itself: where the click happened, and what is drawn',
      probe: (w) => (w.__GRIDATLAS_V9_MAP__ ? 'ready' : 'absent')
    },
    {
      id: 'mapped-substations',
      surface: '__GRIDATLAS_NEON_LINKS__',
      contributes: 'substations as OpenStreetMap has them mapped, and the '
        + 'measurement the neon links already use',
      probe: (w) => {
        const links = w.__GRIDATLAS_NEON_LINKS__;
        if (!links) return 'absent';
        if (typeof links.measure?.distanceKm !== 'function') return 'loaded, cannot measure';
        if (!links.substations_loaded) return 'loaded, no substations yet';
        return 'ready';
      },
      detail: (w) => ({ substations: w.__GRIDATLAS_NEON_LINKS__?.substations_loaded || 0 })
    },
    {
      id: 'neso-connection-points',
      surface: '__GRIDATLAS_NETWORK__',
      contributes: "NESO's published connection points: circuits, transformers, "
        + 'per-voltage fault current and planned changes',
      probe: (w) => {
        const network = w.__GRIDATLAS_NETWORK__;
        if (!network) return 'absent';
        if (network.failed) return 'failed to load';
        if (!network.loaded) return 'loading';
        return 'ready';
      },
      detail: (w) => ({ connection_points: w.__GRIDATLAS_NETWORK__?.count || null,
        schema: w.__GRIDATLAS_NETWORK__?.schema || null })
    },
    {
      id: 'grid-scope',
      surface: '__GRIDATLAS_MODULES__.gridScope',
      contributes: 'the census of what is mapped around a point, in distance bands',
      probe: (w) => (w.__GRIDATLAS_MODULES__?.gridScope ? 'ready' : 'absent')
    },
    {
      id: 'network-topology',
      surface: '__GRIDATLAS_MODULES__.networkTopology',
      contributes: 'circuits, transformers, planned changes and neighbouring '
        + 'sites at a named substation, per voltage',
      probe: (w) => (w.__GRIDATLAS_MODULES__?.networkTopology ? 'ready' : 'absent')
    },
    {
      id: 'declared-connections',
      surface: '__GRIDATLAS_SLD__.declared',
      contributes: 'points of connection bound to a made Order or a published '
        + 'planning document',
      probe: (w) => (w.__GRIDATLAS_SLD__?.declared ? 'ready' : 'absent')
    }
  ];

  const READY = 'ready';

  /**
   * Probe every declared source against a window.
   * @param scope  the window to read; defaults to this one. Passing it in is
   *               what lets a proof drive the probe without a browser.
   */
  function survey(scope) {
    const w = scope || window;
    const sources = SOURCES.map((source) => {
      let state = 'absent';
      let detail = null;
      try { state = source.probe(w) || 'absent'; }
      catch (error) { state = `probe threw: ${error && error.message}`; }
      if (state === READY && typeof source.detail === 'function') {
        try { detail = source.detail(w); } catch (_) { detail = null; }
      }
      return { id: source.id, surface: source.surface,
        contributes: source.contributes, state, ready: state === READY, detail };
    });

    const ready = sources.filter(s => s.ready);
    const missing = sources.filter(s => !s.ready);

    return {
      schema: 'gridatlas.module.source-registry.v1',
      sources,
      ready: ready.map(s => s.id),
      missing: missing.map(s => ({ id: s.id, state: s.state })),
      counts: { declared: sources.length, ready: ready.length, missing: missing.length },
      /* Written as a sentence here so a card cannot compose its own and get
         it wrong, and so an absence is never presented as an absence in the
         world rather than in this page. */
      sentence: missing.length === 0
        ? `All ${sources.length} sources answered.`
        : `${ready.length} of ${sources.length} sources answered. Not answering: `
          + missing.map(s => `${s.id} (${s.state})`).join(', ')
          + '. What they would have added is missing from this answer, not '
          + 'absent from the world.'
    };
  }

  /** Is one source usable right now. */
  function ready(id, scope) {
    const source = SOURCES.find(s => s.id === id);
    if (!source) return false;
    try { return source.probe(scope || window) === READY; }
    catch (_) { return false; }
  }

  NS.sourceRegistry = Object.freeze({
    schema: 'gridatlas.module.source-registry.v1',
    declared: SOURCES.map(s => s.id),
    survey,
    ready
  });
})();