GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot and 2 more files (part 1)

A Python command-line tool in the theme folder of Cosmic that reads grid substations, build graph and pilot places.

532 lines of Python and JavaScript from cosmic, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1156 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. Pilot render · cosmic / tools/explore/theme/pilot.js lines 701–880
  2. Pilot storage · cosmic / tools/explore/theme/pilot.py lines 1–240
  3. Pilot Estate render · cosmic / tools/explore/theme/pilot_estate.py lines 1–112

Pilot

A JavaScript file in the theme folder of Cosmic that maps places, beacon, substations and overhead lines (OHL), and uses data from the GridAtlas repository.

rendercosmic / tools/explore/theme/pilot.js · lines 701–880 of 880 (continued from section 1155) · Entry point · pattern makeView (shared by 2 files)

What it does
It maps places, beacon, substations and overhead lines (OHL). Defines 85 functions or classes, including noop, ease, turn, lattice, half. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: substations, overhead lines (OHL).
Inputs & outputs
In: data source: gridatlas data; JSON file places.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It sets origin (`setOrigin`), loads dem (`loadDem`) and sets basis (`setBasis`). Explore Code Pilot (HOTBAR-36; core flight, FAST MODE and window.PILOT contract v1: ALTIMETER-58 / Pilot-200 W01). It reads `places.json`. It responds to click, visibilitychange and keydown events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
Uses
GridAtlas — Index Page (estate URL)
Used by
loaded by Pilot (script src)
Produces
noop, ease, turn, lattice, half, sq, attach, warnOnce, clamp, fireReady, $, toLocal
Defines here
step, userTook, steerStep, applyKeys, groundHit, tapAt, joyMove, backURL, params, atParam, pick, begin
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.js:701-880 · blob 6a61f9737aa4fdc4ed08917bcc9481b0a7294d02 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
    else {
      if (steerFn) steerStep(dt);
      var vmax = steerFn ? FASTV[3] : FASTV[fast];
      cam.yaw += input.yaw * dt * 0.9;
      cam.pitch = clamp(cam.pitch + input.pitch * dt * 0.7, -1.45, 0.3);
      if (input.thr) { cam.speed = clamp(cam.speed + input.thr * dt * Math.max(30, vmax * 0.25), 0, vmax); cruise = cam.speed; }
      else {   // eased speed change: capped acceleration, exponential settle, and a small linear term so it lands
        var df = cruise - cam.speed, dv = df * Math.min(1, dt * (fast || cam.speed > 150 ? 1.1 : 1.5)), amax = 600 * dt;
        if (Math.abs(dv) < 80 * dt) dv = clamp(df, -80 * dt, 80 * dt);
        cam.speed += clamp(dv, -amax * 1.5, amax); }
      cam.x += Math.sin(cam.yaw) * cam.speed * dt; cam.y += Math.cos(cam.yaw) * cam.speed * dt;
      cam.z += input.lift * dt * (80 + Math.max(0, agl0) * 0.4);
      if (input.lift) settle = false;
      var g = ground(cam.x, cam.y), agl = cam.z - g;
      if (cam.speed > 160 && !steerFn) { var floor = cam.speed * 2.5; if (agl < floor) cam.z += (g + floor - cam.z) * Math.min(1, dt * 0.8); settle = false; }   // FAST climbs so the ground stays readable
      else if (settle) { var tz = g + 400; if (cam.z > tz + 5) cam.z += (tz - cam.z) * Math.min(1, dt * 0.5); else settle = false; }
      cam.z = clamp(cam.z, g + 15, 14000);
    }
    if (Math.hypot(cam.x, cam.y) > 20000) { var ll = toLL(cam.x, cam.y); setOrigin(ll[0], ll[1]); }   // floating origin follows the camera
    var fk = REDUCED ? 1 : 1 - 0.16 * Math.min(1, Math.sqrt(cam.speed / 2500)); fovK += (fk - fovK) * Math.min(1, raw * 2); F = Fbase * fovK;
    setBasis(); view = makeView();
    PILOT.emit('frame', { dt: dt, now: now });
    cx.clearRect(0, 0, Wd, Ht);
    drawSky();
    var m = modes[mode] || modes.sat;
    cx.save(); try { m.ground(cx, view, now); } catch (e) { warnOnce('mode ' + mode, e); cx.restore(); cx.save(); drawGrid(cx, view); } cx.restore();
    drawLayers(now); drawStreaks(); hud();
    if (frameNo % 30 === 0) layoutSlots();
  }
  function step(now) {
    try { frame(now); } catch (e) { warnOnce('frame', e); }
    if (!D.hidden) requestAnimationFrame(step); else paused = true;
  }
  var paused = false;
  D.addEventListener('visibilitychange', function () { if (!D.hidden && paused) { paused = false; last = performance.now(); requestAnimationFrame(step); } });

  // ---- steer hook (W09 request): a module flies continuously; any user input hands control back
  var steerFn = null;
  function userTook() { cancelFlight('cancelled'); if (steerFn) { steerFn = null; PILOT.emit('steer:cancel', {}); } }
  PILOT.steer = function (fn) { steerFn = typeof fn === 'function' ? fn : null; if (steerFn) cancelFlight('cancelled'); return !!steerFn; };
  function steerStep(dt) {
    var r; try { r = steerFn(dt); } catch (e) { warnOnce('steer', e); r = null; }
    if (!r) { steerFn = null; PILOT.emit('steer:cancel', { reason: 'ended' }); return; }
    if (r.hdg != null && isFinite(r.hdg)) { var dy = turn(cam.yaw, +r.hdg * RAD), cap = (0.5 + Math.min(1, cam.speed / 400)) * dt; cam.yaw += clamp(dy, -cap, cap); }
    if (r.speed != null && isFinite(r.speed)) cruise = clamp(+r.speed, 0, FASTV[3]);
    if (r.agl != null && isFinite(r.agl)) { var tz = ground(cam.x, cam.y) + clamp(+r.agl, 15, 12000); cam.z += (tz - cam.z) * Math.min(1, dt * 0.8); }
    if (r.pitch != null && isFinite(r.pitch)) cam.pitch += (clamp(+r.pitch, -1.45, 0.3) - cam.pitch) * Math.min(1, dt * 2);
  }

  // ---- controls: keyboard + pointer
  var keys = {};
  function applyKeys() {
    input.yaw = (keys.d || keys.arrowright ? 1 : 0) - (keys.a || keys.arrowleft ? 1 : 0) + stick.x;
    input.pitch = (keys.arrowup ? 1 : 0) - (keys.arrowdown ? 1 : 0) - stick.y * 0.6;
    input.thr = (keys.w ? 1 : 0) - (keys.s ? 1 : 0) + btnState.thr;
    input.lift = (keys.e || keys[' '] ? 1 : 0) - (keys.q || keys.shift ? 1 : 0) + btnState.lift;
  }
  D.addEventListener('keydown', function (e) {
    if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
    if (e.ctrlKey || e.metaKey || e.altKey) return;
    var k = e.key.toLowerCase();
    if (k === 'n' || k === ']') { flyToPlace(idx + 1); e.preventDefault(); return; }
    if (k === 'p' || k === '[') { flyToPlace(idx - 1); e.preventDefault(); return; }
    if (k === 'f') { setFast(e.shiftKey ? 0 : (fast + 1) % 4); e.preventDefault(); return; }
    if (k === 'h') { $('card').classList.toggle('min'); return; }
    if (k === 'escape') { if (openName) { closePanel(); return; } if (cardMode === 'ext') { showCard(null); return; } location.href = backURL(); return; }
    if (['w', 'a', 's', 'd', 'q', 'e', ' ', 'shift', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright'].indexOf(k) >= 0) { keys[k] = true; if (k !== 'shift') userTook(); applyKeys(); e.preventDefault(); }
  });
  D.addEventListener('keyup', function (e) { keys[e.key.toLowerCase()] = false; applyKeys(); });
  W.addEventListener('blur', function () { keys = {}; applyKeys(); });

  // tap (W01-S14): a short press without movement picks a layer item, else reports the ground point
  function groundHit(sx, sy) {
    if (!basis) return null;
    var b = basis, a = (sx - Wd / 2) / F, c = (Ht / 2 - sy) / F;
    var d = [b.r[0] * a + b.up[0] * c + b.fw[0], b.r[1] * a + b.up[1] * c + b.fw[1], b.up[2] * c + b.fw[2]];
    if (d[2] >= -1e-4) return null;
    var gz = ground(cam.x, cam.y), t = (gz - cam.z) / d[2]; if (t <= 0 || t > 400000) return null;
    gz = ground(cam.x + d[0] * t, cam.y + d[1] * t); t = Math.max(0, (gz - cam.z) / d[2]);
    return toLL(cam.x + d[0] * t, cam.y + d[1] * t);
  }
  function tapAt(sx, sy) {
    if (!view) return;
    for (var i = layers.length - 1; i >= 0; i--) {
      var l = layers[i], r = null; if (l.visible === false || !l.pick) continue;
      try { r = l.pick(sx, sy, view); } catch (e) { warnOnce('layer ' + l.id + ' pick', e); }
      if (r) { showCard({ title: r.title, html: r.html, lat: r.lat, lon: r.lon, cap: r.cap || String(l.title || l.id).toUpperCase(), id: r.id }); PILOT.emit('pick', { layer: l.id, item: r }); return; }
    }
    var hit = groundHit(sx, sy); if (hit) PILOT.emit('tap', { lat: hit[0], lon: hit[1], sx: sx, sy: sy });
  }
  PILOT._tap = tapAt;
  var down = null;
  cv.addEventListener('pointerdown', function (e) { down = { x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, t: performance.now(), id: e.pointerId, moved: false }; try { cv.setPointerCapture(e.pointerId); } catch (x) {} });
  cv.addEventListener('pointermove', function (e) {
    if (!down || e.pointerId !== down.id) return;
    if (!down.moved && Math.hypot(e.clientX - down.x, e.clientY - down.y) > 8) { down.moved = true; userTook(); }
    if (down.moved) { cam.yaw += (e.clientX - down.lx) * 0.004; cam.pitch = clamp(cam.pitch - (e.clientY - down.ly) * 0.003, -1.45, 0.3); }
    down.lx = e.clientX; down.ly = e.clientY;
  });
  cv.addEventListener('pointerup', function (e) {
    if (down && e.pointerId === down.id && !down.moved && performance.now() - down.t < 600) { var r = cv.getBoundingClientRect(); tapAt(e.clientX - r.left, e.clientY - r.top); }
    down = null;
  });
  cv.addEventListener('pointercancel', function () { down = null; });
  cv.addEventListener('wheel', function (e) { cam.speed = cruise = clamp(cam.speed - e.deltaY * 0.05 * Math.max(1, FASTV[fast] / 140), 0, FASTV[fast]); userTook(); e.preventDefault(); }, { passive: false });

  // ---- touch: virtual stick (pattern from overlay.html #joy/#knob) and hold buttons
  var stick = { x: 0, y: 0 }, btnState = { thr: 0, lift: 0 };
  var joy = $('joy'), knob = $('knob'), jid = null;
  function joyMove(e) {
    var r = joy.getBoundingClientRect(), dx = e.clientX - (r.left + r.width / 2), dy = e.clientY - (r.top + r.height / 2), R = r.width / 2, l = Math.hypot(dx, dy);
    if (l > R) { dx *= R / l; dy *= R / l; }
    stick.x = dx / R; stick.y = dy / R; knob.style.transform = 'translate(' + dx + 'px,' + dy + 'px)'; applyKeys();
  }
  joy.addEventListener('pointerdown', function (e) { jid = e.pointerId; joy.setPointerCapture(jid); userTook(); joyMove(e); e.preventDefault(); });
  joy.addEventListener('pointermove', function (e) { if (e.pointerId === jid) joyMove(e); });
  ['pointerup', 'pointercancel'].forEach(function (ev) { joy.addEventListener(ev, function () { jid = null; stick.x = stick.y = 0; knob.style.transform = ''; applyKeys(); }); });
  Array.prototype.forEach.call(D.querySelectorAll('[data-hold]'), function (b) {
    var p = b.getAttribute('data-hold').split(':'), on = function (e) {
      userTook();
      if (p[0] === 'thr') { cruise = clamp(cruise + (+p[1]) * Math.max(15, FASTV[fast] / 9), 0, FASTV[fast]); e.preventDefault(); return; }
      btnState[p[0]] = +p[1]; applyKeys(); e.preventDefault(); }, off = function () { btnState[p[0]] = 0; applyKeys(); };
    b.addEventListener('pointerdown', on); b.addEventListener('pointerup', off); b.addEventListener('pointerleave', off); b.addEventListener('pointercancel', off);
  });
  $('b-next').addEventListener('click', function () { flyToPlace(idx + 1); });
  $('b-prev').addEventListener('click', function () { flyToPlace(idx - 1); });
  $('b-card').addEventListener('click', function () { $('card').classList.toggle('min'); });
  if (W.innerWidth < 600) $('card').classList.add('min');   // phones: the card starts collapsed so the view is clear (UI review)
  if ($('keys')) $('keys').textContent += ' · F fast mode (Shift+F off) · tap or click the ground to inspect';

  function backURL() { return D.referrer && /\/s\/\d+\.html/.test(D.referrer) ? D.referrer : '../index.html'; }
  $('b-back').addEventListener('click', function (e) { if (history.length > 1 && D.referrer) { e.preventDefault(); history.back(); } });

  // ---- debug / tests (W01-S20)
  PILOT.debug = function () {
    return { fps: Math.round(fps), layers: layers.map(function (l) { return { id: l.id, ms: Math.round((l._ms || 0) * 1000) / 1000, visible: l.visible !== false }; }),
             origin: [lat0, lon0], fast: fast, mode: mode, streaks: streaks, tiles: nTiles, imgPause: imgPause, demPause: demPause,
             flight: flight ? { arc: flight.arc, u: Math.min(1, flight.el / flight.s), s: flight.s } : null, ready: isReady };
  };

  // ---- start: #at=lat,lon[,alt] or the place for ?file=ID, #sec=N&block=B, #place=I
  function params() { var o = {}; (location.search.slice(1) + '&' + location.hash.slice(1)).split('&').forEach(function (kv) { var p = kv.split('='); if (p[0]) { try { o[p[0]] = decodeURIComponent(p[1] || ''); } catch (e) { o[p[0]] = p[1] || ''; } } }); return o; }
  function atParam(o) {
    if (o.at == null) return null; var a = o.at.split(',').map(Number);
    return a.length >= 2 && isFinite(a[0]) && isFinite(a[1]) && Math.abs(a[0]) <= 85 && Math.abs(a[1]) <= 180 ? a : null;
  }
  function pick() {
    var o = params(), pl = DATA.places, match = function (fn) { for (var i = 0; i < pl.length; i++) if (pl[i].files.some(fn)) return i; return -1; };
    var at = atParam(o); if (at) return { at: at };
    if (o.place != null && +o.place >= 0 && +o.place < pl.length) return { i: +o.place };
    if (o.file != null) { var i = match(function (f) { return f.id === +o.file; }); if (i >= 0) return { i: i }; i = -1; }
    if (o.sec != null) {
      var j = match(function (f) { return f.section === +o.sec && (o.block == null || f.block === +o.block); });
      if (j < 0) j = match(function (f) { return f.section === +o.sec; });
      if (j >= 0) return { i: j };
      return { i: 0, note: 'Section ' + o.sec + ' names no coordinate in its files, so Pilot starts at the most-named place in the estate.' };
    }
    if (o.file != null) return { i: 0, note: 'File ' + o.file + ' names no coordinate, so Pilot starts at the most-named place in the estate.' };
    return { i: 0 };
  }
  function begin(s) {
    if (s.note) PILOT.note(s.note, 7000);
    if (s.at) { setOrigin(s.at[0], s.at[1]); flyTo(s.at[0], s.at[1], { alt: s.at[2], source: 'url', _swoop: true }); }
    else flyToPlace(s.i, false, true);
    D.body.classList.add('ready');
    W.__pilot = { cam: cam, flyTo: function (i, instant) { return flyToPlace(i, instant); }, idx: function () { return idx; }, place: function () { return P; }, sat: function () { return satOK; }, towers: function () { return towers.length; } };
    last = performance.now(); requestAnimationFrame(step);
    fireReady();
  }
  resize(); W.addEventListener('resize', resize);
  credits();
  fetch('places.json').then(function (r) { if (!r.ok) throw new Error('places.json ' + r.status); return r.json(); }).then(function (d) {
    if (!d.places || !d.places.length) throw new Error('no places');
    DATA = d; begin(pick());
  }).catch(function (e) {
    var at = atParam(params());
    PILOT.note('Pilot could not load its places (' + e.message + ').' + (at ? '' : ''), 9000);
    if (at && !isReady) begin({ at: at });
  });
})();

Pilot

A Python command-line tool in the theme folder of Cosmic that reads grid substations, build graph and pilot places.

storagecosmic / tools/explore/theme/pilot.py · lines 1–240 of 240 · Entry point

What it does
It loads grid substations, build graph and pilot places. Defines 8 functions or classes, including inb, scan_text, git, blobs, km. Uses libraries __future__, argparse, json, math, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV (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: 400kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; JSON file build_graph.json; JSON file pilot-places.json; command-line arguments. Voltage levels named: 400kV.
Downstream impact
Used directly by 2 files: Test Ide (cosmic); Test Pilot Static (cosmic). Reached from 1 other entry point, including CI Chess Workflow (cosmic).
What it achieves
It scans text (`scan_text`) and is built from the inb step (`inb`) and the git step (`git`). Pilot places for Explore Code (HOTBAR-36): real coordinates found in the estate's own code files. Its code works with 400 kV. It accepts `--graph` and `--out`.
Why it matters
Checked by 2 tests, including Test Ide.
Application
cosmic · tools/explore/theme · Python CLI
Uses
__future__, argparse, json, math, re, subprocess, collections, pathlib
Used by
run by Test Ide (script call), run by Test Pilot Static (script call)
Produces
inb, scan_text, git, blobs, km, build, clip_runs, main
Defines here
inb, scan_text, git, blobs, km, build, clip_runs, main
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.py:1-240 · blob 1e6f63dedcdc24f223355aea7118f3a870b2794f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Pilot places for Explore Code (HOTBAR-36): real coordinates found in the estate's own code files.

Writes theme/pilot-places.json (schema explore-pilot-places-v1), which pilot.html reads as pilot/places.json.

Rules (never invent a location):
- A place is a coordinate pair written in a code file listed in build_graph.json, read from the clone at the
  build commit (git show <commit>:<path>), inside Great Britain and Ireland (lat 49.8..60.95, lon -10.7..1.9).
  Forms read: `lat: N ... lon|lng: N` within one statement, and bare pairs `N, N` that fall inside those bounds
  in only one order (lat,lon or lon,lat). A pair that fits both orders is skipped.
- Pairs within ~110 m (3 decimals) merge into one place. Its name is a quoted name/label/title/site string on the
  same line as the coordinate when there is one, otherwise "Coordinate in <file title>".
- Every place lists the files that mention it with their clean-contract key
  "<repo>@<commit> <path>:<line>-<line> <blob>", the line, and the section page.
- Context drawn round a place (all OpenStreetMap ODbL, as published in the GridAtlas atlas-v9 release in the
  estate): grid lines of 132/275/400 kV within RADIUS_KM, and substations (points) within RADIUS_KM, for the
  HUD's nearest asset and the pylons. Their key names the geojson file in the gridatlas clone.
- Clipping: a line is cut into runs of consecutive vertices inside RADIUS_KM (each run extended by one vertex at
  either end so it reaches the edge); separate runs stay separate polylines and are never joined across a gap.

Derived-cache exception (photon rule): pilot-places.json is a small DERIVED CACHE, not a copy of a dataset. It holds
rounded subsets (<= 24 line runs and <= 12 substations within RADIUS_KM of each code place) of the GridAtlas
atlas-v9 release named in GA_REL, pinned by commit and blob in context_sources, so the first view draws without a
network fetch. The live Pilot grid layers (pilot-grid.js) stream the current GridAtlas release instead; the two
releases can differ, and the file says which one it used (cache_exception).
"""
from __future__ import annotations

import argparse, json, math, re, subprocess
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
SRC = Path('/home/claude/src')
GA_REL = 'atlas/releases/202608292126-atlas-v9/data'
LAT0, LAT1, LON0, LON1 = 49.8, 60.95, -10.7, 1.9
RADIUS_KM = 6.0
MAX_PLACES = 240
MAX_PER_FILE = 12
NUM = r'(-?\d{1,3}\.\d{3,10})'
RE_PAIR = re.compile(NUM + r'\s*,\s*' + NUM)
RE_LATLON = re.compile(r'\blat(?:itude)?["\']?\s*[:=]\s*' + NUM + r'[^\n;]{0,80}?\b(?:lon|lng|long|longitude)["\']?\s*[:=]\s*' + NUM, re.I)
RE_LONLAT = re.compile(r'\b(?:lon|lng|long|longitude)["\']?\s*[:=]\s*' + NUM + r'[^\n;]{0,80}?\blat(?:itude)?["\']?\s*[:=]\s*' + NUM, re.I)
RE_NAME = re.compile(r'\b(?:name|label|title|site|substation|place)["\']?\s*[:=]\s*["\']([A-Za-z][^"\'\n]{2,60})["\']')


def inb(lat: float, lon: float) -> bool:
    return LAT0 <= lat <= LAT1 and LON0 <= lon <= LON1


def scan_text(text: str):
    """Yield (lat, lon, line_no, name_or_None) for coordinates in text, per the rules above."""
    for no, line in enumerate(text.split('\n'), 1):
        if len(line) > 4000:
            continue
        found = []
        for m in RE_LATLON.finditer(line):
            found.append((float(m.group(1)), float(m.group(2))))
        for m in RE_LONLAT.finditer(line):
            found.append((float(m.group(2)), float(m.group(1))))
        if not found:
            for m in RE_PAIR.finditer(line):
                a, b = float(m.group(1)), float(m.group(2))
                ab, ba = inb(a, b), inb(b, a)
                if ab and not ba:
                    found.append((a, b))
                elif ba and not ab:
                    found.append((b, a))
        if not found:
            continue
        nm = RE_NAME.search(line)
        for lat, lon in found:
            if inb(lat, lon):
                yield lat, lon, no, (nm.group(1).strip() if nm else None)


def git(repo: Path, *args: str, inp: str | None = None) -> str:
    return subprocess.run(['git', '-C', str(repo), *args], input=inp, capture_output=True, text=True, errors='replace').stdout


def blobs(repo: Path, commit: str, paths: list[str]) -> dict[str, str]:
    out = git(repo, 'cat-file', '--batch-check', inp=''.join(f'{commit}:{p}\n' for p in paths))
    res = {}
    for p, line in zip(paths, out.splitlines()):
        parts = line.split()
        res[p] = parts[0] if len(parts) >= 2 and parts[1] == 'blob' else '-'
    return res


def km(a, b):
    kx = 111.32 * math.cos(math.radians((a[0] + b[0]) / 2))
    return math.hypot((a[0] - b[0]) * 111.32, (a[1] - b[1]) * kx)


def build(graph_path: Path) -> dict:
    g = json.loads(graph_path.read_text())
    commits = {r['repo']: r['commit'] for r in g['repos']}
    by_repo = defaultdict(list)
    for f in g['files']:
        by_repo[f['repo']].append(f)
    hits = []  # (lat, lon, file, line, name)
    for repo, fl in sorted(by_repo.items()):
        clone = SRC / repo
        if not clone.is_dir():
            continue
        bl = blobs(clone, commits[repo], [f['path'] for f in fl])
        for f in fl:
            if f['lines'] > 20000:
                continue
            text = git(clone, 'show', f'{commits[repo]}:{f["path"]}')
            if not text or len(text) > 3_000_000:
                continue
            seen, named, plain = set(), [], []
            for lat, lon, no, nm in scan_text(text):
                k = (round(lat, 3), round(lon, 3))
                if k in seen:
                    continue
                seen.add(k)
                (named if nm else plain).append((lat, lon, no, nm))
            for lat, lon, no, nm in (named + plain)[:MAX_PER_FILE]:
                hits.append((lat, lon, f, no, nm, bl.get(f['path'], '-')))
    places = {}
    for lat, lon, f, no, nm, blob in hits:
        k = (round(lat, 3), round(lon, 3))
        p = places.setdefault(k, {'lat': round(lat, 6), 'lon': round(lon, 6), 'names': [], 'files': {}})
        if nm and nm not in p['names']:
            p['names'].append(nm)
        if f['id'] not in p['files']:
            key = f'{f["repo"]}@{commits[f["repo"]]} {f["path"]}:{no}-{no} {blob}'
            p['files'][f['id']] = {'id': f['id'], 'title': f['title'], 'line': no, 'key': key, 'section': f['section'],
                                   'block': f['block'], 'url': f's/{f["section"]:04d}.html#f{f["block"]}', 'role': f.get('role') or 'other'}
    ranked = sorted(places.values(), key=lambda p: (-len(p['files']), -len(p['names']), p['lat'], p['lon']))[:MAX_PLACES]
    # context: grid lines and substations near each place (OSM ODbL via the GridAtlas atlas-v9 release)
    ga = SRC / 'gridatlas'
    ga_commit = git(ga, 'rev-parse', 'HEAD').strip()
    lines_by_kv = {}
    for kv in ('400', '275', '132'):
        p = ga / GA_REL / f'grid_{kv}kv.geojson'
        if not p.exists():
            continue
        L = []
        for ft in json.loads(p.read_text()).get('features', []):
            geo = ft.get('geometry') or {}
            cs = [geo['coordinates']] if geo.get('type') == 'LineString' else geo.get('coordinates', []) if geo.get('type') == 'MultiLineString' else []
            for c in cs:
                if len(c) >= 2:
                    L.append(c)
        lines_by_kv[kv] = L
    subs = []
    sp = ga / GA_REL / 'grid_substations.geojson'
    if sp.exists():
        for ft in json.loads(sp.read_text()).get('features', []):
            geo = ft.get('geometry') or {}
            if geo.get('type') == 'Point':
                subs.append((geo['coordinates'][1], geo['coordinates'][0], (ft.get('properties') or {}).get('name') or ''))
    blob_of = {}
    for name in [f'grid_{kv}kv.geojson' for kv in lines_by_kv] + ['grid_substations.geojson']:
        blob_of[name] = blobs(ga, ga_commit, [f'{GA_REL}/{name}']).get(f'{GA_REL}/{name}', '-')
    out_places = []
    for i, p in enumerate(ranked):
        c = (p['lat'], p['lon'])
        near_lines = []
        for kv, L in lines_by_kv.items():
            for coords in L:
                for pts in clip_runs(coords, c):
                    near_lines.append({'kv': kv, 'c': [[round(q[0], 5), round(q[1], 5)] for q in pts]})
        near_lines = near_lines[:24]
        near_subs = sorted(([round(s[0], 5), round(s[1], 5), s[2][:60]] for s in subs if km(c, (s[0], s[1])) <= RADIUS_KM),
                           key=lambda s: km(c, (s[0], s[1])))[:12]
        name = p['names'][0] if p['names'] else 'Coordinate in ' + next(iter(p['files'].values()))['title']
        out_places.append({'i': i, 'name': name, 'other_names': p['names'][1:4], 'lat': p['lat'], 'lon': p['lon'],
                           'files': sorted(p['files'].values(), key=lambda x: x['id'])[:12], 'n_files': len(p['files']),
                           'lines': near_lines, 'subs': near_subs})
    return {
        'schema': 'explore-pilot-places-v1', 'cut': g.get('cut'), 'rules': __doc__.strip().split('\n\n')[1],
        'context_sources': {
            'lines': [f'gridatlas@{ga_commit} {GA_REL}/grid_{kv}kv.geojson {blob_of.get(f"grid_{kv}kv.geojson", "-")}' for kv in lines_by_kv],
            'substations': f'gridatlas@{ga_commit} {GA_REL}/grid_substations.geojson {blob_of.get("grid_substations.geojson", "-")}',
            'licence': 'OpenStreetMap contributors, ODbL 1.0'},
        'cache_exception': {'kind': 'derived cache (photon rule exception)', 'source_release': GA_REL,
                            'note': 'Rounded line/substation subsets within %g km of each code place; the live grid layers stream the current GridAtlas release.' % RADIUS_KM},
        'places': out_places,
    }


def clip_runs(coords, c, radius_km=RADIUS_KM):
    """Clip a polyline ([lon, lat] vertices) to the circle of radius_km round c = (lat, lon), segment by segment.

    Each segment is cut exactly where it crosses the circle (on a local tangent plane at c, R 6378.137 km), so no
    vertex inside is dropped and the line ends on the circle. Pieces chain into one run only where they connect (the
    segment ended inside and the next starts there); a line that leaves and re-enters gives separate runs, never a
    chord across the gap."""
    lat0, lon0 = c
    k = math.pi / 180 * 6378.137
    kx = k * math.cos(math.radians(lat0))
    P = [((q[0] - lon0) * kx, (q[1] - lat0) * k) for q in coords]
    back = lambda x, y: [lon0 + x / kx, lat0 + y / k]
    runs, cur = [], None
    for i in range(len(P) - 1):
        (ax, ay), (bx, by) = P[i], P[i + 1]
        dx, dy = bx - ax, by - ay
        A = dx * dx + dy * dy
        B = 2 * (ax * dx + ay * dy)
        C = ax * ax + ay * ay - radius_km * radius_km
        if A == 0:
            cur = None if C > 0 else cur
            continue
        disc = B * B - 4 * A * C
        if disc <= 0:
            cur = None
            continue
        r = math.sqrt(disc)
        t0, t1 = max(0.0, (-B - r) / (2 * A)), min(1.0, (-B + r) / (2 * A))
        if t0 >= t1:
            cur = None
            continue
        p0 = coords[i] if t0 == 0 else back(ax + dx * t0, ay + dy * t0)
        p1 = coords[i + 1] if t1 == 1 else back(ax + dx * t1, ay + dy * t1)
        if cur is not None and t0 == 0:
            cur.append(p1)
        else:
            cur = [p0, p1]
            runs.append(cur)
        if t1 < 1:
            cur = None
    return runs


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--graph', default='/tmp/site8/explore-code/build_graph.json')
    ap.add_argument('--out', default=str(HERE / 'pilot-places.json'))
    a = ap.parse_args(argv)
    data = build(Path(a.graph))
    Path(a.out).write_text(json.dumps(data, separators=(',', ':'), ensure_ascii=False))
    print(f'{len(data["places"])} places -> {a.out} ({Path(a.out).stat().st_size} bytes)')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())

Pilot Estate

A Python command-line tool in the theme folder of Cosmic that works with rewrite imports (`rewrite_imports`) (units: kV), using SHA-256.

rendercosmic / tools/explore/theme/pilot_estate.py · lines 1–112 of 112 · Entry point · pattern source (shared by 13 files)

What it does
It loads data. Defines 6 functions or classes, including rewrite_imports, sub, source, vendored, build. Uses libraries __future__, argparse, hashlib, re, subprocess. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments. Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Test Pilot Geo (cosmic). Reached from 1 other entry point, including CI Chess Workflow (cosmic).
What it achieves
It is built from the sub step (`sub`), the source step (`source`) and the vendored step (`vendored`). Build `theme/pilot-estate.js`: estate originals vendored VERBATIM for the Pilot page (W10 CAPSTAN-41). It accepts `--check`.
Why it matters
Checked by Test Pilot Geo.
Application
cosmic · tools/explore/theme · Python CLI
Uses
__future__, argparse, hashlib, re, subprocess, sys, pathlib
Used by
run by Test Pilot Geo (script call)
Produces
rewrite_imports, source, vendored, build, main
Defines here
rewrite_imports, sub, source, vendored, build, main
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_estate.py:1-112 · blob 7378d4161a6f0a224aa2db128b0e79adfeba7ecd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Build theme/pilot-estate.js: estate originals vendored VERBATIM for the Pilot page (W10 CAPSTAN-41).

    python3 tools/explore/theme/pilot_estate.py            # writes theme/pilot-estate.js from the pinned clones
    python3 tools/explore/theme/pilot_estate.py --check    # exit 1 if the committed file differs

Each block is the source text at a pinned commit with only the leading `export ` keyword removed, so the code keeps
its estate identity (Modular Star families, Spiders genome hashes) and test_pilot_geo.py can prove it byte for byte.
It is a plain script (CONTRACT.md section 1), wrapped in one IIFE; each source sits in its own function scope.
"""
from __future__ import annotations

import argparse, hashlib, re, subprocess, sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
SRC = Path('/home/claude/src')
OUT = HERE / 'pilot-estate.js'

# (name, repo, commit, path, first line, last line or None = whole file, exported names, licence)
BLOCKS = [
    ('geo', 'grid-distance-maths', '8e91b07d8312acca5bcaef43e839f06a3b1d642a', 'src/geodesy.mjs', 1, None,
     ['R_ATLAS', 'R_MEAN', 'R_UK', 'WGS84', 'curvatureKm', 'localScaleKm', 'distanceKm', 'distanceEllipsoidalKm', 'pathLengthKm',
      'initialBearingDeg', 'destinationPoint', 'distanceToSegmentKm', 'distanceToLineKm', 'geodesicCircle', 'circleApproximationError',
      'polygonAreaKm2', 'areaUnits', 'SpatialIndex', 'STRAIGHT_LINE_CAVEAT'], 'Apache-2.0'),
    ('engine', 'ventus-grid-engine', 'ad566356a44e006682e956483d569f31ddbb9630', 'engine/v9-geodesy.js', 1, None,
     ['EARTH_RADIUS_KM', 'distanceKm', 'representativePoint', 'voltagesKv', 'destinationPoint', 'initialBearingDeg', 'schema'], 'Apache-2.0'),
    # The lightning context engine GridAtlas's lab imports (atlas/labs/lightning-grid/app.mjs), at that exact revision.
    # Its dependencies are byte-identical at ad56635 and 69b4e88 (same blobs), so 'engine' above serves both.
    ('nearest', 'ventus-grid-engine', '69b4e88c8464f0310bd67e47ec83ee8afa9e1921', 'engine/v9-nearest-search.js', 1, None,
     ['normalise', 'index', 'schema'], 'Apache-2.0'),
    ('deeplink', 'ventus-grid-engine', '69b4e88c8464f0310bd67e47ec83ee8afa9e1921', 'deeplink/contract.js', 1, None,
     ['IDENTITY_PARAM', 'PARAMS', 'CANONICAL_RECEIVER', 'RETIRED_RECEIVERS', 'isRetiredReceiver', 'buildDeepLink', 'parseDeepLink'], 'Apache-2.0'),
    ('lightning', 'ventus-grid-engine', '69b4e88c8464f0310bd67e47ec83ee8afa9e1921', 'engine/lightning-click-context.js', 1, None,
     ['schema', 'caveat', 'solarMarkerRadiusPx', 'lightningMarker', 'createLightningContextEngine', 'postEventDiligence', 'lightningElectricalScenario'], 'Apache-2.0'),
]
# import specifier -> earlier block that provides it
IMPORTS = {'./v9-geodesy.js': 'engine', './v9-nearest-search.js': 'nearest', '../deeplink/contract.js': 'deeplink'}
IMPORT_RE = re.compile(r"^import \{([^}]*)\} from '([^']+)';$", re.M)


def rewrite_imports(text: str) -> str:
    """`import { a, b as c } from './x.js';` -> `const { a, b: c } = <block>;` (the only other change besides export)."""
    def sub(m):
        names = ', '.join(n.strip().replace(' as ', ': ') for n in m.group(1).split(',') if n.strip())
        return f'const {{ {names} }} = {IMPORTS[m.group(2)]};'
    return IMPORT_RE.sub(sub, text)
EXPORT_RE = re.compile(r'^export (?=(?:const|let|function|class|async function) )', re.M)


def source(repo: str, commit: str, path: str) -> bytes:
    return subprocess.run(['git', '-C', str(SRC / repo), 'show', f'{commit}:{path}'], capture_output=True, check=True).stdout


def vendored(text: str, a: int, b: int | None) -> str:
    lines = text.split('\n')
    return rewrite_imports(EXPORT_RE.sub('', '\n'.join(lines[a - 1:b] if b else lines)))


def build() -> str:
    head = ['/* Pilot module "estate" (W10 / CAPSTAN-41): estate originals vendored VERBATIM, as PILOT.estate. GENERATED by',
            '   theme/pilot_estate.py; do not edit by hand. Each block below is the pinned source with only the leading',
            '   `export ` keyword removed and each `import {..} from` turned into `const {..} = <earlier block>` (identity kept for',
            '   Modular Star / Spiders); test_pilot_geo.py checks it byte for byte.',
            '   PILOT.geo = PILOT.estate.geo: the ONE geodesy for Drone View. Earth model R_ATLAS = 6378.137 km, as GridAtlas, the',
            '   Ventus Grid Engine and Pipeline News, so the same two points give the same number everywhere; a screening',
            '   approximation (about 0.1 % from the ellipsoid in the UK). Every distance is straight-line, never a route.']
    body = []
    for name, repo, commit, path, a, b, names, lic in BLOCKS:
        raw = source(repo, commit, path)
        rng = f'#L{a}-L{b}' if b else ''
        head.append(f'   {name}: Ventusltd/{repo}@{commit} {path}{rng} (file sha256 {hashlib.sha256(raw).hexdigest()}, {lic}, Ventus Ltd)')
        body.append(f'  // ==== {name}: Ventusltd/{repo}@{commit} {path}{rng} (verbatim, export keywords removed)\n'
                    f'  var {name} = (function () {{\n// >>> {name} begin\n{vendored(raw.decode("utf-8"), a, b)}\n// <<< {name} end\n'
                    f'    return {{ {", ".join(f"{n}: {n}" for n in names)} }};\n  }})();')
    head.append('*/')
    glue = '''  // ==== glue (W10): PILOT-order helpers and wiring; no maths of its own
  geo.SOURCE = 'Ventusltd/grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a src/geodesy.mjs';
  geo.EARTH_NOTE = 'Distances use a sphere of radius 6378.137 km (as GridAtlas and the Ventus Grid Engine): a screening approximation, about 0.1 % from the ellipsoid.';
  // PILOT order is lat-first; the estate's functions are lon-first. distM/bearing use the ENGINE's own distanceKm /
  // initialBearingDeg (families 511 / 8770; 1-ulp parity with GridAtlas and the engine).
  geo.distM = function (lat1, lon1, lat2, lon2) { return engine.distanceKm(lon1, lat1, lon2, lat2) * 1000; };
  geo.bearing = function (lat1, lon1, lat2, lon2) { return engine.initialBearingDeg(lon1, lat1, lon2, lat2); };
  geo.caveatText = function (keys) { return (keys || ['distance', 'coverage']).map(function (k) { return geo.STRAIGHT_LINE_CAVEAT[k]; }).join(' '); };
  var estate = { geo: geo, voltagesKv: engine.voltagesKv, engine: engine, nearest: nearest, deeplink: deeplink, lightning: lightning };
  if (typeof module !== 'undefined' && module.exports) module.exports = estate;
  if (typeof window === 'undefined' || !window.PILOT) return;
  var P = window.PILOT;
  P.module('estate', { version: '1', owner: 'W10' });
  P.estate = estate;
  P.geo = geo;
  P.dist = geo.distM;          // one earth radius for every module (review finding 2)
  P.bearing = geo.bearing;'''
    return '\n'.join(head) + '\n(function () {\n  \'use strict\';\n' + '\n'.join(body) + '\n' + glue + '\n})();\n'


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--check', action='store_true')
    a = ap.parse_args(argv)
    new = build()
    if a.check:
        ok = OUT.read_text(encoding='utf-8') == new
        print('pilot-estate.js up to date' if ok else 'pilot-estate.js differs from the pinned sources')
        return 0 if ok else 1
    OUT.write_text(new, encoding='utf-8')
    print(f'wrote {OUT} ({len(new)} bytes)')
    return 0


if __name__ == '__main__':
    sys.exit(main())