GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/labs/lightning-grid

Map View and 2 more files

A JavaScript module in the lightning grid folder of GridAtlas that maps optical observations, optical clusters, optical cluster tap and optical dots. Served with the page at https://gridatlas.globalgrid2050.com/atlas/labs/lightning-grid/.

525 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 521 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. Map View render · gridatlas / atlas/labs/lightning-grid/map-view.mjs lines 1–215
  2. Geodesy geodesy · gridatlas / atlas/modules/202609011950-geodesy.js lines 1–145
  3. Grid Scope render · gridatlas / atlas/modules/202609012040-grid-scope.js lines 1–165

Map View

A JavaScript module in the lightning grid folder of GridAtlas that maps optical observations, optical clusters, optical cluster tap and optical dots. Served with the page at https://gridatlas.globalgrid2050.com/atlas/labs/lightning-grid/.

rendergridatlas / atlas/labs/lightning-grid/map-view.mjs · lines 1–215 of 215 · pattern blank (shared by 4 files)

What it does
It maps optical observations, optical clusters, optical cluster tap and optical dots. Defines 10 functions or classes, including blank, ref, checkedFeature, number, initLightningMap. 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.
Downstream impact
Used directly by 1 file: Labs — Lightning Grid (gridatlas, https://gridatlas.globalgrid2050.com/atlas/labs/lightning-grid/). Reached from 1 other entry point, including Labs — Lightning Grid Page (gridatlas, https://gridatlas.globalgrid2050.com/atlas/labs/lightning-grid/).
What it achieves
It adds sources layers (`addSourcesAndLayers`), paints selection (`paintSelection`) and paints context (`paintContext`). Optical-flash map view for the standalone Lightning → Grid laboratory.
Why it matters
Imported by Labs — Lightning Grid.
Application
gridatlas · atlas/labs/lightning-grid · JavaScript module
Uses
none found
Used by
imported by Labs — Lightning Grid (import)
Produces
initLightningMap
Defines here
blank, ref, checkedFeature, number, initLightningMap, addSourcesAndLayers, paint, paintSelection, paintContext, fit
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/labs/lightning-grid/map-view.mjs:1-215 · blob 3b2343e7bb45ebba52aeebb008c0f771ac5087f0 · 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
/**
 * Optical-flash map view for the standalone Lightning → Grid laboratory.
 *
 * This is NOT a patch to the original Atlas map. It is an isolated map on a
 * different page, with a real 44 CSS-pixel target for every visible flash.
 * Click selection calls the imported Ventus Grid Engine through app.mjs.
 * Never infer a ground strike, connection or damage from these coordinates.
 */
const blank=()=>({type:'FeatureCollection',features:[]});
const ref=(p)=>Number.isFinite(p?.[0])&&Number.isFinite(p?.[1])
  && Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
const checkedFeature=f=>f?.type==='Feature' && f?.geometry?.type==='Point'
  && ref(f.geometry.coordinates) && f.id!=null
  && f.properties?.observation_kind==='optical_lightning_flash';
const number=n=>Number(n).toLocaleString('en-GB');
const notice='Optical positions only. Nearest assets are not necessarily connected, hit or damaged.';

export function initLightningMap({onPick,onStatus=()=>{},onError=()=>{}}={}) {
  if(typeof onPick!=='function')throw new TypeError('Map must have a genuine observation selection callback');
  if(!globalThis.maplibregl?.Map)throw new Error('MapLibre library unavailable. Use the accessible UTC dropdown below.');
  const lib=globalThis.maplibregl;
  const map=new lib.Map({
    container:'flash-map',center:[-3.5,54.5],zoom:5.3,minZoom:2,maxZoom:17,
    attributionControl:true,
    style:{
      version:8,name:'Dark UK context (CARTO / OSM)',
      sources:{
        'carto-dark':{type:'raster',
          tiles:['https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png'],
          tileSize:256,
          attribution:'© OpenStreetMap contributors · © CARTO'}
      },
      layers:[{id:'dark-basemap',type:'raster',source:'carto-dark'}]
    }
  });
  map.addControl(new lib.NavigationControl({showCompass:false}),'top-right');

  let ready=false;
  let events=[],selection=null,context=null;
  let popup=null;
  const solarById=new Map(),subsById=new Map();

  function addSourcesAndLayers(){
    if(ready)return;
    map.addSource('optical-observations',{type:'geojson',data:blank(),cluster:true,
      clusterRadius:42,clusterMaxZoom:10});
    map.addLayer({id:'optical-clusters',type:'circle',source:'optical-observations',
      filter:['has','point_count'],
      paint:{'circle-radius':['step',['get','point_count'],14,10,18,100,23,1000,27],
        'circle-color':'#e4a523','circle-stroke-color':'#15202b','circle-stroke-width':2}});
    // Count-scaled cluster circles require no external glyph URL. Tap to expand.
    map.addLayer({id:'optical-cluster-tap',type:'circle',source:'optical-observations',
      filter:['has','point_count'],paint:{'circle-radius':24,'circle-opacity':0.01}});
    map.addLayer({id:'optical-dots',type:'circle',source:'optical-observations',
      filter:['!',['has','point_count']],
      paint:{'circle-radius':['interpolate',['linear'],['zoom'],4,7,7,10,10,13,15,17],
        'circle-color':'#fff2ad','circle-stroke-color':'#18242b',
        'circle-stroke-width':1.5,'circle-opacity':0.97}});
    // 22px RADIUS = 44 CSS px DIAMETER. Transparent hit layer remains
    // hit-testable on mobile; a dropdown provides keyboard access.
    map.addLayer({id:'optical-flash-tap',type:'circle',source:'optical-observations',
      filter:['!',['has','point_count']],
      paint:{'circle-radius':22,'circle-opacity':0.01}});
    map.addSource('selected-optical',{type:'geojson',data:blank()});
    map.addLayer({id:'selected-optical-ring',type:'circle',source:'selected-optical',
      paint:{'circle-radius':24,'circle-color':'#ffffff','circle-opacity':0,
        'circle-stroke-color':'#ffffff','circle-stroke-width':3,'circle-stroke-opacity':1}});
    map.addSource('nearby-solar',{type:'geojson',data:blank()});
    map.addLayer({id:'nearby-solar-capacity',type:'circle',source:'nearby-solar',
      paint:{'circle-radius':['get','marker_radius_px'],
        'circle-color':'#43e3ab','circle-stroke-color':'#0c2020','circle-stroke-width':2,
        'circle-opacity':0.85}});
    map.addLayer({id:'nearby-solar-tap',type:'circle',source:'nearby-solar',
      paint:{'circle-radius':22,'circle-opacity':0.01}});
    map.addSource('nearest-substations',{type:'geojson',data:blank()});
    map.addLayer({id:'nearest-substation-dots',type:'circle',source:'nearest-substations',
      paint:{'circle-radius':7,'circle-color':'#83acff','circle-stroke-color':'#102038',
        'circle-stroke-width':2}});
    map.addLayer({id:'nearest-substation-tap',type:'circle',source:'nearest-substations',
      paint:{'circle-radius':22,'circle-opacity':0.01}});

    map.on('click','optical-flash-tap',event=>{
      const id=event.features?.[0]?.properties?.flash_id;
      if(id==null)return;
      const match=events.find(f=>String(f.id)===String(id));
      if(match)onPick(String(match.id)); // App callback selects & computes
    });
    map.on('click','optical-cluster-tap',event=>{
      const group=event.features?.[0];
      const id=group?.properties?.cluster_id;
      if(id==null)return;
      map.getSource('optical-observations')?.getClusterExpansionZoom(id,(error,zoom)=>{
        if(error){onError(error.message);return}
        map.easeTo({center:group.geometry.coordinates,zoom:Math.min(17,zoom),duration:550});
      });
    });
    map.on('click','nearby-solar-tap',event=>{
      const refId=String(event.features?.[0]?.properties?.repd_ref??'');
      const p=solarById.get(refId);
      if(!p)return;
      const panel=document.createElement('div');
      const headline=document.createElement('strong');headline.textContent=p.name;
      panel.append(headline);
      const description=document.createElement('p');
      description.textContent=number(p.km)+' km from selected optical position · '+
        (p.capacity_mw==null?'capacity not recorded':number(p.capacity_mw)+' MW recorded')+
        ' · no strike or damage implied.';
      panel.append(description);
      const link=document.createElement('a');
      link.textContent='Open existing GridAtlas MAP project';
      link.href=p.gridatlas_project_url;
      link.target='_blank';link.rel='noopener noreferrer';
      panel.append(link);
      popup?.remove();
      popup=new lib.Popup({closeButton:true,closeOnClick:true})
        .setLngLat([p.location.lon,p.location.lat]).setDOMContent(panel).addTo(map);
    });
    map.on('click','nearest-substation-tap',event=>{
      const id=String(event.features?.[0]?.properties?.item_id??'');
      const p=subsById.get(id);
      if(!p)return;
      const panel=document.createElement('div');
      const headline=document.createElement('strong');
      headline.textContent=p.name||'Unnamed mapped substation';panel.append(headline);
      const para=document.createElement('p');
      para.textContent=number(p.km)+' km from selected optical point · '+
        (p.voltages_kv||[]).map(x=>x+' kV').join(', ') +
        '. Straight-line only; no confirmed electrical connection.';
      panel.append(para);
      popup?.remove();
      popup=new lib.Popup({closeButton:true,closeOnClick:true})
        .setLngLat([p.location.lon,p.location.lat]).setDOMContent(panel).addTo(map);
    });
    const interactive=['optical-flash-tap','optical-cluster-tap',
      'nearby-solar-tap','nearest-substation-tap'];
    for(const layer of interactive){
      map.on('mouseenter',layer,()=>map.getCanvas().style.cursor='pointer');
      map.on('mouseleave',layer,()=>map.getCanvas().style.cursor='');
    }
    ready=true;
    paint();
    onStatus('Map ready: '+number(events.length)+' genuine optical flashes. Yellow dots have a 44 px tap target. '+notice);
  }

  function paint(){
    if(!ready)return;
    const data=events.filter(checkedFeature).map(f=>({
      type:'Feature',geometry:{type:'Point',coordinates:f.geometry.coordinates.slice(0,2)},
      properties:{flash_id:String(f.id),time_utc:f.properties.time_utc}
    }));
    map.getSource('optical-observations').setData({type:'FeatureCollection',features:data});
    paintSelection();
    paintContext();
  }
  function paintSelection(){
    if(!ready)return;
    const data=selection&&checkedFeature(selection)
      ?{type:'FeatureCollection',features:[{type:'Feature',geometry:selection.geometry,
        properties:{flash_id:String(selection.id)}}]}:blank();
    map.getSource('selected-optical').setData(data);
  }
  function paintContext(){
    if(!ready)return;
    solarById.clear();subsById.clear();
    const solar=[],subs=[];
    for(const p of context?.nearby_solar||[]){
      const coords=[p.location?.lon,p.location?.lat];
      if(!ref(coords)||!p.repd_ref)continue;
      solarById.set(String(p.repd_ref),p);
      solar.push({type:'Feature',geometry:{type:'Point',coordinates:coords},
        properties:{repd_ref:String(p.repd_ref),marker_radius_px:p.marker_radius_px}});
    }
    for(const [i,p] of (context?.substations||[]).entries()){
      const coords=[p.location?.lon,p.location?.lat];
      if(!ref(coords))continue;
      const id=String(i);
      subsById.set(id,p);
      subs.push({type:'Feature',geometry:{type:'Point',coordinates:coords},
        properties:{item_id:id}});
    }
    map.getSource('nearby-solar').setData({type:'FeatureCollection',features:solar});
    map.getSource('nearest-substations').setData({type:'FeatureCollection',features:subs});
  }
  function fit(features,padding=40){
    if(!ready){onStatus('Map is still loading.');return}
    const coords=features.map(f=>f?.geometry?.coordinates).filter(ref);
    if(!coords.length){onStatus('No valid coordinates to fit; no camera move.');return}
    if(coords.length===1){map.easeTo({center:coords[0],zoom:8,duration:650});return}
    const bounds=new lib.LngLatBounds(coords[0],coords[0]);
    coords.forEach(c=>bounds.extend(c));
    map.fitBounds(bounds,{padding,maxZoom:9,duration:650});
  }
  map.once('load',addSourcesAndLayers);
  map.on('error',e=>onError('Map tiles or rendering: '+String(e.error?.message||'unknown error')));
  return Object.freeze({
    setObservations(rows){
      events=Array.isArray(rows)?rows.filter(checkedFeature).slice(0,40000):[];
      paint();
      return events.length;
    },
    selectFlash(f){
      selection=checkedFeature(f)?f:null;
      // No auto-flying or zooming: owner must press Fit selection.
      context=null;
      popup?.remove();popup=null;
      paintSelection();paintContext();
    },
    setContext(c){context=c||null;paintContext()},
    clearContext(){context=null;paintContext()},
    fitFlashes(){fit(events)},
    fitSelection(){fit(selection?[selection]:[])},
    getBounds(){return ready?map.getBounds():null},
    isReady(){return ready}
  });
}

Geodesy

A JavaScript file in the atlas folder of GridAtlas that works with distance km (`distanceKm`) and representative point (`representativePoint`) and calculates great-circle distances and angles (units: kV), using haversine.

geodesygridatlas / atlas/modules/202609011950-geodesy.js · lines 1–145 of 145 · version 2026-09-01 19:50 · pattern representativePoint (shared by 22 files)

What it does
Defines distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg. 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, 750kV.
Inputs & outputs
Voltage levels named: 750kV.
Downstream impact
Used directly by 4 files: Asset Context Test (gridatlas); Model 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 is built from the distance km helper (`distanceKm`), the representative point helper (`representativePoint`) and the voltages kV helper (`voltagesKv`). One Earth radius for the whole estate, and the three operations every measurement here is built from. Its code works with 750 kV.
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 2 tests, including Asset Context Test.
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
referenced by Asset Context Test (new URL import.meta.url), referenced by Model 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
distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg
Defines here
distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg
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/202609011950-geodesy.js:1-145 · blob bfc364925b05a4295fc916fc6d55ec771b337548 · 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: geodesy
 *
 * 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.
 */
(() => {
  'use strict';

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

  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;
  }

  NS.geodesy = Object.freeze({
    schema: 'gridatlas.module.geodesy.v1',
    EARTH_RADIUS_KM,
    distanceKm,
    destinationPoint,
    initialBearingDeg,
    representativePoint,
    voltagesKv
  });
})();

Grid Scope

A JavaScript file in the atlas folder of GridAtlas covering substations, using haversine. It is built from the class of helper (`classOf`) and the scope step (`scope`).

rendergridatlas / atlas/modules/202609012040-grid-scope.js · lines 1–165 of 165 · version 2026-09-01 20:40 · Not reached from any entry point (candidate for review) · pattern scope (shared by 8 files)

What it does
It lists and searches substations. Defines classOf, scope. 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, 750kV, 132kV, 110kV, 50kV.
Inputs & outputs
Voltage levels named: 750kV, 132kV, 110kV, 50kV.
What it achieves
"When you click on a blank space, the user should be able to see grid in the vicinity. Its code works with 110 kV, 132 kV and 50 kV.
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
classOf, scope
Defines here
classOf, scope
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/202609012040-grid-scope.js:1-165 · blob 28610fb7069de35c6eeec5c35e02b9d5651826d7 · 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: grid-scope
 *
 * "When you click on a blank space, the user should be able to see grid in
 * the vicinity. Call it the GRID FINDING SCOPE — analysis of what is
 * there, NOT indicative of capacity." — Vikram, 2026-09-01.
 *
 * So this answers exactly one question: WHAT IS MAPPED HERE. It counts
 * what the served payload contains around a point, by voltage class and
 * by distance band, and names the nearest few. It is a census of the map,
 * not a study of the network.
 *
 * WHAT IT WILL NOT DO, EVER
 * It does not say whether a connection is available, likely, cheap or
 * possible. Nothing in a payload of substation positions can support any
 * of that: capacity depends on queue position, committed connections,
 * thermal and fault headroom, consent and commercial terms, and none of
 * those is a distance. A scope that counted substations and implied
 * opportunity would be the most dangerous thing this estate could ship,
 * because it would look like analysis.
 *
 * Pure. No DOM, no network, no state. Depends on: geodesy.
 */
(() => {
  'use strict';

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

  const geodesy = NS.geodesy;
  if (!geodesy) throw new Error('grid-scope requires the geodesy module');

  /* Bands, not a single radius. A reader asking "what is around here"
     wants the shape of the answer - is the nearest thing on top of me or
     twenty kilometres away - and one number hides that. */
  const DEFAULT_BANDS_KM = [2, 5, 10, 25];
  const CLASSES_KV = [400, 275, 220, 132, 66, 33];

  /* A voltage is classified ONLY as a class it actually is.
     ------------------------------------------------------------------
     The first version walked the classes and returned the first one the
     value exceeded, so it labelled 750 kV as 400, 110 kV as 66 and 50 kV
     as 33 - a false label on anything the list does not contain, which is
     exactly the sort of quiet relabelling this estate exists to avoid.
     Codex caught it on the committed module before it reached a card
     (stop-ship 202609012025).

     Now: membership, within a tolerance for the fractions OSM carries.
     Anything else is UNCLASSIFIED and counted as such, because a voltage
     the standard classes do not contain is a fact about the data, not a
     value to be rounded into the nearest familiar number. */
  const CLASS_TOLERANCE_KV = 0.5;

  function classOf(kv) {
    if (!Number.isFinite(kv)) return null;
    for (const known of CLASSES_KV) {
      if (Math.abs(kv - known) <= CLASS_TOLERANCE_KV) return known;
    }
    return null;
  }

  /**
   * @param origin [lon, lat]
   * @param substations  [{ at:[lon,lat], kv:[numbers], name, operator }]
   * @param options { bandsKm, minimumKv, nearestCount }
   */
  function scope(origin, substations, options) {
    const bandsKm = (options && options.bandsKm) || DEFAULT_BANDS_KM;
    const minimumKv = (options && options.minimumKv) || 0;
    const nearestCount = (options && options.nearestCount) || 5;
    const maximumKm = bandsKm[bandsKm.length - 1];

    const within = [];
    for (const substation of substations || []) {
      if (!substation || !Array.isArray(substation.at)) continue;
      const voltages = (Array.isArray(substation.kv) ? substation.kv : [])
        .filter(Number.isFinite);
      /* Non-finite voltages are dropped BEFORE the maximum.
         ----------------------------------------------------------------
         Codex, 202609012055: Math.max over a NaN gives NaN, and NaN < floor
         is false, so a substation whose voltage did not parse survived a
         132 kV floor and was censused as though it qualified. A voltage
         that is not a number is not a voltage above the floor. */
      const top = voltages.length ? Math.max(...voltages) : 0;
      if (top < minimumKv) continue;
      const km = geodesy.distanceKm(origin[0], origin[1],
        substation.at[0], substation.at[1]);
      if (km > maximumKm) continue;
      within.push({
        name: substation.name || '',
        operator: substation.operator || '',
        kv: top,
        class_kv: classOf(top),
        km,
        at: substation.at
      });
    }
    within.sort((a, b) => a.km - b.km);

    const bands = bandsKm.map((band) => {
      const inBand = within.filter(entry => entry.km <= band);
      const counts = {};
      let unclassified = 0;
      const unclassifiedKv = [];
      for (const entry of inBand) {
        if (entry.class_kv == null) {
          // Counted, never folded into a class it is not.
          unclassified += 1;
          if (Number.isFinite(entry.kv) && !unclassifiedKv.includes(entry.kv)) {
            unclassifiedKv.push(entry.kv);
          }
          continue;
        }
        counts[entry.class_kv] = (counts[entry.class_kv] || 0) + 1;
      }
      const highest = inBand.reduce(
        (best, entry) => (entry.class_kv != null && (best == null || entry.class_kv > best)
          ? entry.class_kv : best), null);
      return {
        within_km: band,
        substations: inBand.length,
        by_class_kv: counts,
        highest_class_kv: highest,
        unclassified_voltage: unclassified,
        unclassified_kv: unclassifiedKv.sort((a, b) => b - a)
      };
    });

    /* Named first, because an unnamed OSM node is a fact about the map
       rather than a place anyone can look up. Both are reported: the
       nearest thing, and the nearest thing with an identity. */
    const named = within.filter(entry => entry.name);
    return {
      schema: 'gridatlas.grid-scope.v1',
      origin: [origin[0], origin[1]],
      radius_km: maximumKm,
      minimum_kv: minimumKv,
      counted: within.length,
      bands,
      nearest: within.slice(0, nearestCount),
      nearest_named: named.slice(0, nearestCount),
      nearest_transmission: within.find(entry => entry.kv >= 275 - 0.5) || null,
      /* Carried in the result itself so it cannot be separated from the
         numbers by a renderer, a screenshot or a quote. */
      what_this_is: 'A census of the substations in the served map payload '
        + 'around this point, by voltage class and distance band.',
      what_this_is_not: 'Not a statement about capacity, headroom, '
        + 'availability or the cost of connecting here. Distance is not '
        + 'capacity: queue position, committed connections, thermal and '
        + 'fault headroom, consent and commercial terms decide that, and '
        + 'none of them is in this payload.',
      method: 'haversine on a single Earth radius of '
        + geodesy.EARTH_RADIUS_KM + ' km, straight line to mapped geometry'
    };
  }

  NS.gridScope = Object.freeze({
    schema: 'gridatlas.module.grid-scope.v2',
    CLASS_TOLERANCE_KV,
    DEFAULT_BANDS_KM,
    CLASSES_KV,
    classOf,
    scope
  });
})();