GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/lightning/src

08 Map and 8 more files

A JavaScript file in the lightning folder of GridAtlas that maps the Renewable Energy Planning Database (REPD) register and substations.

692 lines of JavaScript from gridatlas, in 9 files. Topic: Maps, GIS and field navigation. Section 635 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. 00 Header render · gridatlas / tools/lightning/src/00-header.js lines 1–64
  2. 01 Helpers render · gridatlas / tools/lightning/src/01-helpers.js lines 1–63
  3. 02 Transport ingest · gridatlas / tools/lightning/src/02-transport.js lines 1–39
  4. 03 Index other · gridatlas / tools/lightning/src/03-index.js lines 1–81
  5. 04 Windows render · gridatlas / tools/lightning/src/04-windows.js lines 1–49
  6. 05 Cells render · gridatlas / tools/lightning/src/05-cells.js lines 1–75
  7. 06 Load other · gridatlas / tools/lightning/src/06-load.js lines 1–61
  8. 07 Captions other · gridatlas / tools/lightning/src/07-captions.js lines 1–84
  9. 08 Map render · gridatlas / tools/lightning/src/08-map.js lines 1–176

00 Header

A JavaScript file in the lightning folder of GridAtlas covering UK lightning and the Renewable Energy Planning Database (REPD) register, and uses data from the lightning repository.

rendergridatlas / tools/lightning/src/00-header.js · lines 1–64 of 64 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: the REPD register.
What it achieves
UK-lightning-overlay, generation @@GEN@@ . EUMETSAT MTG LI L2-LFL optical flashes, OFF by default, never persisted; NOT confirmed ground strikes; unsearched is unknown, never zero.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/00-header.js:1-64 · blob 6df5624ee438d62dd813bf8b3c20eb141b9b59e5 · 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
/// UK lightning overlay: readable source. Build: node tools/lightning/build.mjs (docs/LIGHTNING-SOURCE.md).
/// Lines starting with /// (like this one) and the ///#if / ///#else / ///#endif variant blocks are source only; a line
/// ending in /// continues on the next line. Everything else ships byte for byte in atlas/modules/<GEN>-uk-lightning-overlay.js.
/// Variants: "layers" (M4 202610290045: the listed technologies' own REPD layers are switched on) and "dots" (M4b
/// 202610290050: only the listed sites are drawn, as REPD-styled dots). @@GEN@@ is the generation stamp.
///
/// 00 header: the shipped header comments, the IIFE, the aliases and the constants.
///
/// The L3 header, as written before build-M stage A1 shortened it to one line (generation 202610281340):
/// EUMETSAT MTG Lightning Imager (L2-LFL) optical flashes, OFF by default, appended last to the original Layers panel
/// and fullscreen curtain; no request, source, layer or listener until switched on; never persisted. Optical flashes are
/// NOT confirmed ground strikes; a day never searched is unknown, never zero. Above the device cap the window draws as
/// tappable ≈10 km cells (data/history/grid) within 30 km of a REPD site.
/// Rules trimmed from lightning history-window.mjs (data-plane/hourly-lookback-index-v2 @ f7db76c). No engine, Pipeline
/// News or menu-proxy attribute. Name glossary: docs/lightning/CANDIDATE-202610261949.md.
/// The shipped header comments below are part of the module bytes (the generation proof reads them).
/* uk-lightning-overlay, generation @@GEN@@ (UTC). EUMETSAT MTG LI L2-LFL optical flashes, OFF by default, never persisted; NOT confirmed ground strikes; unsearched is unknown, never zero. Long periods: ≈10 km cells within 30 km of a REPD site. */
/* M2: a tap lists the nearest REPD project sites (straight-line, 40 km; projects at one point grouped; status and technology filters; 10 km / 40 km summary); a row flies to the project and draws its nearest-substation links, with "◀ back" to the lightning card. Distance only: never "affected". */
/* M4: a module camera move never starts inside another (MapLibre fires moveend synchronously from stop()): the pending framing is dropped before each own move and otherwise runs after the stop that fired it, only when the map is not moving. */
///#if dots
/* M4b: the listed REPD sites only are drawn as REPD-styled dots (the engine's glow + core paint); the Layers controls are never touched. */
///#else
/* M3: the original REPD map layers of the listed technologies are switched on through their own Layers checkboxes, and only those M3 switched on are switched off again on close, lightning OFF, a period change, LATEST or a new list. */
///#endif
/* M5: every listed REPD project shows its full REPD record (address, postcode, county, region, ref, operator, planning) from the pinned parquet the map's project search reads, joined only on an exact point, name, MW and type match; plus an Area summary. */
(()=>{'use strict';
/// Aliases (build-M A3): Math.max/min, Array.isArray, Date.parse (static, no this), appendChild and getBoundingClientRect
/// helpers, and U, the phrase every unknown count carries. NS is the shared window.__GRIDATLAS_MODULES__ namespace, the only
/// global this module writes.
let MX=Math.max,///
  MN=Math.min,///
  AI=Array.isArray,///
  DP=Date.parse,///
  ap=(p,c)=>p.appendChild(c),///
  gr=e=>e.getBoundingClientRect(),///
  U='unknown, not zero',///
  NS=(window.__GRIDATLAS_MODULES__=window.__GRIDATLAS_MODULES__||{});
if(NS.ukLightning||typeof document==='undefined')return;
/// Identity and sources. GEN is stamped by the build. AR: the archive (index, days, grid) on Ventusltd/lightning main;
/// FEED: the 7-day live feed. TMO: the 15 s request timeout; BUDGET: the most points ever drawn; RQ: the most day files per
/// window (and the LRU size). PERIODS: [key, label, ms] or [key, label, -months]; custom = CUSTOM UTC dates. LONG: periods
/// that need the archive. COLOUR: status dot colour by state letter (LOADING, PARTIAL, UNKNOWN, BEFORE-ARCHIVE, FAIL).
let GEN='@@GEN@@',///
  AR='https://raw.githubusercontent.com/Ventusltd/lightning/main/data/history/',///
  IX_SCHEMA='uk-lightning-history-index.v2',///
  GS='uk-lightning-history-grid.v1',
FEED='https://raw.githubusercontent.com/Ventusltd/lightning/main/data/uk_lightning.geojson',///
  FEED_SCHEMA='FeatureCollection/optical_lightning_flash',
SRC='gridatlas-lightning',///
  LAYER='l-gridatlas-lightning',///
  DAY=864e5,///
  HOUR=36e5,///
  TMO=15000,///
  BUDGET=40000,///
  RQ=400,///
  DRE=/^\d{4}-\d{2}-\d{2}$/,///
  TOE='timeout after 15 s',///
  NA=e=>/HTTP 404/.test(e)?'archive not yet published':'archive unavailable',
PERIODS=[['12h','12 hours',12*HOUR],['24h','24 hours',DAY],['48h','48 hours',2*DAY],///
    ['7d','7 days',7*DAY],['30d','30 days',30*DAY],['3m','3 months',-3],///
    ['6m','6 months',-6],['12m','12 months',-12],['custom','Custom UTC dates',0]],
LONG=['30d','3m','6m','12m'],BASE='Lightning Flashes (Optical)',TITLE='Weather · EUMETSAT Lightning Imager',
FOOTER=`Times UTC · Optical flashes seen by MTG Lightning Imager (EUMETSAT L2-LFL), not confirmed ground strikes · Missing days are ${U} · UK box −11.0,49.5 → 3.0,61.5`,
COLOUR=st=>({L:'#888',P:'#ffcc00',U:'#ff8800',B:'#ff8800',F:'#ff4444'})[st[0]]||'#00ff88',

01 Helpers

A JavaScript file in the lightning folder of GridAtlas.

rendergridatlas / tools/lightning/src/01-helpers.js · lines 1–63 of 63 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
Date and number formatting, GeoJSON guards, the device cap, month arithmetic and the published state S.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/01-helpers.js:1-63 · blob f21ee77f7137ad61d19df32e347cab9391867752 · 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
/// 01 helpers: date and number formatting, GeoJSON guards, the device cap, month arithmetic and the published state S.
///
/// ymd: UTC date; ds: date -> ms; Q: getElementById; E: throw. T/Ts: UTC minute/second text, 'unknown' if not finite.
ymd=t=>new Date(t).toISOString().slice(0,10),///
  ds=d=>DP(d+'T00:00:00Z'),///
  Q=id=>document.getElementById(id),///
  E=m=>{throw new TypeError(m)},
T=(t,n=16)=>isFinite(t)?new Date(t).toISOString().slice(0,n).replace('T',' ')+' UTC':'unknown',Ts=t=>T(t,19),
/// N: grouped number; pl: plural; dm/hm/dt: short date, hh:mm, both; du: duration in h/min (LR-words W8: hours grouped);
/// hz: a window of 48 h or less (hour clip); de: end text; sv: "x of y searched"; lr: when the collector last ran and how far
/// it searched; F7: the live-feed flash phrase; AGO: age, via du (LR-words W6).
N=n=>Number(n).toLocaleString('en-GB'),///
  pl=(n,w,s='s')=>N(n)+' '+w+(n==1?'':s),///
  dm=t=>{///
    let s=new Date(t).toUTCString(),y=s.slice(12,16);///
    return+s.slice(5,7)+s.slice(7,11)+(y==new Date().getUTCFullYear()?'':' '+y)///
  },///
  hm=t=>T(t).slice(11,16),///
  dt=t=>dm(t)+' '+hm(t),///
  du=m=>(m=Math.round(m/6e4),(m>59?N(m/60|0)+' h ':'')+(m%60||m<60?m%60+' min':'')).trim(),///
  hz=w=>!w.custom&&w.span<=2*DAY,///
  de=(a,b)=>dm(a)==dm(b)?hm(b):dt(b),///
  sv=(r,k,p)=>{///
    let v=r.cov,w=r.w,a=k&&/READY|EMPTY/.test(k.st);///
    return hz(w)?(a?'all ':(v.f>0?du(v.f*w.span):'0')+' of ')+w.label+' searched':(a?'all '+pl(v.d,'day'):`${v.k} of ${pl(v.d,'day')}`)+' searched'+(p&&v.pp?` (${v.pp} in part)`:'')///
  },///
  lr=(g,now,f)=>isFinite(g)?`collector last ran ${ymd(g)==ymd(now)?hm(g):dt(g)} UTC${f&&g-f>HOUR?`, searched to ${ymd(f)==ymd(now)?hm(f):dt(f)} UTC`:''}${g>now+9e5?' (device clock behind)':''}`:'collector last run unknown',///
  F7=r=>`${N(r.ev.length)} seen in the available 7-day feed · ${r.w.label} requested${r.old?' · older history unknown':''}`,///
  AGO=t=>t<0?'?':t<3e4?'<1 min':du(t),
/// ov: overlap of [a,b) and [c,d); FC: FeatureCollection; bx: inside the UK box; isFC; tm: a flash's time (Z added when
/// missing); msg: an error's text, sanitised by cs (LR-security S3).
ov=(a,b,c,d)=>MX(0,MN(b,d)-MX(a,c)),///
  FC=f=>({type:'FeatureCollection',features:f||[]}),///
  bx=(x,y)=>x===+x&&y===+y&&x>=-11&&x<=3&&y>=49.5&&y<=61.5,///
  isFC=o=>o&&o.type==='FeatureCollection'&&AI(o.features),///
  tm=f=>{///
    let s=f.properties.time_utc+'';///
    return DP(/T[\d:.]+$/.test(s)?s+'Z':s)///
  },///
  msg=e=>cs(e&&e.message||e),
/// The device point cap: 10,000 on a phone (coarse pointer or <= 700 px), else 40,000. Above it a window draws as cells.
ph=()=>{///
    try{///
      return matchMedia('(pointer: coarse)').matches||window.innerWidth<=700///
    }catch(_){return false}///
  },///
  cap=()=>ph()?10000:40000,
/// mm: t minus k calendar months, the day clamped to the target month (3M, 6M, 12M).
mm=(t,k)=>{///
    let d=new Date(t),day=d.getUTCDate();///
    d.setUTCDate(1);///
    d.setUTCMonth(d.getUTCMonth()-k);///
    d.setUTCDate(MN(day,new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+1,0)).getUTCDate()));///
    return d.getTime()///
  },
/// State machine (published as NS.ukLightning.state): installed, waiting_for, on, requests, errors, last; period, end and h
/// (the PREV/NEXT stack of window ends), from/to (CUSTOM), consent (LOAD POINTS), serial (cancels stale loads), idx/ie (index
/// and its error), res (the drawn result), sfs (the panel groups). lru: url -> {p: promise, sealed}.
S={///
    schema:'gridatlas.module.uk-lightning-overlay.v1',generation:GEN,installed:false,waiting_for:[],on:false,requests:0,errors:[],last:null,
period:'24h',end:null,h:[],from:'',to:'',consent:false,serial:0,idx:null,ie:null,res:null,sfs:[]///
  },///
  lru=new Map(),

02 Transport

A JavaScript file in the lightning folder of GridAtlas.

ingestgridatlas / tools/lightning/src/02-transport.js · lines 1–39 of 39 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
Fetch for .JSON (no redirects, 15 s timeout that also covers the body), XMLHttpRequest for the live feed, and the LRU of day/grid promises.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/02-transport.js:1-39 · blob 83d355f19a5d38c3f788c5431e5aebc15a075668 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/// 02 transport: fetch for .json (no redirects, 15 s timeout that also covers the body), XMLHttpRequest for the live feed,
/// and the LRU of day/grid promises.
///
note=m=>S.errors.push(String(m)),
/// gj: fetch JSON (or bytes with raw) with the 15 s timeout covering the body; a redirect is refused; "HTTP n" on error.
/// M2 (build-M2 gj-abort): once its own timer has aborted, any rejection (a body stream that errors on abort, as the
/// bridge's may) is reported as the timeout, not as "Failed to fetch".
gj=(u,cache,raw)=>{let c=new AbortController(),t=setTimeout(()=>c.abort(),TMO);S.requests++;
return fetch(u,{cache,signal:c.signal}).then(r=>{///
        if(!r.ok||r.redirected)throw new Error(r.ok?'redirected':'HTTP '+r.status);///
        return raw&&r.arrayBuffer?r.arrayBuffer():r.json()///
      }).catch(e=>{///
        throw c.signal.aborted||e&&e.name==='AbortError'?new Error(TOE):e///
      }).finally(()=>clearTimeout(t))///
  },
/// gx: the live feed by XMLHttpRequest (same timeout; a redirect is refused through responseURL).
gx=u=>{S.requests++;return new Promise((res,rej)=>{let x=new XMLHttpRequest();x.open('GET',u);x.timeout=TMO;
x.onload=()=>{///
          if(x.status>=200&&x.status<300){///
            try{///
              if(x.responseURL&&!x.responseURL.startsWith(u))E('redirected');///
              res(JSON.parse(x.responseText))///
            }catch(e){rej(e)}///
          }else rej(new Error('HTTP '+x.status))///
        };
x.onerror=()=>rej(new Error('network error'));x.ontimeout=()=>rej(new Error(TOE));x.send()})},
/// lg/ls: LRU get and set, at most RQ entries.
lg=k=>{///
    if(!lru.has(k))return;///
    let v=lru.get(k);///
    lru.delete(k);///
    lru.set(k,v);///
    return v///
  },///
  ls=(k,v)=>{///
    lru.delete(k);///
    lru.set(k,v);///
    while(lru.size>RQ)lru.delete(lru.keys().next().value)///
  },

03 Index

A JavaScript file in the lightning folder of GridAtlas.

othergridatlas / tools/lightning/src/03-index.js · lines 1–81 of 81 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
Inputs & outputs
In: JSON file index.json.
What it achieves
03 archive index v2 (Ventusltd/lightning `data/history/index.json`): every row validated; coverage from `scan_windows`.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/03-index.js:1-81 · blob 900432dcdb6383a73bca20cdd2c9047dca396679 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/// 03 archive index v2 (Ventusltd/lightning data/history/index.json): every row validated; coverage from scan_windows.
///
/// vk: one index v2 row; parts are hourly days/YYYY/MM/DD/HH.json with integer counts; a bad row throws with its date.
vk=r=>{///
    let n=r&&r.count,b=w=>E(`invalid index row ${r&&r.date}: ${w}`);///
    if(!r||ymd(ds(r.date)||0)!=r.date)b('date');///
    if(!['none','partial','full'].includes(r.coverage))b('coverage');
if(r.coverage==='none'?n!==null:n>>>0!==n)b('count');///
    if(n===0&&!(r.scanned_seconds>0))b('count 0 unscanned');///
    if(n>0&&!r.path&&!(r.parts&&r.parts.length))b('no path/parts');
if(r.path&&!/^days\/\d{4}\/\d{2}\/\d{2}\.json$/.test(r.path))b('path');///
    if(typeof r.sealed!=='boolean')b('sealed');
if(r.parts&&!(AI(r.parts)&&r.parts.length<=24&&r.parts.every(p=>p&&/^days\/\d{4}(\/\d\d){3}\.json$/.test(p.path)&&(p.count>>>0||-1)===p.count)))b('parts')///
  },
/// ni: normalise the index: schema, observation, generated_utc, cutoff and the scan windows; by = date -> row; lost
/// (shard_lost) days are unknown, never searched.
ni=raw=>{if(!raw||typeof raw!=='object'||!AI(raw.days))E('not a lightning history index');
if(raw.schema!==IX_SCHEMA)E('unsupported index schema '+raw.schema);
if(raw.observation!=='satellite optical lightning flashes, not ground strikes')E('index observation missing');
let gen=DP(raw.generated_utc);///
    if(!isFinite(gen))E('index generated_utc missing');///
    if(!DRE.test(raw.cutoff_date_utc||''))E('index cutoff_date_utc missing');
raw.days.forEach(vk);
let sw=(raw.scan_windows||[]).map(w=>({///
          s:DP(w.start_utc),e:DP(w.end_utc),n:Number(w.successful_runs)||1///
        })).filter(w=>isFinite(w.s)&&isFinite(w.e)&&w.e>w.s).sort((a,b)=>a.s-b.s),
cutoff=ds(raw.cutoff_date_utc),iv=Number(raw.collection_interval_hours)||3;
return{///
      days:raw.days,by:new Map(raw.days.map(r=>[r.date,r])),sw,gen,cutoff,iv,nextDue:DP(raw.next_update_due_utc||'')||gen+(iv+1)*HOUR,lastScan:sw.length?sw.reduce((a,w)=>MX(a,w.e),-Infinity):null,
covStart:DP(raw.coverage_start_utc||'')||(sw.length?sw[0].s:cutoff),cutoffDate:raw.cutoff_date_utc,lost:new Set(raw.days.filter(r=>r.shard_lost).map(r=>r.date))///
    }///
  },
/// stale: the archive last searched more than 4 h ago, or its index is dated more than 15 min after the device clock.
stale=(g,now,f=g)=>!(now-f<=4*HOUR&&g<=now+9e5),
/// li: load the index once (q busts the cache after a mismatch); unsealed LRU entries are dropped when it changes.
li=q=>{///
    if(!S.ip){///
      let p=S.ip=gj(AR+'index.json'+(q?'?'+q:''),'no-cache').then(ni).then(m=>{///
          if(S.ip===p){///
            for(let k of[...lru.keys()])if(!lru.get(k).sealed)lru.delete(k);///
            S.idx=m;///
            S.ie=null///
          }return m///
        }).catch(e=>{///
          if(S.ip===p){S.ip=null;///
            S.idx=null;///
            S.ie=msg(e)}throw e///
        })///
    }return S.ip///
  },
/// cv: coverage of [ws,we) from scan_windows (union): f fraction searched, r runs, a/b first/last scan, d dates, u unknown
/// dates, l lost days, ny not yet searched (ms at the end), bf before the archive (ms), k known days, pp partly searched days.
cv=(x,ws,we)=>{let win=we-ws,u=[];let r=0,a=null,b=null,sd=0,d=0,l=0,fs=null,lz,pp=0;
for(let w of x.sw){///
      let o=ov(MX(ws,b),we,w.s,w.e);///
      if(o<=0)continue;///
      sd+=o;///
      r+=w.n;///
      let s=MX(ws,w.s),e=MN(we,w.e);///
      a=a===null?s:MN(a,s);///
      b=b===null?e:MX(b,e)///
    }
for(let t=ds(ymd(ws));///
      t<we;///
      t+=DAY){///
      if(ov(ws,we,t,t+DAY)<=0)continue;///
      d++;///
      let y=ymd(t),row=x.by.get(y);///
      if(x.lost.has(y)){///
        l++;///
        let m=t;///
        for(let w of x.sw)sd-=ov(MX(ws,m),MN(we,t+DAY),w.s,w.e),m=MX(m,w.e)///
      }else if(!row||row.coverage==='none')u.push(y);///
      else{fs??=t;///
        lz=t;///
        pp+=row.coverage==='partial'}///
    }
return{///
      f:win>0?MN(1,sd/win):0,r,a,b,d,u,l,fs,lz,pp,k:d-u.length-l,ny:x.lastScan===null?win:MX(0,we-MX(ws,x.lastScan)),bf:MX(0,MN(we,x.covStart)-ws)///
    }///
  },

04 Windows

A JavaScript file in the lightning folder of GridAtlas that uses SHA-256.

rendergridatlas / tools/lightning/src/04-windows.js · lines 1–49 of 49 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
04 windows and day files: UTC, end-anchored [start,end) windows; hourly or daily shard targets; a 4-wide fan-out.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/04-windows.js:1-49 · blob 601413ab493e006484fc4fc70c50e253407a10c2 · 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
/// 04 windows and day files: UTC, end-anchored [start,end) windows; hourly or daily shard targets; a 4-wide fan-out.
///
/// wf: the window {s, e, span, atLatest, period, label, clamped, custom}; S.end anchors PREV/NEXT, CUSTOM uses whole UTC dates.
wf=now=>{let P=PERIODS.find(p=>p[0]===S.period)||PERIODS[1],cu=S.period==='custom';let s,e,atLatest;
if(cu){///
      s=ds(S.from);///
      e=MN(ds(S.to)+DAY,now);///
      atLatest=ds(S.to)+DAY>=now///
    }else{///
      e=S.end===null?now:MN(S.end,now);///
      atLatest=S.end===null;///
      s=P[2]<0?mm(e,-P[2]):e-P[2]///
    }
return{s,e,atLatest,period:P[0],label:P[1],span:e-s,clamped:false,custom:cu}},
/// tg: the shard targets of one index row inside the window (a daily file, or the hourly parts that overlap it).
tg=(row,ws,we)=>!row||!row.count?[]:row.path?[row]
:(row.parts||[]).filter(p=>{///
      let h=ds(row.date)+p.path.slice(-7,-5)*HOUR;///
      return h<we&&h+HOUR>ws///
    }).map(p=>({...p,sealed:row.sealed})),
/// sh: fetch one day file (the HTTP cache is used only for a sealed day), check schema, date, count, bytes and sha256 against its index row.
sh=(t,date)=>{let u=AR+t.path,c=lg(u);if(c)return c.p;
let p=gj(u,t.sealed?'default':'no-cache',1).then(async b=>{///
        let o=b.byteLength>=0?await new Response(b).json():b,s=(window.crypto||0).subtle;
if(!isFC(o)||o.schema!=='uk-lightning-history-day.v1'||!o.metadata||o.metadata.date_utc!==date)E('invalid day file');
let bad=[o.features.length!==t.count&&'count',b.byteLength!==t.bytes&&'bytes',///
          s&&[...new Uint8Array(await s.digest('SHA-256',b))].map(x=>(x|256).toString(16).slice(1)).join('')!==t.sha256&&'sha256'].filter(Boolean);
if(bad.length)E('index mismatch: '+bad.join(', '));///
        if(!s&&t.sha256)E('not verified (no WebCrypto)');///
        return o.features///
      }).catch(e=>{lru.delete(u);///
        throw e});
ls(u,{p,sealed:!!t.sealed});return p},
/// fr: fan out over the shard targets, 4 at a time, abandoned when S.serial moves on; failures are kept per day.
fr=async(rows,ws,we,sn)=>{///
    let jobs=[];///
    for(let row of rows)for(let t of tg(row,ws,we))jobs.push({row,t});///
    let parts=new Array(jobs.length),fl=[];///
    let pos=0;
await Promise.all(Array.from({length:MN(4,jobs.length)},async()=>{///
          while(pos<jobs.length&&sn===S.serial){///
            let i=pos++,{row,t}=jobs[i];///
            try{parts[i]=await sh(t,row.date)}catch(e){///
              parts[i]=[];///
              fl.push({date:row.date,error:msg(e),t})///
            }///
          }///
        }));
return{parts,fl,rq:jobs.length}},

05 Cells

A JavaScript file in the lightning folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register, using SHA-256.

rendergridatlas / tools/lightning/src/05-cells.js · lines 1–75 of 75 · Not reached from any entry point (candidate for review)

What it does
It lists and searches the REPD register.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: the REPD register.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
05 flashes and cells: feature validation and de-duplication, month grids, the REPD land mask, the cell layer data.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/05-cells.js:1-75 · blob 1c5bdd13208f47996cba744822771ff115131677 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/// 05 flashes and cells: feature validation and de-duplication, month grids, the REPD land mask, the cell layer data.
///
/// ok: a valid optical-flash Point inside the UK box with a finite time and a scalar id. co: collect the features of the
/// window, de-duplicated by id (or time and position), sorted by time; a.bad counts the rejected ones.
ok=f=>f&&f.type==='Feature'&&f.geometry&&f.geometry.type==='Point'&&(c=>AI(c)&&c.length<4&&bx(c[0],c[1]))(f.geometry.coordinates)&&f.properties&&FEED_SCHEMA.split('/')[1]===f.properties.observation_kind&&isFinite(tm(f))&&!(f.id&&typeof f.id=='object'),
co=(parts,ws,we)=>{///
    let m=new Map();///
    let k=0;///
    for(let part of parts)for(let f of part){///
      if(!ok(f)){k++;///
        continue}let t=tm(f);///
      if(t>=ws&&t<we)m.set(f.id==null?t+','+f.geometry.coordinates:JSON.stringify(f.id),f)///
    }let a=[...m.values()].sort((a,b)=>tm(a)-tm(b));///
    a.bad=k;///
    return a///
  },
/// Cells: month grids grid/YYYY-MM.json (0.1°, per UTC day); a day counts only if coverage, count and sha256 match its index
/// row. LR-security S1: 2 MB cap, checked on the raw bytes before parsing. The const below stays const: test-engine asserts
/// its text (build-M A5 KEEP).
gg=mo=>{if(!/^\d{4}-\d\d$/.test(mo))E('grid path');const u=AR+'grid/'+mo+'.json',h=lg(u);if(h)return h.p;
let p=gj(u,'no-cache',1).then(async b=>{///
        let o=b.byteLength>2e6?E('grid size'):b.byteLength>=0?await new Response(b).json():b;///
        if(!o||o.schema!==GS||o.month!==mo||o.cols!==140||o.rows!==120||o.cell_deg!==.1||!AI(o.days)||o.days.length>31||!AI(o.cells)||o.cells.length>16800)E('invalid grid '+mo);///
        let t=[];
for(let r of o.cells){///
          if(!AI(r)||r.length%2<1||r.length<3||r.length>63||r[0]>>>0!==r[0]||r[0]>=16800)E('grid cell');///
          for(let i=1;///
            i<r.length;///
            i+=2){///
            let d=r[i],n=r[i+1];///
            if(d>>>0!==d||d<1||d>31||n>>>0!==n||!n)E('grid count');///
            t[d]=(t[d]||0)+n///
          }///
        }
for(let d of o.days)if(!d||!AI(d.sha256)||(d.date+'').slice(0,8)!==mo+'-'||(t[+d.date.slice(8)]||0)!==(d.count||0))E('grid sum '+mo);///
        return o///
      }).catch(e=>{lru.delete(u);///
        throw e});///
    ls(u,{p});///
    return p///
  },
/// Land mask: cells whose centre is within 30 km of an onshore REPD site, as run lengths over the 140 x 120 grid; totals keep
/// every cell. L3 (LR-bugs LRB1) dropped the REPD placeholder 49.766807,-7.55716 (OSGB 0,0): 5,508 -> 5,472 cells. The
/// const in the loop below stays const (build-M A5 KEEP).
LM=()=>{///
    if(!LM.a){///
      let a=LM.a=new Uint8Array(16800);///
      let p=0,v=1;///
      for(const c of'M3bCjeCie83C7rC6sC6r4583Bmr1a28BmAg26BaAqB7AsB6AsB5AtB3AuB4AtB4AsB5AsAw81AqAvB0AvAzAxB0AwB1AvB3AuB3AuB8ArB6AtB4AvB0AwAzAuAyAwAzAxAyAyAxB0AvB0AuB1AmBaAmBbAkBe82A7Bh47A5BrA4Av4e5aA3Am71b7a6A3Alo4b4A4Ajr3c2A5Agv3c1A5Agw3AfAhz3AbAkA0161A3AnB9AoB5AsB1AxAyAzAwB1l2A8B2AtB9AnBbAkBdAiBdAjBcAjBdAiBfAgBiAdBnA6Bh44A5Bh81A6BgAgBgAhBgAhBiAgBjAdBib1A3B872AgB692AfB6ArB5AsB6ArBcAkBdAjB973AcB9b  … [line shortened here: 541 characters; full line on GitHub]
        p,p+=c[1]?(c.charCodeAt(0)-64)*36+parseInt(c[1],36):parseInt(c,36))///
    }return LM.a///
  },
/// gd: the cell layer data for the window's known days: n flashes in all cells, k drawn inside the mask, st days not yet in a
/// grid, e the refused month's reason (LR-bugs LRB3), T the glow floor = max(30, p95 of drawn cells). LRB2: if every grid day
/// is stale, fall back to the summary.
gd=async(rows,sn)=>{///
    let er,n=0,st=0,k=0;///
    let gs=new Map(await Promise.all([...new Set(rows.filter(y=>y.count>0).map(y=>y.date.slice(0,7)))].map(async m=>[m,await gg(m).catch(e=>(er=e,{days:[],cells:[]}))]))),ok=new Set,c=new Map,f=[],v=[];
for(let y of rows)if(y.count>0){///
      let d=gs.get(y.date.slice(0,7)).days.find(d=>d.date===y.date);///
      if(d&&d.count===y.count&&d.coverage===y.coverage&&d.sha256+''==(y.path?[y.sha256]:y.parts.map(p=>p.sha256))+'')ok.add(y.date),n+=y.count;///
      else st++///
    }if(!n)throw er||Error('grid stale');
for(let[m,g]of gs)for(let r of g.cells)for(let i=1;///
      i<r.length;///
      i+=2)if(ok.has(m+'-'+(r[i]+'').padStart(2,0)))c.set(r[0],(c.get(r[0])||0)+r[i+1]);
for(let[q,x]of c)if(LM()[q]){///
      let lon=-11+(q%140+.5)/10,lat=49.5+((q/140|0)+.5)/10;///
      k+=x;///
      v.push(x);///
      f.push({///
          type:'Feature',properties:{cell:q,n:x,lon,lat,s:sn},geometry:{type:'Point',coordinates:[lon,lat]}///
        })///
    }
v.sort((a,b)=>a-b);return{fc:FC(f),n,k,st,e:er&&msg(er),T:MX(30,v[v.length*.95|0]||0)}},

06 Load

A JavaScript file in the lightning folder of GridAtlas that uses SHA-256.

othergridatlas / tools/lightning/src/06-load.js · lines 1–61 of 61 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
06 tiers: the live feed (7 days only), the archive overview (cells), the archive detail (points, budgeted).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/06-load.js:1-61 · blob 476564692407d9225170b5853587bd97038f4493 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/// 06 tiers: the live feed (7 days only), the archive overview (cells), the archive detail (points, budgeted).
///
/// ff: the live feed tier (7 days only); reason names why the archive was not used.
ff=async(w,now,reason)=>{
let f=await(S.fp||(S.fp=gx(FEED).catch(e=>{S.fp=null;throw e})));if(!isFC(f))E('invalid live feed');
let ev=co([f.features],w.s,w.e);
return{///
      mode:'feed',w,idx:null,ie:reason,meta:f.metadata||{},old:w.s<now-7*DAY,ev,fl:[],cs:'live feed',ic:ev.length,cl:ev.length>cap(),cov:null///
    }},
/// lw: load a window: the index, then BEFORE-ARCHIVE, overview (cells) or detail (points). Within the device cap, 32 MB and
/// RQ files, points load for any window; above, cells draw and LOAD POINTS asks first (S.consent). arch counts whole UTC
/// days above 48 h (LR-bugs LRB4 + LR-numbers F1), J's hour clip at 48 h or less.
lw=async(now,sn,q)=>{let w=wf(now);let x=null,ie=null;try{x=await li(q)}catch(e){ie=msg(e)}
if(!x)return ff(w,now,ie);
if(w.e<=x.cutoff)return{mode:'overview',w,idx:x,before:true,fl:[],ev:[],arch:0};
if(w.s<x.cutoff){w.s=x.cutoff;w.span=w.e-w.s;w.clamped=true}
let rows=[...x.by.values()].filter(y=>{let f=ds(y.date);///
        return f<w.e&&f+DAY>w.s}),known=rows.filter(y=>y.count!==null),
r={///
      mode:'overview',w,idx:x,before:false,rows,arch:known.reduce((n,y)=>n+(y.parts&&hz(w)?tg(y,w.s,w.e).reduce((a,p)=>a+p.count,0):y.count),///
        0),cov:cv(x,w.s,w.e),fl:[],ev:[],ld:[],sk:[]///
    };
let tf=rows.filter(y=>y.count>0),bytes=0,count=0,nq=0;
for(let row of tf)for(let t of tg(row,w.s,w.e)){///
      nq++;///
      count+=t.count||0;///
      bytes+=t.bytes>0?t.bytes:(t.count||0)*530///
    }
if(count>MN(BUDGET,cap())||bytes>32e6||nq>RQ){///
      r.budget=`${N(count)} flashes, ${N(bytes)} bytes, ${N(nq)} files`;///
      try{r.gd=await gd(rows,sn)}catch(e){r.ge=NA(msg(e))+': '+msg(e)}if(sn!==S.serial)return r;///
      if(!S.consent){r.clp=true;///
        return r}
let run=0,rb=0,rn=0;///
      tf.sort((a,b)=>b.date.localeCompare(a.date));///
      let keep=[];///
      for(let y of tf){///
        let ps=tg(y,w.s,w.e),c=ps.reduce((a,p)=>a+(p.count||0),0),b=ps.reduce((a,p)=>a+(p.bytes>0?p.bytes:(p.count||0)*530),0),q=ps.length;///
        if(r.sk.length||run+c>BUDGET||rb+b>32e6||rn+q>RQ){r.sk.push(y.date);///
          continue}keep.push(y);///
        run+=c;///
        rb+=b;///
        rn+=q///
      }if(!keep.length){r.clp=r.big=1;///
        return r}tf=keep;///
      count=run///
    }
r.ld=tf.map(y=>y.date);r.ic=count;r.cs='index';r.cl=count>cap();
/// A sha256 mismatch on an unsealed day means the archive is being rewritten: reload the index once, then say so.
let got=await fr(tf,w.s,w.e,sn);///
    for(let f of got.fl)if(/WebCrypto/.test(f.error))f.u=1;///
    else if(!f.t.sealed&&/mismatch/.test(f.error)){///
      if(!q){S.ip=null;///
        return lw(now,sn,now)}f.error+='; archive updating, reload later';///
      f.u=1///
    }r.mode='detail';///
    r.fl=got.fl;///
    r.rq=got.rq;///
    r.ev=co(got.parts,w.s,w.e);///
    return r///
  },

07 Captions

A JavaScript file in the lightning folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register.

othergridatlas / tools/lightning/src/07-captions.js · lines 1–84 of 84 · Not reached from any entry point (candidate for review)

What it does
It lists and searches the REPD register.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: the REPD register.
What it achieves
07 state and captions: the state machine (cf) and the caption lines (cp).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/07-captions.js:1-84 · blob e506f4b1c718f0d1856ad2f7f0de0ab026ec76eb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/// 07 state and captions: the state machine (cf) and the caption lines (cp). Unknown is never shown as zero.
///
/// cf: classify a result: FAIL, BEFORE-ARCHIVE, PARTIAL, UNKNOWN, READY·DETAIL, READY·OVERVIEW or EMPTY, with reasons.
cf=(r,now)=>{let st;let rs=[];
if(r.fail){st='FAIL';rs.push(r.fail)}else if(r.before){st='BEFORE-ARCHIVE';rs.push('before archive start')}
else if(r.fl.some(f=>!f.u)){st='FAIL';rs.push(`${r.fl.length} of ${r.rq} day files failed`)}
else{///
      let c=r.cov,f=c?c.f:0;///
      if(r.mode==='feed'){///
        st=r.ev.length?'PARTIAL':'UNKNOWN';///
        rs.push('coverage unknown')///
      }else if(!c||f<=0){st='UNKNOWN';///
        rs.push('nothing searched')}
else if(f<1||c.ny>0||c.l||c.u.length||r.fl.length){///
        st='PARTIAL';///
        if(c.ny>0)rs.push('tail unknown');///
        if(c.bf>0)rs.push('head unknown');///
        if(c.u.length)rs.push(`${c.u.length} unscanned dates`);///
        if(!rs.length)rs.push(r.fl.length?'unverified':'gaps in window')///
      }
else if(r.mode!=='overview')st=r.sk.length?(rs.push('days not loaded'),'PARTIAL'):r.ev.length?'READY·DETAIL':'EMPTY-COVERED';///
      else st=r.arch>0?r.gd?'READY·CELLS':'READY·SUMMARY':'EMPTY-COVERED'///
    }
let g=r.idx?r.idx.gen:r.meta?DP(r.meta.query_end_utc):NaN,f=r.idx&&r.idx.lastScan||g;///
    return{///
      st,g,f,stale:!!(r.idx||r.meta)&&r.w.atLatest!==false&&stale(g,now,f),colour:COLOUR(st),rs///
    }///
  },
/// DN: the cell caption (LR-words W1 with LRB3's reason): what the map shows, what is counted but not drawn.
/// M5 (V-geometry G2): cells are 0.1° and drawn only near REPD sites, so the caption says it is not a national density map.
DN=r=>{///
    let g=r.gd;///
    return`map limited to ≤30 km of REPD sites, not a national density map: ${N(g.k)} in ${pl(g.fc.features.length,'0.1° cell')}; ${N(g.n-g.k)} counted, not drawn${g.st?` · ${pl(g.st,'day')} not yet mapped (unknown${g.e?'; '+g.e:''})`:''} · tap a cell for nearest substations`///
  },
/// cp: the caption lines window, days, actual, flashes, refresh, searched, warning and footer. Every number is either
/// measured or named unknown; a day never searched is never zero (complexity 82: see reports/V-maintain.md).
cp=(r,now,k)=>{///
    let w=r.w,x=r.idx,v=r.cov,nz=` (${U})`,L={///
      window:'',days:'',actual:'',flashes:'',refresh:'',searched:'',warning:'',footer:FOOTER///
    };
L.window=w.custom?`Window  UTC dates ${ymd(w.s)} to ${ymd(MX(w.s,w.e-1))} inclusive (${pl(Math.ceil(w.span/DAY),'day')}${w.atLatest?', to now':''})`:`Window  ${w.label} · ${dt(w.s)} → ${de(w.s,w.e)} UTC · ${w.atLatest?'latest':'earlier page'}`;
L.days=r.mode==='feed'?`${r.old?'Last 7 days only (live feed)':'Live 7-day feed'} · ${NA(r.ie)}${/404/.test(r.ie)?'':': '+r.ie} · ${r.old?'earlier days '+U:'hours searched unknown'}`:r.before?`Before the 1-year archive (from ${dm(x.cutoff)}): never searched${nz}`:!v?'':hz(w)?(v.f<=0?`None of the ${w.label} searched yet${nz}`:k&&/READY|EMPTY/.test(k.st)?`All ${w.label} searched (${dt(v.a)} → ${de(v  … [line shortened here: 836 characters; full line on GitHub]
if(v&&v.bf>0&&v.f<=0&&x)L.days+=` · archive starts ${dm(x.covStart)}`;
if(w.clamped)L.window+=' · start clamped to retention start '+x.cutoffDate;
if(r.fail){L.warning=r.ie&&!x?`Archive unavailable: ${r.ie} — nothing shown (${U})`:r.fail;return L}
if(r.before){///
      L.warning=`Window predates the archive (began ${T(x.covStart)}; retention from ${x.cutoffDate}) — ${U}`;///
      return L///
    }
r.out=0;try{let b=mh().getBounds();r.out=r.ev.filter(f=>!b.contains(f.geometry.coordinates)).length}catch(_){}
let n=r.ev.length,first=n?`Actual  first ${Ts(tm(r.ev[0]))} · last ${Ts(tm(r.ev[n-1]))}`:'',
drawn=(!n?'':` · ${N(n)} drawn as ${r.cl?'clusters':'points'} (cap ${N(cap())})`)+(r.ev&&r.ev.bad?` · ${N(r.ev.bad)} malformed records rejected`:'')+(r.out?` · ${N(r.out)} of ${N(n)} outside the current view`:'');
if(r.mode==='feed'){let m=r.meta,P=(k,f=T)=>f(DP(m[k]));
L.refresh=`Refresh live feed ${P('query_end_utc')} (last collection window ${P('query_start_utc')} → ${P('query_end_utc')}; latest detection ${P('latest_detection_utc',Ts)}; 7-day retention; ${NA(r.ie)}: ${r.ie}; earlier hours ${U})`;
L.searched='Searched EUMETSAT unknown (live feed records only its last collection window)';///
      if(r.old)L.warning=NA(r.ie)+': earlier coverage '+U
L.actual=first||`Actual  none seen in the 7-day feed (${U})`;L.flashes=`Flashes ${F7(r)}${drawn}`}
else if(r.mode==='detail'){///
      L.actual=r.fl.length?'Actual  unknown (day files failed)':first||'Actual  no archived flashes within this window';
L.flashes=(r.sk.length?`Flashes ${N(r.arch)} archived on the overlapping UTC dates (index, whole days) · ${N(n)} downloaded from the newest ${r.ld.length} of ${r.ld.length+r.sk.length} days (budget ${N(BUDGET)} flashes / 32 MB; ${r.sk.length} days not loaded)${drawn}`:`Flashes ${r.fl.length?`${N(r.ic)} in index · ${N(n)} loaded`:N(n)+' archived in window'}${drawn}`)+(r.gd?' · '+DN(r):'')///
    }
else{let o=r.rows.filter(y=>y.first_observation_utc),k=r.rows.length;
L.actual=o.length?`Actual  on the ${k} overlapping UTC dates: first ${Ts(DP(o[0].first_observation_utc))} · last ${Ts(DP(o[o.length-1].last_observation_utc))} (whole UTC days)`:`Actual  no archived flashes on the ${k} overlapping UTC dates`;
L.flashes=`Flashes ${N(r.arch)} archived on ${k} overlapping UTC dates · ${r.gd?`${DN(r)}${r.clp&&!r.big?` · LOAD POINTS adds the newest ${N(MN(BUDGET,r.arch))} flashes`:''}`:`none drawn (summary mode; ${r.clp?`index sum ${r.budget} exceeds the budget; ${r.big?'newest day alone exceeds it; none drawn':`LOAD POINTS draws up to the newest ${N(BUDGET)}`}`:'points load automatically within the budget'  … [line shortened here: 439 characters; full line on GitHub]
    }
if(x)L.refresh=`Refresh archive ${T(x.gen)} (${AGO(now-x.gen)} ago; expected every ${x.iv} h)${stale(x.gen,now,x.lastScan||x.gen)?' · overdue':''}`;
let c=r.mode!=='feed'&&r.cov;if(c){let warn=[];
L.searched=c.f>0?`Searched EUMETSAT ${du(c.f*w.span)} of ${du(w.span)}${c.a!==null?` · ${T(c.a)} → ${T(c.b)}`:''}`:c.l?'Searched EUMETSAT: shard lost (integrity alert), '+U:'Searched EUMETSAT none of this window — no collection run covers it';
if(c.ny>0)warn.push(`Not yet searched: last ${AGO(c.ny)} of window (${U})`);
if(c.bf>0&&x&&!c.u.length)warn.push(`Unknown: ${ymd(w.s)} to ${ymd(MN(w.e,x.covStart)-1)} precede archive start ${T(x.covStart)} (not zero)`);
if(c.l)warn.push(`${c.l} days lost from the archive (integrity alert), ${U}`);///
      if(c.u.length)warn.push(`Unknown: ${c.u.length} of ${c.d} UTC dates have no collection run`);
if(r.fl.length)warn.push(`${r.fl.length} of ${r.rq} day files failed (${r.fl.map(f=>f.date+' '+f.error).join(', ')}); points incomplete, counts from index`);
let ub=(r.rows||[]).filter(y=>[y.first_observation_utc,y.last_observation_utc].some(t=>t!=null&&!isFinite(DP(t)))).length;///
      if(ub)warn.push(`${N(ub)} archive entr${ub==1?'y':'ies'} unreadable (malformed timestamp; ${U})`);
if(c.f<1&&!warn.length)warn.push('Unknown: gaps between collection runs inside this window (not zero)');///
      L.warning=warn.join(' · ')///
    }
if(k&&/UNK|PAR/.test(k.st)&&/^Flashes 0 a/.test(L.flashes))L.flashes+=' (gaps unknown)'
if(v&&v.f<=0&&!v.l&&r.mode!=='feed'&&!r.fl.length){///
      L.flashes='Flashes not yet searched'+nz;///
      L.actual='Actual  not yet searched'///
    }
return L},

08 Map

A JavaScript file in the lightning folder of GridAtlas that maps the Renewable Energy Planning Database (REPD) register and substations.

rendergridatlas / tools/lightning/src/08-map.js · lines 1–176 of 176 · Not reached from any entry point (candidate for review)

What it does
It maps the REPD register and substations. Defines go. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: the REPD register, substations.
What it achieves
The map handle, the card position, the cell layers, the point layers and the tap handler.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
go
Defines here
go
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/08-map.js:1-176 · blob 313d45ecdc9eb90fc488340e80856ebfc4f8036d · 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
/// 08 map: the map handle, the card position, the cell layers, the point layers and the tap handler.
///
/// mh: the original's MapLibre map (window.__GRIDATLAS_V9_MAP__), or null. sf: the text font the style already uses.
mh=()=>{let m=window.__GRIDATLAS_V9_MAP__;return m&&typeof m.addSource==='function'?m:null},
sf=m=>{///
    try{///
      for(let l of m.getStyle().layers||[]){///
        let f=l.type==='symbol'&&l.layout&&l.layout['text-font'];///
        if(AI(f)&&f.length&&typeof f[0]==='string')return f///
      }///
    }catch(_){}return['Open Sans Regular']///
  },
/// pc: close the card and its neon layers. cs: strip format characters (bidi) and cap at 200 (LR-security). el: element
/// with inline style and text (DOM: shell classes, inline styles on own nodes only).
HIT=SRC+'-hit',OTH='gridatlas-offtakers-hit',CEL=SRC+'-cell',CNT=LAYER+'-count',pc=()=>{if(S.pp){S.pp.remove();S.pp=null}nc()},
cs=v=>(v+'').replace(/\p{Cf}/gu,'').slice(0,200),///
  el=(t,css,s)=>{///
    let e=document.createElement(t);///
    if(css)e.style.cssText=css;///
    if(s!=null)e.textContent=s;///
    return e///
  },
/// cpos: dock the card at the bottom of the map like the original's (kv-card), lifted clear of the original's bottom
/// controls, never over the menu bar. M2R-layout F1 (MAJOR-1): an open card never rises above the container top + 320 px.
/// M6: at most 45 % of the map height (at least 200 px), so the origin and the links stay in view above the open card.
/// M2R-camera fix C (fixes-m4): on a map under 500 px tall with at least 300 px beside the card, the card docks right (c.sd).
cpos=()=>{///
    let c=S.pp,m=mh();///
    if(!c||!m)return;///
    let k=gr(m.getContainer()),q=Q('gridatlas-menu-bar'),t=MX(0,(q?gr(q).bottom:0)-k.top)+8,w=MN(480,///
      k.width-16),sd=c.sd=k.height<500&&k.width-w>=300,L=sd?k.right-8-w:k.left+(k.width-w)/2,h=c.offsetHeight||0;///
    c.style.marginRight=sd?'0':'auto';///
    let b=8;
for(let o of[Q('gridatlas-dash-toggle'),document.querySelector('.map-controls')]){///
      let r=o&&gr(o);///
      if(r&&r.height&&r.right>L&&r.left<L+w&&r.top<k.bottom&&r.bottom>k.top)b=MX(b,k.bottom-r.top+8)///
    }
if(b+h>k.height-t)b=8;///
    c.bb=b;///
    c.style.bottom=b+'px';///
    c.style.maxHeight=MX(44,MN(k.height-t-b,MX(200,k.height*.45|0)))+'px'///
  },
/// cx: remove every Lightning source and layer.
cx=()=>{///
    let m=mh();///
    pc();///
    if(m)try{///
      for(let l of[CNT,HIT,LAYER])if(m.getLayer(l))m.removeLayer(l);///
      if(m.getSource(SRC))m.removeSource(SRC);///
      dd()///
    }catch(e){note(e)}S.mode=null///
  },
/// Cells: REPD-style graduated core (n <= 3 about 1 px, faint) and a glow for the top 5 %, violet ramp on log10 n
/// (1/3/10/30/100/300); ids avoid 'l-'. RP: the original's project and substation layers, which win a tap; *glow* layers
/// never do (LR-taps F3). Cells sit below the original's projects.
CS=SRC+'-cells',///
  CL=[CEL+'-glow',CEL+'-core',CEL],///
  RP=(m,a)=>{///
    try{///
      return m.getStyle().layers.filter(l=>(l.source=='src-repd'||l.id=='l-subs')&&(a||!/glow/.test(l.id)&&m.getLayoutProperty(l.id,'visibility')!='none')).map(l=>l.id)///
    }catch(_){return[]}///
  },
dd=g=>{///
    let m=mh();///
    if(!m)return;///
    for(let l of CL)if(m.getLayer(l))m.removeLayer(l);///
    if(m.getSource(CS))m.removeSource(CS);///
    if(!g||!g.fc.features.length)return;
let b=RP(m,1).find(l=>l!='l-subs')||(m.getLayer(LAYER)?LAYER:void 0),L=['log10',///
      ['get','n']],I=(x,...s)=>['interpolate',['linear'],x,...s],B=[0,///
      .48,1,1.48,2,2.48],R=v=>I(L,...B.flatMap((k,i)=>[k,v[i]])),Z=(a,///
      c,d)=>I(['zoom'],5,a,7,c,10,d),
C=R(['#5a5590','#6f68a8','#8d7fd0','#a066ff','#c23cff','#e01cff']),A=(i,p,x)=>m.addLayer({id:CL[i],type:'circle',source:CS,...x,paint:p},b);///
    m.addSource(CS,{type:'geojson',data:g.fc});
A(0,{///
        'circle-radius':Z(I(L,1.48,5,2.48,13),I(L,1.48,8,2.48,20),I(L,1.48,16,2.48,36)),'circle-color':C,'circle-opacity':I(L,///
          1.48,.15,2.48,.4),'circle-blur':1///
      },{filter:['>=',['get','n'],g.T]});
A(1,{///
        'circle-radius':Z(R([.8,1,1.2,1.7,3.2,6]),R([1,1.2,1.6,2.4,5,9]),///
          R([2,2.5,3.5,6,12,20])),'circle-color':C,'circle-opacity':R([.22,.3,.42,.6,.85,.95]),'circle-stroke-width':I(L,///
          1.48,0,2,.6),'circle-stroke-color':'#140a2a'///
      },{layout:{'circle-sort-key':['get','n']}});
A(2,{'circle-radius':22,'circle-opacity':0})},
/// dw: one source, a points layer, an invisible 44 px hit layer and (clustered) count labels; hidden until data.
dw=(fc,cl)=>{///
    let m=mh(),K={///
      'circle-stroke-width':1.5,'circle-stroke-color':'#1a1a1a'///
    },Z=k=>['interpolate',['linear'],['zoom'],5,k(6),8,k(8),11,k(10)];///
    if(!m)E('no map');///
    let mode=cl?'cluster':'raw';///
    if(S.mode&&S.mode!==mode)cx();
if(!m.getSource(SRC)){///
      m.addSource(SRC,Object.assign({type:'geojson',data:FC()},cl?{cluster:true,clusterRadius:40,clusterMaxZoom:10}:{}));
m.addLayer({///
          id:LAYER,type:'circle',source:SRC,layout:{visibility:'none'},paint:cl?{///
            'circle-radius':Z(x=>['case',['has','point_count'],['step',['get','point_count'],12,100,16,1000,20,10000,26],x]),...K,'circle-color':['case',///
              ['has','point_count'],'#ffb000','#fff3a0'],'circle-opacity':0.9///
          }
:{'circle-radius':Z(x=>x),...K,'circle-color':'#fff3a0','circle-opacity':0.95}});
m.addLayer({///
          id:HIT,type:'circle',source:SRC,layout:{visibility:'none'},paint:{'circle-radius':22,'circle-opacity':0}///
        });
if(cl)try{///
        m.addLayer({///
            id:CNT,type:'symbol',source:SRC,filter:['has','point_count'],layout:{///
              visibility:'none','text-field':['get','point_count_abbreviated'],'text-font':sf(m),'text-size':11///
            },paint:{'text-color':'#000'}///
          })///
      }catch(e){note('count labels: '+msg(e))}S.mode=mode///
    }
m.getSource(SRC).setData(fc);///
    let v=fc.features.length?'visible':'none';///
    for(let l of[LAYER,HIT,CNT])if(m.getLayer(l))m.setLayoutProperty(l,'visibility',v)///
  },
/// tap: a flash (or cluster) under the tap wins, then the nearest cell unless a project or substation of the original is
/// hit. No work while loading or with no hit layer (LR-regress m2, LR-taps F2). Other click handlers always run.
tap=e=>{///
    let m=mh();///
    if(!S.on||S.busy||!m||!(m.getLayer(HIT)||m.getLayer(CEL)))return;///
    /// a tap another overlay owns (a potential-offtakers dot under it, or a tap it has claimed) is not this module's: no card
    /// change, no cell tap and no REPD layer hand-over, so a layer this module switched on is never given to the reader by a tap
    /// it did not handle (R-taps MAJOR: Drax with both overlays on left bess ticked after both were OFF).
    if(e.gridatlasClaim||m.getLayer(OTH)&&m.queryRenderedFeatures(e.point,{layers:[OTH]}).length)return;///
///#if dots
    /// dots: a tap on a drawn listed site opens that site's project view, as its row does.
    let rq=S.pp&&S.pp.ps&&m.getLayer(NI[13])&&m.queryRenderedFeatures(e.point,{layers:[NI[13]]})[0],rg=rq&&S.pp.ps[rq.properties.k];///
    if(rg)return RpV(m,S.pp,rg);///
    let px=e.point.x??e.point[0],///
///#else
    let px=e.point.x??e.point[0],///
///#endif
    py=e.point.y??e.point[1],Y=l=>m.getLayer(l)?m.queryRenderedFeatures(e.point,{layers:[l]}):[];///
    let f=null,dm=Infinity;
for(let q of Y(HIT)){///
      let g=q.properties&&!q.properties.cluster&&S.res&&S.res.ev[q.properties.i],a=m.project((g||q).geometry.coordinates),d=(a.x-px)**2+(a.y-py)**2;///
      if(d<dm){dm=d;///
        f=q}///
    }pc();///
    if(!f){///
      let rp=RP(m),h=rp.length&&m.queryRenderedFeatures(e.point,{layers:rp});///
      /// layers: a tap on a drawn REPD dot belongs to the engine and closes the card (as L3); the tapped dot's technology is handed
      /// to the reader and every other layer this module switched on is released (M2R-l3regress MINOR M3-L1, fixes-m4).
      if(///
///#if dots
        h&&h.length)return;///
///#else
        h&&h.length){///
        for(let q of h)S.ly&&S.ly.delete(q.properties&&q.properties.tech);///
        return Ry()///
      }///
///#endif
      for(let q of Y(CEL)){///
        let p=q.properties||{},k=cb(p),a=k&&m.project([p.lon,p.lat]),d=k?(a.x-px)**2+(a.y-py)**2:1/0;///
        if(d<dm){dm=d;///
          f=p}///
      }///
///#if dots
      return f&&cc(m,f)///
    }
///#else
      return f?cc(m,f):Ry()///
    }
///#endif
/// A cluster tap zooms in; cm(m) first drops the module's pending framing (M4, M2R-taps T1).
let p=f.properties||{};///
    if(p.cluster){///
      let go=z=>(cm(m),m.easeTo({center:f.geometry.coordinates,zoom:z})),z=m.getSource(SRC).getClusterExpansionZoom(p.cluster_id,(err,z)=>err||go(z));///
      if(z&&z.then)z.then(go,note);///
      return///
    }
let g=S.res&&p.s===S.res.s&&S.res.ev[p.i];///
    if(!g)return;///
    let[x,y]=g.geometry.coordinates,id=g.id==null?'(none)':cs(g.id);
cd(m,x,y,'Lightning flash','Flash '+Ts(tm(g)),`lat ${y.toFixed(3)}, lon ${x.toFixed(3)} · ID ${sid(id)}`,'Flash ID '+id,'optical flash')///
  },