In this section
- Pilot Lightning geodesy · cosmic / tools/explore/theme/pilot-lightning.js lines 1–700
Pilot Lightning
A JavaScript file in the theme folder of Cosmic that maps UK lightning and grid substations, using SHA-256 and haversine, and uses data from the GridAtlas, lightning and PipelineNews repositories.
geodesycosmic / tools/explore/theme/pilot-lightning.js · lines 1–700 of 880 · Entry point · pattern describeOpticalFeedEvidence (shared by 2 files)
- What it does
- It maps UK lightning, grid substations, solar and the REPD register. Defines 86 functions or classes, including mm, finite, validPoint, rowLocation, positive. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 275kV (all 132kV or above)): 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: solar, the REPD register, 275kV.
- Inputs & outputs
- In: data source: gridatlas data; data source: lightning data; data source: pipelinenews data; GeoJSON file uk_lightning.geojson; JSON file index.json; GeoJSON file grid_substations.geojson; GeoJSON file kv.geojson; form fields (user input). Voltage levels named: 275kV.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- It builds atlas v9 deep link (`buildAtlasV9DeepLink`), parses optical feed (`parseOpticalFeed`) and describes optical feed evidence (`describeOpticalFeedEvidence`). W08 (FLASHOVER-31); integrated and maintained by W10 (CAPSTAN-41). Its code works with 275 kV. It responds to click and submit events.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · script
- Uses
- GridAtlas — Atlas Page (estate URL), GridAtlas — Index Page (estate URL)
- Used by
- loaded by Pilot (script src), mentioned in Standalone (comment link)
- Produces
- mm, finite, validPoint, rowLocation, positive, capacityOf, solarProject, numberInRange, projectFields, buildAtlasV9DeepLink, FEED_CONTRACT, utc
- Defines here
- mm, finite, validPoint, rowLocation, positive, capacityOf, solarProject, numberInRange, projectFields, buildAtlasV9DeepLink, FEED_CONTRACT, utc, finite, validCoordinates, parseOpticalFeed, describeOpticalFeedEvidence, q, safeBase, pad, ymd, ds, T, fmt, fetchJSON, compass, words, bearingText, interp, rampRGB, zoomI
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-lightning.js:1-700 · blob 08456acac8c54365d0461b8f58ef5a5f222ec9d7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/* pilot-lightning.js - W08 (FLASHOVER-31); integrated and maintained by W10 (CAPSTAN-41).
Lightning context: optical flashes and the nearest substations, geographical context only (not a risk assessment,
not a surge study). Released as an ARCHIVE (owner, 2026-12-06): the collector last ran 2026-11-01; not live.
- 12-month (and 6M/3M/30D) optical-flash density from the same published monthly files
(Ventusltd/lightning data/history), the same day checks, the same REPD-30 km cell mask,
colours and circle sizes as GridAtlas atlas/modules/202610291043-uk-lightning-overlay.js;
- tap a flash: the Ventus Grid Engine lightning context GridAtlas's lab uses (ventus-grid-engine@69b4e88
createLightningContextEngine, vendored verbatim in pilot-estate.js): six nearest substations at the chosen minimum
voltage, no distance cut-off; REPD solar within 20 km. Engine geodesy and deep links come from PILOT.estate.
Optical flashes are not confirmed ground strikes. Distances are straight-line, not recorded fault data, and never a
current path or surge-protection study. */
(function () {
'use strict';
if (!window.PILOT) return;
var P = window.PILOT;
P.module('lightning', { version: '2', owner: 'W08' });
/* ==== BEGIN GENERATED ENGINE BLOCK (gen_engine_block.py; do not edit by hand) ==== */
/* Engine geodesy, voltages and the MAP deep-link contract come from PILOT.estate (pilot-estate.js: ventus-grid-engine
engine/v9-geodesy.js and deeplink/contract.js vendored verbatim, sha256-pinned, the same code as before), so nothing
here duplicates the estate. The earlier 5-within-40-km substation rule (gridatlas sld-without-layout) is retired:
substations now come from the engine's lightning context, as the GridAtlas lab. */
const { EARTH_RADIUS_KM, distanceKm, representativePoint, voltagesKv, initialBearingDeg } = P.estate.engine;
const { IDENTITY_PARAM, PARAMS, CANONICAL_RECEIVER, RETIRED_RECEIVERS, isRetiredReceiver, buildDeepLink } = P.estate.deeplink;
/* from gridatlas@f944f8dcbc09 atlas/modules/202610291043-uk-lightning-overlay.js (file sha256 15ff1e37890770ef): mm (calendar-month window) and LM (cells within 30 km of a REPD site); transform: MN -> Math.min */
const mm=(t,k)=>{let d=new Date(t),day=d.getUTCDate();d.setUTCDate(1);d.setUTCMonth(d.getUTCMonth()-k);d.setUTCDate(Math.min(day,new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+1,0)).getUTCDate()));return d.getTime()};
const LM=()=>{if(!LM.a){let a=LM.a=new Uint8Array(16800);let p=0,v=1;for(const c of'M3bCjeCie83C7rC6sC6r4583Bmr1a28BmAg26BaAqB7AsB6AsB5AtB3AuB4AtB4AsB5AsAw81AqAvB0AvAzAxB0AwB1AvB3AuB3AuB8ArB6AtB4AvB0AwAzAuAyAwAzAxAyAyAxB0AvB0AuB1AmBaAmBbAkBe82A7Bh47A5BrA4Av4e5aA3Am71b7a6A3Alo4b4A4Ajr3c2A5Agv3c1A5Agw3AfAhz3AbAkA0161A3AnB9AoB5AsB1AxAyAzAwB1l2A8B2AtB9AnBbAkBdAiBdAjBcAjBdAiBfAgBiAdBnA6Bh44A5Bh81A6BgAg … [line shortened here: 682 characters; full line on GitHub]
/* from ventus-grid-engine@69b4e88c8464 engine/lightning-click-context.js (file sha256 a4375943d9fa1cc4): finite, validPoint, positive, capacityOf, solarProject, rowLocation (pinned draft SHA used by GridAtlas labs/lightning-grid) */
const finite = (x) => typeof x === 'number' && Number.isFinite(x);
const validPoint = (lon,lat) => finite(lon) && finite(lat)
&& lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90;
const rowLocation = (row) => {
const p=row?.location, geom=row?.geometry;
const centre=representativePoint(geom);
const lon=p?.lon ?? p?.longitude ?? centre?.[0] ?? row?.longitude;
const lat=p?.lat ?? p?.latitude ?? centre?.[1] ?? row?.latitude;
return validPoint(lon,lat)?{lon,lat}:null;
};
const positive = n => finite(n) && n>0;
const capacityOf = project => {
if (project?.capacity_mw == null || project?.capacity_mw === '') return null;
const n=Number(project.capacity_mw);
return positive(n)?n:null;
};
const solarProject = (project) => {
const p=project?.type==='Feature' ? project.properties : project;
const t=String(p?.technology||p?.repd_technology||'').toLowerCase();
if(!t.includes('solar'))return null;
const location=rowLocation(project);
if(!location || (p?.geometry_status && p.geometry_status!=='valid'))return null;
const repdRef=String(p?.repd_ref??'').trim();
if(!/^[0-9]+$/.test(repdRef))return null;
const mw=capacityOf(p);
return {repd_ref:repdRef,name:String(p.name||'Unnamed REPD solar project'),
location,capacity_mw:mw,technology:'solar'};
};
/* from pipelinenews@ce0a1a16f0e1 releases/202611132345-pipelinenews/assets/202609040044-atlas-pointer-deep-link.mjs (file sha256 7ab16bbc704324d1): RECEIVER, technologies, QUERY_PARAMETER_ORDER, numberInRange, projectFields, buildAtlasV9DeepLink verbatim; `export` dropped */
const RECEIVER = Object.freeze({
base_url: "https://ventusltd.github.io/gridatlas/atlas/",
hostname: "ventusltd.github.io",
pathname: "/gridatlas/atlas/",
});
const CANONICAL_PROJECT_TECHNOLOGIES = Object.freeze([
"act", "bess", "biomass", "caes", "flywheel", "geothermal",
"hydro", "hydrogen", "other", "solar", "solar_roof", "tidal",
"wind_offshore", "wind_onshore",
]);
const TECHNOLOGIES = new Set(CANONICAL_PROJECT_TECHNOLOGIES);
const QUERY_PARAMETER_ORDER = Object.freeze([
"repd_ref", "project", "technology", "capacity_mw",
"latitude", "longitude", "zoom",
]);
const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/u;
const DEFAULT_ZOOM = 12;
function numberInRange(value, minimum, maximum) {
if (value === null || value === undefined || value === "") return null;
const number = Number(value);
return Number.isFinite(number) && number >= minimum && number <= maximum
? number : null;
}
function projectFields(project) {
const coordinates = Array.isArray(project?.ll) ? project.ll : null;
return {
repdRef: String(project?.repd_ref ?? project?.ref ?? "").trim(),
name: String(project?.name ?? project?.n ?? "").replace(/\s+/gu, " ").trim(),
technology: String(project?.technology ?? project?.t ?? "").trim(),
capacity: numberInRange(project?.capacity_mw ?? project?.c, 0, Number.MAX_VALUE),
latitude: numberInRange(project?.latitude ?? coordinates?.[1], -90, 90),
longitude: numberInRange(project?.longitude ?? coordinates?.[0], -180, 180),
geometryStatus: project?.geometry_status,
};
}
function buildAtlasV9DeepLink(project) {
const fields = projectFields(project);
if (fields.geometryStatus !== undefined && fields.geometryStatus !== "valid") return "";
if (!/^[1-9]\d*$/u.test(fields.repdRef)) return "";
if (!TECHNOLOGIES.has(fields.technology)) return "";
if (CONTROL_CHARACTER.test(fields.name)) return "";
if (fields.capacity === null || fields.latitude === null || fields.longitude === null) return "";
const url = new URL(RECEIVER.base_url);
url.searchParams.set("repd_ref", fields.repdRef);
url.searchParams.set("project", fields.name);
url.searchParams.set("technology", fields.technology);
url.searchParams.set("capacity_mw", String(fields.capacity));
url.searchParams.set("latitude", String(fields.latitude));
url.searchParams.set("longitude", String(fields.longitude));
url.searchParams.set("zoom", String(DEFAULT_ZOOM));
return url.href;
}
/* from gridatlas@f944f8dcbc09 atlas/labs/lightning-grid/feed-contract.mjs (file sha256 78a1cf0b8628a329): parseOpticalFeed, describeOpticalFeedEvidence verbatim (lines 7-101), wrapped in a scope; `export` dropped */
const FEED_CONTRACT = (() => {
const hour=3600000;
const utc=t=>typeof t==='string' && /(?:Z|\+00:00)$/i.test(t) && Number.isFinite(Date.parse(t))
? Date.parse(t) : NaN;
const finite=n=>typeof n==='number' && Number.isFinite(n);
const validCoordinates=p=>Array.isArray(p) && p.length>=2
&& finite(p[0]) && finite(p[1])
&& p[0]>=-180 && p[0]<=180 && p[1]>=-90 && p[1]<=90;
function parseOpticalFeed(data,{nowMs=Date.now(),staleAfterHours=6}={}){
if(!finite(nowMs)||!finite(staleAfterHours)||staleAfterHours<=0)
throw new TypeError('Invalid clock or freshness threshold');
if(data?.type!=='FeatureCollection'||!Array.isArray(data.features))
throw new Error('Source is not a GeoJSON FeatureCollection');
const meta=data.metadata||{};
const queryStartMs=utc(meta.query_start_utc);
const queryEndMs=utc(meta.query_end_utc);
if(Number.isFinite(queryEndMs)&&queryEndMs>nowMs+5*60000)
throw new Error('Feed query end is in the future; coverage UNKNOWN');
if(Number.isFinite(queryStartMs)&&Number.isFinite(queryEndMs)&&queryStartMs>queryEndMs)
throw new Error('Feed query window is inverted; coverage UNKNOWN');
const selected=new Map(),conflicting=new Set();
let rejected=0,duplicate=0;
for(const f of data.features){
const id=f?.id==null?'':String(f.id).trim();
const time=utc(f?.properties?.time_utc);
const coordinates=f?.geometry?.coordinates;
if(!id || f?.type!=='Feature' || f?.geometry?.type!=='Point'
|| !validCoordinates(coordinates)
|| f?.properties?.observation_kind!=='optical_lightning_flash'
|| !Number.isFinite(time)||time>nowMs+5*60000
|| (Number.isFinite(queryEndMs)&&time>queryEndMs+5*60000)){
rejected++;continue;
}
if(selected.has(id)){
duplicate++;
const old=selected.get(id);
if(old.properties.time_utc!==f.properties.time_utc
|| old.geometry.coordinates[0]!==coordinates[0]
|| old.geometry.coordinates[1]!==coordinates[1])conflicting.add(id);
continue;
}
selected.set(id,f);
}
for(const id of conflicting){selected.delete(id);rejected++}
const observations=[...selected.values()].sort((a,b)=>
Date.parse(b.properties.time_utc)-Date.parse(a.properties.time_utc));
const freshness=Number.isFinite(queryEndMs)
?(nowMs-queryEndMs>staleAfterHours*hour?'STALE_QUERY':'RECENT_QUERY')
:'QUERY_TIME_UNKNOWN';
const latestMs=observations.length?Date.parse(observations[0].properties.time_utc):NaN;
const latestDeclaredMs=utc(meta.latest_detection_utc);
const warnings=[];
if(rejected||duplicate)warnings.push(rejected+' rejected/ambiguous, '+duplicate+' duplicate source records');
if(freshness==='STALE_QUERY')warnings.push('Collector query is stale; later optical observations UNKNOWN');
if(freshness==='QUERY_TIME_UNKNOWN')warnings.push('Last successful query time UNKNOWN');
if(Number.isFinite(latestDeclaredMs) && Number.isFinite(latestMs)
&& Math.abs(latestMs-latestDeclaredMs)>60000)
warnings.push('Latest detected timestamp differs from feed metadata');
if(Number.isFinite(meta.total_before_display_cap)
&& meta.total_before_display_cap<data.features.length)
warnings.push('Feed source total is inconsistent with displayed rows');
if(data.features.length && !observations.length)
throw new Error('All source records invalid or ambiguous; observations UNKNOWN, not zero');
return Object.freeze({
observations,
evidence:Object.freeze({
raw_records:data.features.length,accepted:observations.length,
rejected,duplicates:duplicate,conflicting_ids:conflicting.size,
latest_detection_utc:Number.isFinite(latestMs)?new Date(latestMs).toISOString():null,
query_start_utc:Number.isFinite(queryStartMs)?new Date(queryStartMs).toISOString():null,
query_end_utc:Number.isFinite(queryEndMs)?new Date(queryEndMs).toISOString():null,
query_freshness:freshness,
query_age_hours:Number.isFinite(queryEndMs)?Math.max(0,(nowMs-queryEndMs)/hour):null,
retention_days:Number.isFinite(meta.retention_days)?meta.retention_days:null,
cumulative_coverage:'UNKNOWN',
unobserved_interval:'UNKNOWN',
warnings
})
});
}
function describeOpticalFeedEvidence(e){
const last=e.latest_detection_utc?e.latest_detection_utc.replace('T',' ').replace('Z',' UTC')
:'not recorded';
const query=e.query_end_utc?e.query_end_utc.replace('T',' ').replace('Z',' UTC')
:'UNKNOWN';
const freshness=e.query_freshness==='STALE_QUERY'?'STALE COLLECTOR QUERY'
:e.query_freshness==='QUERY_TIME_UNKNOWN'?'QUERY FRESHNESS UNKNOWN'
:'recent collector query (not complete coverage)';
return 'Authentic optical observations: '+e.accepted+' accepted of '+e.raw_records+
' source records. Latest optical detection: '+last+'. Latest collector query ended: '+
query+' ('+freshness+'). Seven-day retention is not a verified seven-day search: '+
'unsearched hours and older history UNKNOWN, not zero.'+
(e.warnings.length?' SOURCE WARNINGS: '+e.warnings.join('; ')+'.':'');
}
return { parseOpticalFeed, describeOpticalFeedEvidence };
})();
/* from grid-distance-maths@8e91b07d8312 src/geodesy.mjs (file sha256 69234c6996c54755): STRAIGHT_LINE_CAVEAT verbatim */
const STRAIGHT_LINE_CAVEAT = P.geo.STRAIGHT_LINE_CAVEAT; // grid-distance-maths, via PILOT.estate
/* ==== END GENERATED ENGINE BLOCK ==== */
/* ---------- provenance: every engine function used, tied to the estate's tools ---------- */
var EC = 'https://code.globalgrid2050.com/explore-code/s/';
var VGE = 'Ventusltd/ventus-grid-engine@ad566356a44e', GAc = 'Ventusltd/gridatlas@f944f8dcbc09';
var PROV = [
{ fn: 'distanceKm', what: 'straight-line distance (haversine, R 6378.137 km)', src: VGE + ' engine/v9-geodesy.js L29-47', sec: '0718', vedic: 'MEASURE', gg: 'GG2050-VEDIC-000001', spider: '36ba3e77237b67ee' },
{ fn: 'initialBearingDeg', what: 'bearing from the point to each substation', src: VGE + ' engine/v9-geodesy.js L133-139', sec: '0718', vedic: 'BEARING', gg: 'GG2050-VEDIC-000005', spider: 'd25f9e5dd6ac7cc7' },
{ fn: 'representativePoint', what: 'substation outline to one point', src: VGE + ' engine/v9-geodesy.js L63-81', sec: '0718', vedic: 'REPRESENT', gg: 'GG2050-VEDIC-000002', spider: '47a2cb69d8e9cde3' },
{ fn: 'voltagesKv', what: 'OSM voltage tag to kV', src: VGE + ' engine/v9-geodesy.js L89-107', sec: '0718', vedic: 'VOLTAGE', gg: 'GG2050-VEDIC-000003', spider: '24d9457f7ef90d24' },
{ fn: 'createLightningContextEngine / selectFlash', what: 'Ventus Grid Engine lightning context, as the GridAtlas lab: 6 nearest substations at the chosen minimum voltage, no distance cut-off; solar within 20 km (30)', src: 'Ventusltd/ventus-grid-engine@69b4e88c8464f0310bd67e47ec83ee8afa9e1921 engine/lightning-click-context.js L76-132 (verbatim in pilot-estate.js, file sha256 a4375943d9fa1cc4) … [line shortened here: 452 characters; full line on GitHub]
{ fn: 'loadSubstations (qualifying loop)', what: 'GridAtlas: which substations count', src: GAc + ' atlas/modules/202611222130-sld-without-layout.js L3762-3796', sec: '0395', vedic: null, gg: null, spider: '628bf3331f10f342' },
{ fn: 'mm, LM, gd', what: 'GridAtlas: month window, REPD-30 km mask, cell sums', src: GAc + ' atlas/modules/202610291043-uk-lightning-overlay.js', sec: '0525', vedic: null, gg: null, spider: null },
{ fn: 'buildAtlasV9DeepLink', what: 'Open in GridAtlas: the Pipeline News MAP link (repd_ref, project, technology, capacity_mw, latitude, longitude, zoom=12; no bearing)', src: 'Ventusltd/pipelinenews@ce0a1a16f0e1 releases/202611132345-pipelinenews/assets/202609040044-atlas-pointer-deep-link.mjs L76-95', sec: '0707', vedic: null, gg: null, spider: null },
{ fn: 'parseOpticalFeed', what: 'GridAtlas lab feed contract, 6 h staleness', src: GAc + ' atlas/labs/lightning-grid/feed-contract.mjs L15-86', sec: '0514', vedic: null, gg: null, spider: null },
{ fn: 'cellOf', what: 'point to 0.1° cell, rounded before flooring', src: 'Ventusltd/lightning@2882145e28a0 grid.py cell_of', sec: '1885', vedic: null, gg: null, spider: null },
{ fn: 'buildDeepLink', what: 'engine deep-link contract (same receiver; ported for reference)', src: VGE + ' deeplink/contract.js L198-220', sec: '1898', vedic: 'BUILD PROJECT MAP LINK', gg: 'GG2050-VEDIC-000086', spider: 'da5d11dfdf322423' },
{ fn: 'STRAIGHT_LINE_CAVEAT', what: 'canonical caveat text (grid-distance-maths, R_ATLAS 6378.137, same haversine as the engine)', src: 'Ventusltd/grid-distance-maths@8e91b07 src/geodesy.mjs L400-410', sec: '0509', vedic: null, gg: null, spider: null },
{ fn: 'solarProject', what: 'engine lab: REPD solar rows near the point', src: 'Ventusltd/ventus-grid-engine@69b4e88c8464 engine/lightning-click-context.js (draft SHA pinned by GridAtlas labs/lightning-grid)', sec: '0514', vedic: null, gg: null, spider: null }
];
/* ---------- sources (photon rule: streamed, never copied) ---------- */
var RAW = 'https://raw.githubusercontent.com/Ventusltd/lightning/main/data/';
var GA_REL = 'atlas/releases/202608300453-atlas-v9/data/';
var PN_RAW = 'https://raw.githubusercontent.com/Ventusltd/pipelinenews/main/data/atlas/202608261927-atlas-solar-partition-v9-1-';
var PN_SITE = 'https://globalgrid2050.com/uk_renewables_pipeline/202611221850/';
var TITLE = 'Lightning proximity: distance to nearest substations (risk screening, not a surge study)';
var SCOPE = 'Engine-computed straight-line distances and bearings from a chosen point, as GridAtlas shows them. Not recorded fault data, not a lightning current path and not a surge-protection study (specialist firms do those). Use it to open a discussion of surge-protection coordination.';
var OBS = 'Optical flashes seen from orbit by the MTG Lightning Imager; not confirmed ground strikes.';
var CREDIT = 'Lightning: EUMETSAT MTG Lightning Imager L2-LFL (EO:EUM:DAT:0691), via Ventusltd/lightning - optical flashes, not confirmed ground strikes';
var SUB_CREDIT = 'Substations and lines: Data © OpenStreetMap contributors (via GridAtlas atlas-v9) · distances: Ventus Grid Engine';
var BOX = { w: -11.0, s: 49.5, e: 3.0, n: 61.5 };
var DAY = 864e5;
function q(name) { try { return new URLSearchParams(location.search).get(name); } catch (e) { return null; } }
function safeBase(v) {
if (!v) return null;
try {
var u = new URL(v, location.href), local = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
if (!(local || u.origin === location.origin)) return null;
return u.href.replace(/\/?$/, '/');
} catch (e) { return null; }
}
var LGB = safeBase(q('lgbase')) || RAW;
var GAB = safeBase(q('lgga')) || ((P.data && P.data.GA) || 'https://ventusltd.github.io/gridatlas/') + GA_REL;
var PNB = safeBase(q('lgpn')) ? safeBase(q('lgpn')) + '202608261927-atlas-solar-partition-v9-1-' : PN_RAW;
var src = {
feed: function () { return LGB + 'uk_lightning.geojson'; },
index: function () { return LGB + 'history/index.json'; },
grid: function (ym) { return LGB + 'history/grid/' + ym + '.json'; },
day: function (path) { return LGB + 'history/' + path; },
subs: function () { return GAB + 'grid_substations.geojson'; },
line: function (kv) { return GAB + 'grid_' + kv + 'kv.geojson'; },
solar: function (i) { return PNB + String(i).padStart(3, '0') + '.geojson'; },
base: LGB, ga: GAB
};
/* ---------- helpers ---------- */
var esc = P.esc || function (s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; });
};
function pad(n) { return (n < 10 ? '0' : '') + n; }
function ymd(t) { return new Date(t).toISOString().slice(0, 10); }
function ds(d) { return Date.parse(d + 'T00:00:00Z'); }
function T(ms) { var d = new Date(ms); return ymd(ms) + ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ' UTC'; }
function fmt(n) { return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
function fetchJSON(url) {
if (P.data && P.data.fetchJSON) return P.data.fetchJSON(url);
return fetch(url).then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status + ' ' + url); return r.json(); });
}
// Pipeline News grid-proximity scope compass (pipelinenews 202608311610-grid-proximity.mjs), plus words
var COMPASS = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var WORDS = { N: 'north', S: 'south', E: 'east', W: 'west' };
function compass(deg) { return COMPASS[Math.round(deg / 22.5) % 16]; }
function words(c) {
if (c.length === 1) return WORDS[c];
if (c.length === 2) return WORDS[c[0]] + '-' + WORDS[c[1]];
return WORDS[c[0]] + '-' + WORDS[c[1]] + '-' + WORDS[c[2]];
}
function bearingText(deg) { var c = compass(deg); return String(Math.round(deg) % 360).padStart(3, '0') + '° ' + c; }
/* ---------- GridAtlas colour and size ramps (dd(), ported) ---------- */
var RB = [0, 0.48, 1, 1.48, 2, 2.48];
var RAMP = ['#5a5590', '#6f68a8', '#8d7fd0', '#a066ff', '#c23cff', '#e01cff'].map(function (h) {
return [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
});
function interp(x, stops, vals) {
if (x <= stops[0]) return vals[0];
for (var i = 1; i < stops.length; i++) if (x <= stops[i]) {
var t = (x - stops[i - 1]) / (stops[i] - stops[i - 1]);
return vals[i - 1] + t * (vals[i] - vals[i - 1]);
}
return vals[vals.length - 1];
}
function rampRGB(L) {
return [0, 1, 2].map(function (c) { return Math.round(interp(L, RB, RAMP.map(function (r) { return r[c]; }))); });
}
function zoomI(z, a, c, d) { return interp(z, [5, 7, 10], [a, c, d]); }
function coreRadius(L, z) {
return zoomI(z, interp(L, RB, [0.8, 1, 1.2, 1.7, 3.2, 6]), interp(L, RB, [1, 1.2, 1.6, 2.4, 5, 9]), interp(L, RB, [2, 2.5, 3.5, 6, 12, 20]));
}
function coreOpacity(L) { return interp(L, RB, [0.22, 0.3, 0.42, 0.6, 0.85, 0.95]); }
function glowRadius(L, z) {
return zoomI(z, interp(L, [1.48, 2.48], [5, 13]), interp(L, [1.48, 2.48], [8, 20]), interp(L, [1.48, 2.48], [16, 36]));
}
function glowOpacity(L) { return interp(L, [1.48, 2.48], [0.15, 0.4]); }
function strokeW(L) { return interp(L, [1.48, 2], [0, 0.6]); }
/* ---------- periods and window (GridAtlas wf(), long periods) ---------- */
var PERIODS = [['30d', '30 days', 30 * DAY], ['3m', '3 months', -3], ['6m', '6 months', -6], ['12m', '12 months', -12]];
function windowFor(period, end) {
var p = PERIODS.filter(function (x) { return x[0] === period; })[0] || PERIODS[3];
var e = end, s = p[2] < 0 ? mm(e, -p[2]) : e - p[2];
return { s: s, e: e, period: p[0], label: p[1], span: e - s };
}
function windowRows(index, w) {
var cutoff = ds(index.cutoff_date_utc);
if (w.s < cutoff) { w.s = cutoff; w.span = w.e - w.s; w.clamped = true; }
return index.days.filter(function (y) { var f = ds(y.date); return f < w.e && f + DAY > w.s; });
}
function monthsNeeded(rows) {
var seen = {}, out = [];
rows.forEach(function (y) { if (y.count > 0) { var m = y.date.slice(0, 7); if (!seen[m]) { seen[m] = 1; out.push(m); } } });
return out.sort().reverse();
}
// GridAtlas gd(): day checks against the index, sums over checked days, REPD-30 km mask, glow threshold
function cellsFrom(rows, gs) {
var n = 0, st = 0, k = 0, pending = 0, ok = new Set(), c = new Map(), f = [], v = [];
rows.forEach(function (y) {
if (!(y.count > 0)) return;
var g = gs.get(y.date.slice(0, 7));
if (!g) { pending++; return; }
var d = g.days.filter(function (d) { return d.date === y.date; })[0];
if (d && d.count === y.count && d.coverage === y.coverage && d.sha256 + '' == (y.path ? [y.sha256] : y.parts.map(function (p) { return p.sha256; })) + '') { ok.add(y.date); n += y.count; } else st++;
});
gs.forEach(function (g, m) {
g.cells.forEach(function (r) {
for (var 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]);
});
});
c.forEach(function (x, cq) {
if (!LM()[cq]) return;
var lon = -11 + (cq % 140 + 0.5) / 10, lat = 49.5 + ((cq / 140 | 0) + 0.5) / 10;
k += x; v.push(x); f.push({ q: cq, n: x, lon: lon, lat: lat, L: Math.log10(x) });
});
v.sort(function (a, b) { return a - b; });
return { cells: f, n: n, k: k, st: st, pending: pending, T: Math.max(30, v[v.length * 0.95 | 0] || 0) };
}
// lightning grid.py cell_of(): round((x - origin) / 0.1, 6) before floor, so 0.1-steps never fall into the cell below
function round6(x) { var r = Math.round(Math.abs(x) * 1e6) / 1e6; return x < 0 ? -r : r; }
function cellOf(lon, lat) {
var col = Math.floor(round6((lon - BOX.w) / 0.1)), row = Math.floor(round6((lat - BOX.s) / 0.1));
col = Math.min(Math.max(col, 0), 139); row = Math.min(Math.max(row, 0), 119);
return row * 140 + col;
}
/* ---------- flashes (optional context: live feed) ---------- */
function packFlashes(fc) {
var out = { lat: [], lon: [], t: [], id: [], n: 0, dropped: 0, meta: (fc && fc.metadata) || {} };
if (!fc || fc.type !== 'FeatureCollection' || !Array.isArray(fc.features)) throw new Error('not a FeatureCollection');
fc.features.forEach(function (f) {
var p = f && f.properties, g = f && f.geometry;
if (!p || p.observation_kind !== 'optical_lightning_flash' || !g || g.type !== 'Point') { out.dropped++; return; }
var lon = +g.coordinates[0], lat = +g.coordinates[1], t = Date.parse(p.time_utc);
if (!isFinite(lat) || !isFinite(lon) || !isFinite(t) || lat < BOX.s || lat > BOX.n || lon < BOX.w || lon > BOX.e) { out.dropped++; return; }
out.lat.push(lat); out.lon.push(lon); out.t.push(t); out.id.push(String(f.id || ''));
});
out.n = out.lat.length;
return out;
}
function freshness(meta, n, now) {
now = now == null ? Date.now() : now;
var pub = Date.parse(meta && meta.published_at_utc), last = Date.parse(meta && meta.last_detection_utc);
var r = { stale: true, days: null, text: '' }; // display text only; the stale verdict is the lab contract's 6 h rule
if (isFinite(pub)) {
var age = now - pub; r.days = Math.floor(age / DAY); r.stale = age > 6 * 3600e3;
r.text = (r.stale ? 'Archive data — last collector run ' + ymd(pub) + '; not live. Feed published ' : 'Feed published ') + T(pub) + ' (' + (r.days >= 1 ? r.days + ' day' + (r.days === 1 ? '' : 's') : Math.round(age / 3600e3) + ' h') + ' ago)';
} else r.text = 'Archive data — feed publication time unknown; not live';
r.text += n > 0 ? (isFinite(last) ? ' · newest flash ' + T(last) : '') : ' · no flashes recorded in the searched window (unsearched time is unknown)';
return r;
}
/* ---------- the readout: engine distances and bearings from a point ---------- */
// Substations: the Ventus Grid Engine lightning context engine GridAtlas's lab imports (ventus-grid-engine@69b4e88
// engine/lightning-click-context.js, vendored verbatim in pilot-estate.js as PILOT.estate.lightning). As in the lab
// (atlas/labs/lightning-grid/app.mjs:196-204): SIX nearest substations at the selected minimum voltage, NO radius
// on the substation query (radiusKm limits the solar projects only), Point/Polygon/MultiPolygon locations, voltages
// normalised by the engine's voltagesKv. A flash goes through selectFlash itself; a chosen point or cell centre (no
// flash id, so selectFlash cannot be used honestly) uses the same index the engine builds, with the same mapping.
var SUB_LIMIT = 6, SOLAR_RADIUS_KM = 20, SOLAR_LIMIT = 30;
function engineRows(lon, lat, list) {
return list.map(function (x) {
var loc = x.location, b = initialBearingDeg(lon, lat, loc.lon, loc.lat);
return { name: x.name || '', kv: (x.voltages_kv || []).slice(), km: x.km, at: [loc.lon, loc.lat], operator: x.operator || '',
id: x.source_site_id || x.code || null, bearing: b, compass: compass(b) };
});
}
function readout(lon, lat, eng, kind, info) {
var rows, ctx = null;
if (kind === 'flash' && info && info.id != null && isFinite(info.t)) {
ctx = eng.engine.selectFlash({ type: 'Feature', id: String(info.id), geometry: { type: 'Point', coordinates: [lon, lat] },
properties: { observation_kind: 'optical_lightning_flash', time_utc: new Date(info.t).toISOString() } },
{ radiusKm: SOLAR_RADIUS_KM, minimumKv: S.minKv, substationLimit: SUB_LIMIT, solarLimit: SOLAR_LIMIT });
rows = engineRows(lon, lat, ctx.substations);
} else {
var hit = eng.index.nearest(lon, lat, { minimumKv: S.minKv, limit: SUB_LIMIT });
rows = engineRows(lon, lat, (Array.isArray(hit) ? hit : hit ? [hit] : []).map(function (x) {
return { name: x.point.name || null, source_site_id: x.point.code || x.point.site_code || null, voltages_kv: x.point.voltages_kv, km: x.km, location: x.point.location, operator: x.point.operator };
}));
}
return { lon: lon, lat: lat, rows: rows, ctx: ctx, minKv: S.minKv, located: eng.located, total: eng.total };
}
function gaLine(a) { return (+a.km).toFixed(2) + ' km · ' + (a.kv && a.kv.length ? a.kv.join('/') + ' kV' : 'voltage not stated') + ' · ' + (a.name || 'unnamed substation'); }
function nearbySolar(lon, lat, solar) {
// engine lab selectFlash(): radiusKm 20, solarLimit 30 (GridAtlas lab), sorted by km then repd_ref, Pipeline News MAP link per row
return solar.map(function (p) { return Object.assign({}, p, { km: distanceKm(lon, lat, p.location.lon, p.location.lat) }); })
.filter(function (p) { return p.km <= SOLAR_RADIUS_KM; })
.sort(function (a, b) { return a.km - b.km || a.repd_ref.localeCompare(b.repd_ref); })
.slice(0, SOLAR_LIMIT)
.map(function (p) {
// the Pipeline News MAP link format GridAtlas receives (buildAtlasV9DeepLink; '' when fail-closed)
var ga = buildAtlasV9DeepLink({ repd_ref: p.repd_ref, name: p.name, technology: p.technology, capacity_mw: p.capacity_mw, latitude: p.location.lat, longitude: p.location.lon });
var pn = new URL(PN_SITE); pn.searchParams.set('technology', 'solar'); pn.searchParams.set('q', p.name);
return Object.assign({}, p, { gridatlas_project_url: ga, pipelinenews_url: pn.href });
});
}
// A GridAtlas-format deep link (engine contract PARAMS: latitude, longitude) to a point
function pointFromLink(href) {
try {
var u = new URL(href), lat = Number(u.searchParams.get('latitude')), lon = Number(u.searchParams.get('longitude'));
if (u.searchParams.get('latitude') === null || !isFinite(lat) || !isFinite(lon)) return null;
return { lat: lat, lon: lon, repd_ref: u.searchParams.get(IDENTITY_PARAM), name: u.searchParams.get('project') };
} catch (e) { return null; }
}
/* ---------- nearest mapped line (Pilot helper, not an engine function) ---------- */
var CELL = 0.1, RM = EARTH_RADIUS_KM * 1000, RAD = Math.PI / 180; // R_ATLAS 6378.137 km (estate radius; never turf's 6371.0088)
// Lines: the shared grid-distance-maths SpatialIndex (every cell a segment's box covers) and distanceToSegmentKm,
// via PILOT.geo, so the ring search stops only when the hit is provably nearest (the df4da10 fix class).
function indexLines(fc, kv, L) {
var G = P.geo;
L = L || { segs: [], idx: new G.SpatialIndex(CELL), names: [], n: 0 };
(fc.features || []).forEach(function (f) {
var g = f.geometry; if (!g) return;
var parts = g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : [];
var ni = L.names.push({ name: (f.properties && f.properties.name) || 'Unnamed line (OSM)', kv: kv }) - 1;
parts.forEach(function (cs) {
for (var i = 0; i + 1 < cs.length; i++) {
var a = cs[i], b = cs[i + 1], si = L.segs.length;
L.segs.push([a[1], a[0], b[1], b[0], ni]);
L.idx.addSegment(si, a[0], a[1], b[0], b[1]);
}
});
});
L.n = L.segs.length;
return L;
}
function nearestLine(L, lat, lon) {
if (!L || !L.n) return null;
var G = P.geo, foot = {};
var best = L.idx.nearest(lon, lat, function (si) { var s = L.segs[si], h = G.distanceToSegmentKm(lon, lat, s[1], s[0], s[3], s[2]); foot[si] = h.foot; return h.km; });
if (!best) return null;
var nm = L.names[L.segs[best.id][4]];
return { name: nm.name, kv: nm.kv, d: best.km * 1000, lat: foot[best.id][1], lon: foot[best.id][0] };
}
/* ---------- state ---------- */
var S = {
on: false, period: '12m', end: null, ctx: 'none', index: null, gs: new Map(), G: null, rows: null, w: null,
progress: null, F: null, Fsrc: null, fresh: null, subs: null, lines: null, solar: null,
sel: null, err: null, busy: false, serial: 0, minKv: 132, engine: null, located: null
};
var stats = { fetches: [] };
function track(url) { stats.fetches.push(url); return fetchJSON(url); }
function render() { if (body) draw(); }
function guard() {
if (P.offline) { S.err = 'Lightning data not loaded: offline mode (?offline=1).'; render(); return false; }
return true;
}
/* ---------- layers ---------- */
var layer = {
id: 'lightning', title: TITLE, order: 60, visible: false, credit: CREDIT, _drawn: [], _labels: [],
draw: function (g, v) { drawFlashes(g, v); drawSel(g, v); },
pick: function (sx, sy) { return pickFlash(sx, sy); }
};
var cellsLayer = {
id: 'lightning-cells', title: 'Lightning flash density (GridAtlas style, optical)', order: 20, visible: false, _drawn: [],
draw: function (g, v) { drawCells(g, v); },
pick: function (sx, sy) { return pickCell(sx, sy); }
};
P.addLayer(cellsLayer);
P.addLayer(layer);
function setVis() {
var vis = function (id, b) { if (P.setLayerVisible) P.setLayerVisible(id, b); else P.layer(id).visible = b; };
vis('lightning', S.on);
vis('lightning-cells', S.on && !!S.G);
if (P.credit) P.credit('lightning-subs', S.on && S.sel ? SUB_CREDIT : null);
}
function zoomAt(v, lat, lon, p) {
var p2 = v.project(lat, lon + 0.01, null); if (!p2) return 7;
var px = Math.hypot(p2.x - p.x, p2.y - p.y); if (!(px > 0)) return 3;
var mpp = 0.01 * 111320 * Math.cos(lat * RAD) / px;
return Math.log(156543.03392 * Math.cos(lat * RAD) / mpp) / Math.LN2;
}
function drawCells(g, v) {
var G = S.G; cellsLayer._drawn = [];
if (!G) return;
var b = v.bbox, cells = G.cells, zRef = null;
g.save();
for (var pass = 0; pass < 2; pass++) for (var i = 0; i < cells.length; i++) {
var c = cells[i];
if (b && (c.lat < b.s - 0.1 || c.lat > b.n + 0.1 || c.lon < b.w - 0.1 || c.lon > b.e + 0.1)) continue;
var p = v.project(c.lat, c.lon, null); if (!p || p.x < -40 || p.y < -40 || p.x > v.w + 40 || p.y > v.h + 40) continue;
var z = zoomAt(v, c.lat, c.lon, p);
if (zRef === null) zRef = z;
var rgb = rampRGB(c.L);
if (pass === 0) {
if (c.n < G.T) continue;
var gr = glowRadius(c.L, z), grd = g.createRadialGradient(p.x, p.y, 0, p.x, p.y, gr);
grd.addColorStop(0, 'rgba(' + rgb + ',' + glowOpacity(c.L).toFixed(3) + ')'); grd.addColorStop(1, 'rgba(' + rgb + ',0)');
g.fillStyle = grd; g.beginPath(); g.arc(p.x, p.y, gr, 0, 6.2832); g.fill();
} else {
var r = coreRadius(c.L, z);
g.fillStyle = 'rgba(' + rgb + ',' + coreOpacity(c.L).toFixed(3) + ')';
g.beginPath(); g.arc(p.x, p.y, r, 0, 6.2832); g.fill();
var sw = strokeW(c.L); if (sw > 0) { g.lineWidth = sw; g.strokeStyle = '#140a2a'; g.stroke(); }
cellsLayer._drawn.push({ i: i, x: p.x, y: p.y });
}
}
cellsLayer._zoom = zRef;
g.restore();
}
function drawFlashes(g, v) {
var F = S.F; layer._drawn = [];
if (!F || !F.n || S.ctx === 'none') return;
g.save();
for (var i = 0; i < F.n && layer._drawn.length < 2000; i++) {
if (v.bbox && (F.lat[i] < v.bbox.s || F.lat[i] > v.bbox.n || F.lon[i] < v.bbox.w || F.lon[i] > v.bbox.e)) continue;
var p = v.project(F.lat[i], F.lon[i], null); if (!p || p.x < -20 || p.y < -20 || p.x > v.w + 20 || p.y > v.h + 20) continue;
layer._drawn.push({ i: i, x: p.x, y: p.y });
// GridAtlas raw flash dot: #fff3a0, stroke #1a1a1a 1.5
g.beginPath(); g.arc(p.x, p.y, 4, 0, 6.2832); g.fillStyle = 'rgba(255,243,160,0.95)'; g.fill();
g.lineWidth = 1.5; g.strokeStyle = '#1a1a1a'; g.stroke();
}
g.restore();
}
function drawSel(g, v) {
var R = S.sel; layer._labels = [];
if (!R) return;
var o = v.project(R.lat, R.lon, null); if (!o) return;
g.save();
g.font = '600 11px system-ui, sans-serif'; g.lineCap = 'round';
var lab = null;
R.rows.forEach(function (a, i) {
var p = v.project(a.at[1], a.at[0], null); if (!p) return;
// straight-line distance ruler (GridAtlas neon link colours #d8c96a / #bfe9ee); never a current path
g.setLineDash([2, 6]); g.lineWidth = 3; g.strokeStyle = 'rgba(0,0,0,0.55)';
g.beginPath(); g.moveTo(o.x, o.y); g.lineTo(p.x, p.y); g.stroke();
g.lineWidth = 1.6; g.strokeStyle = i === 0 ? '#d8c96a' : '#bfe9ee'; g.stroke(); g.setLineDash([]);
g.beginPath(); g.arc(p.x, p.y, 5, 0, 6.2832); g.fillStyle = '#5fbdc2'; g.fill();
var t = (+a.km).toFixed(2) + ' km · ' + bearingText(a.bearing);
if (i === 0) lab = { t: t, x: p.x, y: p.y };
layer._labels.push(t);
});
g.beginPath(); g.arc(o.x, o.y, 7, 0, 6.2832); g.strokeStyle = '#ffe14d'; g.lineWidth = 2.5; g.stroke();
if (lab) { // label last, beside the point and clear of the pin, kept inside the view
var tw = g.measureText(lab.t).width, lx = Math.max(4, Math.min(v.w - tw - 6, Math.max(lab.x, o.x) + 14)), ly = Math.max(14, Math.min(v.h - 4, Math.min(lab.y, o.y) - 10));
g.fillStyle = 'rgba(0,0,0,0.75)'; g.fillRect(lx - 3, ly - 12, tw + 6, 16); g.fillStyle = '#f4f0c8'; g.fillText(lab.t, lx, ly);
}
g.restore();
}
/* ---------- picking: cells (GridAtlas hit radius 22 px) and flashes ---------- */
function nearestDrawn(list, sx, sy) {
var best = null, bd = 22 * 22;
list.forEach(function (o) { var d = (o.x - sx) * (o.x - sx) + (o.y - sy) * (o.y - sy); if (d <= bd) { bd = d; best = o; } });
return best;
}
function pickCell(sx, sy) {
var o = nearestDrawn(cellsLayer._drawn, sx, sy); if (!o) return null;
var c = S.G.cells[o.i];
return choose(c.lon, c.lat, 'cell', { n: c.n, q: c.q });
}
function pickFlash(sx, sy) {
var o = nearestDrawn(layer._drawn, sx, sy); if (!o) return null;
var F = S.F;
return choose(F.lon[o.i], F.lat[o.i], 'flash', { t: F.t[o.i], id: F.id[o.i] });
}
/* ---------- choosing a point: run the engine readout ---------- */
var pendingTok = 0;
function loadSubs() {
if (S.subs) return Promise.resolve(S.subs);
if (!guard()) return Promise.reject(new Error('offline'));
return track(src.subs()).then(function (fc) {
var feats = fc.features || [], L = P.estate.lightning, eng = L.createLightningContextEngine({ substations: feats, solarProjects: [] });
// the same located-substation mapping createLightningContextEngine applies, for points that are not flashes
var located = feats.map(function (p) {
var location = rowLocation(p); if (!location) return null;
var meta = p.type === 'Feature' ? p.properties || {} : p;
var kv = Array.isArray(meta.voltages_kv) ? meta.voltages_kv : voltagesKv(meta);
return Object.assign({}, meta, { name: meta.name || p.name || null, code: meta.code || p.id || null, location: location, voltages_kv: kv });
}).filter(Boolean);
S.subs = { engine: eng, index: P.estate.nearest.index(located), located: eng.dataset_summary.located_substations, total: feats.length };
return S.subs;
});
}
function choose(lon, lat, kind, info) {
var tok = ++pendingTok, head = headFor(lon, lat, kind, info);
var card = { title: head.title, cap: head.cap, lat: lat, lon: lon, id: 'lightning:' + kind + ':' + lat.toFixed(5) + ',' + lon.toFixed(5), html: head.html + '<div id="p-lightning-ro-' + tok + '" class="p-lightning-ro">Measuring with Ventus Grid Engine…</div>' };
loadSubs().then(function (subs) {
if (tok !== pendingTok) return;
if (tok !== pendingTok) return;
S.sel = readout(lon, lat, subs, kind, info); S.sel.kind = kind; S.sel.info = info;
if (P.hash) P.hash('lgp', lat.toFixed(5) + ',' + lon.toFixed(5));
setVis();
var el = document.getElementById('p-lightning-ro-' + tok);
if (el) el.innerHTML = readoutHtml(S.sel);
render();
if (P.emit) P.emit('lightning:select', { kind: kind, lat: lat, lon: lon, nearest: S.sel.rows.map(function (a) { return { name: a.name, kv: a.kv[0], km: a.km, bearing: a.bearing }; }) });
}).catch(function () {
var el = document.getElementById('p-lightning-ro-' + tok);
if (el) el.textContent = 'Substation data could not be loaded, so nearest substations are UNKNOWN (not none). Try again online.';
});
return card;
}
function headFor(lon, lat, kind, info) {
var w = S.w;
if (kind === 'cell') {
var x = 11.156 * Math.cos(lat * RAD);
return {
cap: 'LIGHTNING CELL (OPTICAL)', title: fmt(info.n) + ' optical flash' + (info.n === 1 ? '' : 'es') + ' in this 0.1° cell',
html: '<p class="p-lightning-dim">' + (w ? ymd(w.s) + ' to ' + ymd(Math.max(w.s, w.e - 1)) + ' UTC · ' : '') + 'centre lat ' + lat.toFixed(3) + ', lon ' + lon.toFixed(3) +
' · ≈' + x.toFixed(1) + ' km E–W × 11.1 km N–S; the centre is not a flash location</p>'
};
}
if (kind === 'flash') return { cap: 'OPTICAL LIGHTNING FLASH', title: 'Flash ' + T(info.t), html: '<p class="p-lightning-dim">lat ' + lat.toFixed(3) + ', lon ' + lon.toFixed(3) + ' · ' + esc(OBS) + '</p>' };
var cq = cellOf(lon, lat), cc = S.G && S.G.cells.filter(function (c) { return c.q === cq; })[0];
return { cap: 'CHOSEN POINT', title: 'Point ' + lat.toFixed(5) + ', ' + lon.toFixed(5), html: '<p class="p-lightning-dim">' + esc(info && info.from || 'chosen point') + ' · 0.1° cell ' + cq + ': ' +
(cc ? fmt(cc.n) + ' optical flashes in the ' + esc(S.w.label) + ' window' : S.G ? 'no mapped flashes (map limited to ≤30 km of REPD sites; unsearched time is unknown, not zero)' : 'density still loading') + '</p>' };
}
function km2(k) { return k < 1 ? Math.round(k * 1000) + ' m' : k.toFixed(2) + ' km'; }
function readoutHtml(R) {
var h = '<p class="p-lightning-obs">Screening · nearest substations to this ' + (R.kind === 'cell' ? 'cell centre' : R.kind === 'flash' ? 'optical flash' : 'point') +
', straight line. Proximity, not exposure or a current path; not evidence any asset was struck.</p>';
h += '<p class="p-lightning-dim">' + SUB_LIMIT + ' nearest substations at ' + (R.minKv ? '≥' + R.minKv + ' kV' : 'any declared voltage') + ' (Ventus Grid Engine lightning context, as the GridAtlas lab; no distance cut-off) from ' + fmt(R.located) + ' located of ' + fmt(R.total) + ' mapped. Voltage: ' +
[0, 132, 275, 400].map(function (k) { return '<button type="button" class="p-lightning-btn" data-p-lightning-kv="' + k + '" aria-pressed="' + (R.minKv === k) + '">' + (k ? '≥' + k : 'All') + '</button>'; }).join(' ') + '</p>';
if (!R.rows.length) h += '<p>No mapped substation at ' + (R.minKv ? '≥' + R.minKv + ' kV' : 'a declared voltage') + ' in the loaded dataset.</p>';
h += '<ol class="p-lightning-subs">' + R.rows.map(function (a) {
return '<li><span class="p-lightning-ga">' + esc(gaLine(a)) + '</span><br><span class="p-lightning-brg">bearing ' + esc(bearingText(a.bearing)) + ': ' + esc(km2(a.km)) + ' ' + words(a.compass) + ' of the point</span>' +
' <button type="button" class="p-lightning-btn" data-p-lightning-fly="' + a.at[1].toFixed(7) + ',' + a.at[0].toFixed(7) + '" data-p-lightning-label="' + esc(a.name || 'substation') + '">Fly there</button></li>';
}).join('') + '</ol>';
if (S.lines) {
var n = nearestLine(S.lines, R.lat, R.lon);
h += n ? '<p class="p-lightning-dim">Nearest mapped 400/275 kV line: ' + esc(n.name) + ', ' + esc(km2(n.d / 1000)) + ' (Pilot helper, not an engine function).</p>' : '<p class="p-lightning-dim">No mapped 400/275 kV line within about 10 km.</p>';
} else h += '<button type="button" class="p-lightning-btn" data-p-lightning="lines">Add nearest 400/275 kV line</button>';
if (S.solar) h += solarHtml(R);
else h += ' <button type="button" class="p-lightning-btn" data-p-lightning="solar">Nearby REPD solar + GridAtlas / Pipeline News links (8 files, 1.3 MB)</button>';
h += '<p class="p-lightning-dim">' + esc(STRAIGHT_LINE_CAVEAT.distance) + ' ' + esc(STRAIGHT_LINE_CAVEAT.headroom) + '</p>';
h += '<p class="p-lightning-dim">Open in GridAtlas: <a href="https://ventusltd.github.io/gridatlas/atlas/" target="_blank" rel="noopener">GridAtlas</a> (switch on Lightning Flashes (Optical), 12M, tap the same cell). GridAtlas and Pipeline News deep links carry a REPD project (repd_ref, technology, latitude, longitude, zoom); neither format has a bearing parameter or a point-only form.</p>';
h += provHtml();
return h;
}
function solarHtml(R) {
var rows = nearbySolar(R.lon, R.lat, S.solar);
if (!rows.length) return '<p class="p-lightning-dim">No REPD solar project within ' + SOLAR_RADIUS_KM + ' km in the loaded Pipeline News solar partitions (engine lab radius).</p>';
return '<h4 class="p-lightning-h">REPD solar within ' + SOLAR_RADIUS_KM + ' km, nearest ' + SOLAR_LIMIT + ' (engine lab)</h4><ol class="p-lightning-subs">' + rows.map(function (p) {
var b = initialBearingDeg(R.lon, R.lat, p.location.lon, p.location.lat);
return '<li>' + esc(p.km.toFixed(2)) + ' km · ' + esc(bearingText(b)) + ' · ' + esc(p.name) + (p.capacity_mw !== null ? ' · ' + esc(p.capacity_mw) + ' MW' : '') +
'<br>' + (p.gridatlas_project_url ? '<a class="p-lightning-link" href="' + esc(p.gridatlas_project_url) + '" target="_blank" rel="noopener">Open in GridAtlas</a>' : 'no GridAtlas link (fails the MAP contract)') + ' · <a class="p-lightning-link" href="' + esc(p.pipelinenews_url) + '" target="_blank" rel="noopener">Open in Pipeline News</a></li>';
}).join('') + '</ol><p class="p-lightning-dim">Registered project points; distance does not establish a strike or fault.</p>';
}
function provHtml() {
return '<details class="p-lightning-prov"><summary>Engine functions used</summary><ul>' + PROV.map(function (p) {
return '<li>' + (p.sec ? '<a href="' + EC + p.sec + '.html" target="_blank" rel="noopener"><code>' + esc(p.fn) + '</code></a>' : '<code>' + esc(p.fn) + '</code>') + ' – ' + esc(p.what) +
(p.vedic ? ' · Vedic word <b>' + esc(p.vedic) + '</b> (' + esc(p.gg) + ')' : '') + (p.spider ? ' · genome ' + esc(p.spider) : '') +
'<br><span class="p-lightning-dim">' + esc(p.src) + '</span></li>';
}).join('') + '</ul></details>';
}