GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / cosmic / tools/explore/periodic

Pilot LiDAR and 3 more files

A JavaScript file in the theme folder of Cosmic that tiles xy (`tileXY`) and metres (`tileMetres`), picks zoom (`pickZoom`) and draws on a canvas.

568 lines of Python and JavaScript from cosmic, in 4 files. Topic: Maps, GIS and field navigation. Section 468 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Map storage · cosmic / tools/explore/periodic/map.py lines 598–651
  2. Test Map test · cosmic / tools/explore/periodic/test_map.py lines 1–138
  3. Pilot LiDAR geodesy · cosmic / tools/explore/theme/pilot-lidar.js lines 1–273
  4. Test Pilot Geo test · cosmic / tools/explore/theme/test_pilot_geo.py lines 1–103

Map

A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, periodic and table, using SHA-256. It loads identity (`load_identity`) and adds numbered (`add_numbered`).

storagecosmic / tools/explore/periodic/map.py · lines 598–651 of 651 (continued from section 467) · Entry point · pattern evidence_key (shared by 2 files)

What it does
It loads build graph, identity, periodic and table. Defines 15 functions or classes, including zs, sha256, git_head, load, top. Uses libraries argparse, collections, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Inputs & outputs
In: JSON file build_graph.json; JSON file identity.json; JSON file periodic.json; JSON file table.json; JSON file elements.json; JSON file functions.json; JSON file blocks.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: Test Map (cosmic); Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Periodic table of the code estate: the MAPPER.
Why it matters
Run by Extras. Checked by Test Map.
Application
cosmic · tools/explore/periodic · Python CLI
Uses
argparse, collections, hashlib, json, os, re, subprocess, sys
Used by
imported by Test Map (import), run by Extras (script call)
Produces
zs, sha256, git_head, load, top, quantile_assign, propose_symbol, fam_sort, evidence_key, load_identity, build, assign_analogues
Defines here
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/periodic/map.py:598-651 · blob 4a3a781cdcd640d8c283d7c1fd5057bc903d228c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
    for k, (rule, z) in done.items():
        r = REAL_TABLE[z - 1]
        elements[k]["analogue"] = dict(Z=z, symbol=r["symbol"], name=r["name"], rule=rule, basis=basis[k])
    elements_median = median
    return elements_median


RULES = {
    "numbers": "number and symbol are copied from star-maker/elements/table.json (47) and elements/catalogue/elements.json "
               "(all register blocks, same numbers for the shared 47); a mismatch aborts the build; candidates get number null",
    "file_assignment": "a graph file belongs to the block(s) identity.json lists for it; if none, to the catalogue blocks that own "
                       "any of its Modular Star families (family:<n>); with several, the primary is the block owning most of the "
                       "file's families, then the lower number; the others are listed in 'also'",
    "candidates": "a file with no block is clustered by its strongest Vedic candidate word (highest score, then word) when that "
                  "word covers >= %d unmapped files (period 3); else by its most shared path name word (stop words and "
                  "version/timestamp tokens removed; most files, then nearest the file name, then alphabetical) when >= %d "
                  "files; else into <ROLE>-RESIDUE. Candidates get a proposed symbol '*Xy' and never a number" % (MIN_CLUSTER, MIN_CLUSTER),
    "families": "a Modular Star family maps to its catalogue block when the catalogue names one; otherwise to the element "
                "holding most of its occurrences (ties: numbered first, lower number, key); unnumbered function "
                "occurrences (no family key) are counted, not mapped",
    "group": "column = Explore Code graph role: numbered elements by catalogue category (constants->docs-config, geodesy, "
             "network/connections/solar->electrical, layers->storage, cartridges->render, interface/arrival->interaction, "
             "news->energy-data, proofs->test); otherwise the dominant role of member files (ties in graph role order); "
             "elements with no files use star family (physics->transform, vocabulary->docs-config)",
    "period": "row = abstraction level: catalogue kind constant 1, layer/deeplink 2, auto 4, engine 5, cartridge/tool 6, app 7; "
              "Vedic candidates 3; other candidates by dominant graph kind (configuration/SQL/style 2, modules/scripts/tests 4, "
              "CLI/workflow/shell 6, page 7)",
    "state": "state SETTLED/UNSETTLED copied from star-maker (else catalogue); UNSETTLED elements carry star-maker's competing "
             "values with their file counts",
    "valence": "number of distinct other elements joined to this one by at least one build_graph edge between member files",
    "importance": "dependents of member files + file count + 10 x valence (used only to rank MAPPING.md)",
    "analogue": "playful chemical lens only: rules applied in order (halogen, hydrogen, carbon-group, noble, heavy-unstable, "
                "then by group column); within a rule, elements are sorted by the rule's metric and spread over its pool by "
                "quantile; it never replaces number or symbol",
}


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    for k, v in DEFAULTS.items():
        p.add_argument("--" + k, default=v)
    args = p.parse_args(argv)
    out = build(args)
    os.makedirs(os.path.dirname(args.out), exist_ok=True)
    tmp = args.out + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(out, fh, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    os.replace(tmp, args.out)
    print(json.dumps(out["counts"], sort_keys=True))
    return out


if __name__ == "__main__":
    main()

Test Map

A test in the periodic folder of Cosmic that checks Map. It sets up class (`setUpClass`) and is built from the units class (`Units`) and the live class (`Live`).

testcosmic / tools/explore/periodic/test_map.py · lines 1–138 of 138 · Entry point · pattern test_deterministic (shared by 11 files)

What it does
It tests its inputs. Defines 14 functions or classes, including Units, test_quantile_spreads_over_pool, test_proposed_symbols_unique, test_family_sort, test_real_table. Uses libraries json, os, sys, tempfile, unittest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Inputs & outputs
In: JSON file a.json; JSON file b.json; JSON file table.json; JSON file elements.json; JSON file blocks.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `map.py` (MAPPER). Builds the table twice from the live inputs (about 20 s).
Why it matters
Guards the behaviour of Map.
Application
cosmic · tools/explore/periodic · test
Uses
Map (import), json, os, sys, tempfile, unittest
Used by
none found
Produces
Units, Live
Defines here
Units, test_quantile_spreads_over_pool, test_proposed_symbols_unique, test_family_sort, test_real_table, Live, setUpClass, test_deterministic, test_every_file_mapped, test_every_family_mapped, test_existing_numbers_unchanged, test_candidates_never_numbered, test_unsettled_keep_competing_values, test_axes_and_analogue
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/periodic/test_map.py:1-138 · blob 4c094f7d89fb94abb709c80978bd4adce434df98 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unknown
#!/usr/bin/env python3
"""Tests for map.py (MAPPER). Run: python3 -m unittest test_map -v
Builds the table twice from the live inputs (about 20 s)."""
import json
import os
import sys
import tempfile
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import map as M  # noqa: E402

HAVE = all(os.path.exists(p) for p in (M.DEFAULTS["graph"], M.DEFAULTS["identity"],
                                       M.DEFAULTS["starmaker"], M.DEFAULTS["elements"]))


class Units(unittest.TestCase):
    def test_quantile_spreads_over_pool(self):
        got = M.quantile_assign([(3, "c"), (1, "a"), (2, "b")], [1, 2, 3])
        self.assertEqual(got, {"a": 1, "b": 2, "c": 3})
        many = M.quantile_assign([(i, "k%02d" % i) for i in range(10)], [7, 8])
        self.assertEqual(sorted(set(many.values())), [7, 8])

    def test_proposed_symbols_unique(self):
        taken = {"Pa", "Pr"}
        a = M.propose_symbol("PARSE", taken)
        b = M.propose_symbol("PARSE", taken)
        self.assertNotIn(a, {"Pa", "Pr"})
        self.assertNotEqual(a, b)

    def test_family_sort(self):
        keys = ["familysha:ab", "family:10", "family:2"]
        self.assertEqual(sorted(keys, key=M.fam_sort), ["family:2", "family:10", "familysha:ab"])

    def test_real_table(self):
        self.assertEqual(len(M.REAL_TABLE), 118)
        self.assertEqual(M.REAL_TABLE[0]["symbol"], "H")
        self.assertEqual(M.REAL_TABLE[117]["symbol"], "Og")


@unittest.skipUnless(HAVE, "estate inputs not present")
class Live(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.tmp = tempfile.mkdtemp()
        cls.out1 = os.path.join(cls.tmp, "a.json")
        cls.out2 = os.path.join(cls.tmp, "b.json")
        cls.d = M.main(["--out", cls.out1])
        M.main(["--out", cls.out2])
        cls.E = {e["key"]: e for e in cls.d["elements"]}
        with open(M.DEFAULTS["graph"]) as fh:
            cls.graph = json.load(fh)

    def test_deterministic(self):
        with open(self.out1, "rb") as a, open(self.out2, "rb") as b:
            self.assertEqual(a.read(), b.read())

    def test_every_file_mapped(self):
        ids = {str(f["id"]) for f in self.graph["files"]}
        self.assertEqual(set(self.d["files"]), ids)
        members = []
        for fid, v in self.d["files"].items():
            self.assertIn(v["element"], self.E)
            self.assertIn(int(fid), self.E[v["element"]]["files"])
        for e in self.E.values():
            members += e["files"]
        self.assertEqual(sorted(members), sorted(int(i) for i in ids))  # each file in exactly one element

    def test_every_family_mapped(self):
        with open(M.DEFAULTS["identity"]) as fh:
            ident = json.load(fh)
        fams = {x["family_key"] for f in ident["files"].values() for x in f["functions"] if x.get("family_key")}
        self.assertTrue(fams <= set(self.d["families"]))
        for v in self.d["families"].values():
            self.assertIn(v["element"], self.E)

    def test_existing_numbers_unchanged(self):
        with open(os.path.join(M.DEFAULTS["starmaker"], "elements", "table.json")) as fh:
            star = json.load(fh)["elements"]
        self.assertEqual(len(star), 47)
        for s in star:
            e = self.E["block:" + s["symbol"]]
            self.assertEqual((e["number"], e["symbol"], e["state"]), (s["number"], s["symbol"], s["state"]))
            self.assertEqual(e["source"], "star-maker")
        with open(os.path.join(M.DEFAULTS["elements"], "catalogue", "elements.json")) as fh:
            cat = json.load(fh)
        for c in cat:
            self.assertEqual((self.E[c["key"]]["number"], self.E[c["key"]]["symbol"]), (c["number"], c["symbol"]))
        reg = os.path.join(M.DEFAULTS["stars"], "blocks", "blocks.json")
        if os.path.exists(reg):
            with open(reg) as fh:
                for b in json.load(fh)["blocks"]:
                    self.assertEqual(self.E["block:" + b["symbol"]]["number"], b["number"])
        nums = [e["number"] for e in self.E.values() if e["number"] is not None]
        self.assertEqual(len(nums), len(set(nums)))

    def test_candidates_never_numbered(self):
        existing = {e["symbol"] for e in self.E.values() if e["status"] == "numbered"}
        cands = [e for e in self.E.values() if e["status"] == "candidate"]
        self.assertTrue(cands)
        props = [e["proposed_symbol"] for e in cands]
        self.assertEqual(len(props), len(set(props)))
        for e in cands:
            self.assertIsNone(e["number"])
            self.assertIsNone(e["symbol"])
            self.assertTrue(e["key"].startswith("candidate:"))
            self.assertTrue(e["proposed_symbol"].startswith("*"))
            self.assertNotIn(e["proposed_symbol"][1:], existing)
        for e in self.E.values():
            if e["status"] == "numbered":
                self.assertIsNone(e["proposed_symbol"])

    def test_unsettled_keep_competing_values(self):
        uns = [e for e in self.E.values() if e["state"] == "UNSETTLED"]
        self.assertEqual(len(uns), 12)
        for e in uns:
            self.assertGreaterEqual(len(e["competing_values"]), 2)
        for e in self.E.values():
            if e["state"] != "UNSETTLED":
                self.assertEqual(e["competing_values"], [])

    def test_axes_and_analogue(self):
        groups = {g["id"] for g in self.d["axes"]["groups"]}
        periods = {p["n"] for p in self.d["axes"]["periods"]}
        for e in self.E.values():
            self.assertIn(e["group"], groups)
            self.assertIn(e["period"], periods)
            a = e["analogue"]
            self.assertTrue(1 <= a["Z"] <= 118)
            self.assertEqual(M.REAL_TABLE[a["Z"] - 1]["symbol"], a["symbol"])
            self.assertTrue(e["evidence"], e["key"])
        self.assertEqual(sum(1 for e in self.E.values() if e["analogue"]["symbol"] == "H"), 1)
        self.assertEqual(sum(1 for e in self.E.values() if e["analogue"]["symbol"] == "C"), 1)


if __name__ == "__main__":
    unittest.main()

Pilot LiDAR

A JavaScript file in the theme folder of Cosmic that tiles xy (`tileXY`) and metres (`tileMetres`), picks zoom (`pickZoom`) and draws on a canvas.

geodesycosmic / tools/explore/theme/pilot-lidar.js · lines 1–273 of 273 · Entry point · pattern blend (shared by 2 files)

What it does
It draws LiDAR terrain. Defines 26 functions or classes, including tileXY, tileMetres, clamp, decode, pickZoom. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: JSON file index.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 picks zoom (`pickZoom`), decodes blob (`decodeBlob`) and gets blob (`getBlob`). Pilot LiDAR reader (optional module; TRIGPOINT-62, LiDAR proof of concept for OS square TR06).
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
none found
Used by
loaded by Pilot (script src)
Produces
tileXY, tileMetres, clamp, decode, pickZoom, ringFor, add, sqFor, sqHas, urlFor, bps, px
Defines here
tileXY, tileMetres, clamp, decode, pickZoom, ringFor, add, sqFor, sqHas, urlFor, bps, px, sampleZ, height, blend, decodeBlob, fromImg, getBlob, net, trimCache, pump, prune, update, setCredit, loadIndex, start
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-lidar.js:1-273 · blob a5751da49f9ad5045e743f19495348adc34d2ff1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unknown
/* Pilot LiDAR reader (optional module; TRIGPOINT-62, LiDAR proof of concept for OS square TR06).
   Streams Environment Agency 1 m DTM heights, built by .github/workflows/lidar-tr06.yml as Terrarium tiles on the
   same Web-Mercator z/x/y grid as the satellite imagery, and blends them into Pilot's ground height.
   - Reads lidar/index.json (squares, zooms, every tile's measured bytes). Asks only for tiles the index lists.
   - Keeps a 3x3 ring of blocks round the camera, plus the next 2 blocks along the heading, fetched first.
   - Picks z16 (~1.5 m), z15, z14 or none (core AWS z12) by height above ground, speed and bandwidth
     (navigator.connection: 2g/slow-2g = none, saveData = z14 max, downlink caps the speed; else measured download
     speed, else 0.5 Mbps assumed).
   - Bilinear sampling across tile edges, finest loaded zoom first; feathers into AWS over the square's edge band
     and wherever LiDAR has no data (alpha 0). LRU cache of 120 decoded blocks (~31 MB) + Cache Storage if allowed.
   - Credits: "Contains Environment Agency information (c) Environment Agency and/or database right, OGL v3".
   Activation: needs the core hook PILOT.groundSource(fn) so the drape uses the heights (requested from W01 through
   CAPSTAN-41). Without the hook it stays idle and fetches nothing unless ?lidar=1. ?lidar=0 turns it off;
   ?lidar=<url of index.json> points it elsewhere. ?offline=1: never fetches. Plain script, no libraries. */
(function () {
  'use strict';
  if (!window.PILOT) return;
  var P = window.PILOT, W = window, D = document;
  P.module('lidar', { version: '1', owner: 'TRIGPOINT-62' });

  var CREDIT = 'Contains Environment Agency information © Environment Agency and/or database right, OGL v3';
  var MAX_TILES = 120, CONCURRENCY = 2, DEFAULT_BPS = 62500, DEFAULT_TILE_BYTES = 100000, MAX_AGL = 3000;
  var ZOOMS = [16, 15, 14], EARTH_C = 40075016.686, CACHE_NAME = 'pilot-lidar-v1';
  var q = location.search, mFlag = /[?&]lidar=([^&#]*)/.exec(q), flag = mFlag ? decodeURIComponent(mFlag[1]) : '';
  var OFF = flag === '0' || P.offline, FORCE = flag === '1' || /^(https?:|\.|\/)/.test(flag);
  var INDEX_URL = /^(https?:|\.|\/)/.test(flag) ? flag : new URL('../../lidar/index.json', location.href).href;

  // ---------- pure helpers (exported on PILOT.lidar for tests) ----------
  function tileXY(lat, lon, z) {
    var n = Math.pow(2, z), r = lat * Math.PI / 180;
    return [(lon + 180) / 360 * n, (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n];
  }
  function tileMetres(lat, z) { return EARTH_C * Math.cos(lat * Math.PI / 180) / Math.pow(2, z); }
  function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }

  // Terrarium RGBA (Uint8ClampedArray, 256x256x4) -> Float32Array heights, NaN where alpha is 0.
  function decode(px) {
    var n = px.length >> 2, h = new Float32Array(n);
    for (var i = 0; i < n; i++) {
      var j = i << 2;
      h[i] = px[j + 3] === 0 ? NaN : px[j] * 256 + px[j + 1] + px[j + 2] / 256 - 32768;
    }
    return h;
  }

  // Which zoom to stream: 16, 15, 14, or 0 (none: core AWS terrain only).
  // o = {agl, speed, lat, bps, queue, zooms:[..], avgBytes:{z: bytes}, conn:{effectiveType, saveData}}
  // Keep-up rule (VERDICT section 3): each block crossed needs one new row of 3 blocks, so bytes per metre of travel
  // = 3 x mean block bytes / block width; half the link is kept for latency, so need = 2 x speed x bytes per metre.
  function pickZoom(o) {
    if (!o || !(o.agl < MAX_AGL)) return 0;
    var c = o.conn || {}, et = c.effectiveType;
    if (et === 'slow-2g' || et === '2g') return 0;
    var top = o.agl < 300 ? 16 : o.agl < 800 ? 15 : o.agl < 2000 ? 14 : 0;
    if (c.saveData) top = Math.min(top, 14);
    if (o.queue > 6 && o.speed > 5 && top > 14) top--;   // moving and falling behind: step down (hovering may wait)
    var bps = o.bps > 0 ? o.bps : DEFAULT_BPS, zs = o.zooms || ZOOMS;
    for (var z = top; z >= 14; z--) {
      if (zs.indexOf(z) < 0) continue;
      var bytes = (o.avgBytes && o.avgBytes[z]) || DEFAULT_TILE_BYTES;
      var need = 2 * Math.max(0, o.speed || 0) * 3 * bytes / tileMetres(o.lat || 52, z);
      if (need <= bps) return z;
    }
    return 0;
  }

  // Keys "z/x/y" to hold at zoom z: centre, then the 2 blocks ahead along hdg, then the rest of the 3x3 ring
  // (front first). has(key) filters to tiles the index lists.
  function ringFor(lat, lon, hdg, z, has) {
    var t = tileXY(lat, lon, z), cx = Math.floor(t[0]), cy = Math.floor(t[1]);
    var a = hdg * Math.PI / 180, dx = Math.sin(a), dy = -Math.cos(a), out = [], seen = {};
    function add(x, y) { var k = z + '/' + x + '/' + y; if (!seen[k] && (!has || has(k))) { seen[k] = 1; out.push(k); } }
    add(cx, cy);
    for (var s = 1; s <= 2; s++) add(Math.floor(t[0] + dx * s), Math.floor(t[1] + dy * s));
    var ring = [];
    for (var j = -1; j <= 1; j++) for (var i = -1; i <= 1; i++) if (i || j) ring.push([i, j, -(i * dx + j * dy)]);
    ring.sort(function (p, r) { return p[2] - r[2]; });
    ring.forEach(function (p) { add(cx + p[0], cy + p[1]); });
    return out;
  }

  // ---------- state ----------
  var index = null, squares = [], cache = new Map(), queue = [], active = 0, started = false, enabled = false;
  var bwSamples = 0, bwEwma = 0, lastZ = 0, want = [], usedZ = 0, stats = { fetched: 0, bytes: 0, errors: 0, cacheHits: 0 };
  var cv = null, cg = null, swCache = null, putCount = 0;

  function sqFor(lat, lon) {
    for (var i = 0; i < squares.length; i++) {
      var b = squares[i].bbox; if (lon >= b[0] && lon <= b[2] && lat >= b[1] && lat <= b[3]) return squares[i];
    }
    return null;
  }
  function sqHas(k) { for (var i = 0; i < squares.length; i++) if (squares[i].tiles[k] != null) return squares[i]; return null; }
  function urlFor(sq, k) {
    var p = k.split('/');
    return new URL(sq.tiles_url.replace('{z}', p[0]).replace('{x}', p[1]).replace('{y}', p[2]), INDEX_URL).href;
  }
  function bps() {
    var c = navigator.connection, link = c && c.downlink > 0 ? c.downlink * 125000 : 0;
    if (bwSamples >= 2) return link ? Math.min(link, bwEwma) : bwEwma;
    return link || DEFAULT_BPS;
  }

  // global pixel (gx, gy) at zoom z: number, NaN (no data) or undefined (tile not loaded)
  function px(z, gx, gy) {
    var c = cache.get(z + '/' + Math.floor(gx / 256) + '/' + Math.floor(gy / 256));
    if (!c || !c.h) return undefined;
    return c.h[(((gy % 256) + 256) % 256) * 256 + (((gx % 256) + 256) % 256)];
  }
  function sampleZ(lat, lon, z) {
    var t = tileXY(lat, lon, z), fx = t[0] * 256 - 0.5, fy = t[1] * 256 - 0.5, x0 = Math.floor(fx), y0 = Math.floor(fy);
    var c = cache.get(z + '/' + Math.floor(t[0]) + '/' + Math.floor(t[1]));
    if (!c || !c.h) return undefined;                 // containing block not loaded: try a coarser zoom
    c.t = Date.now();
    var ax = fx - x0, ay = fy - y0, s = 0, w = 0;
    var vs = [px(z, x0, y0), px(z, x0 + 1, y0), px(z, x0, y0 + 1), px(z, x0 + 1, y0 + 1)];
    var ws = [(1 - ax) * (1 - ay), ax * (1 - ay), (1 - ax) * ay, ax * ay];
    for (var i = 0; i < 4; i++) if (vs[i] === vs[i] && vs[i] !== undefined) { s += vs[i] * ws[i]; w += ws[i]; }
    return w > 1e-6 ? { h: s / w, cover: w } : NaN;
  }
  // {h, w, z}: LiDAR height, blend weight (0..1) toward LiDAR, zoom used; or null where there is no LiDAR here.
  function height(lat, lon) {
    var sq = sqFor(lat, lon); if (!sq) return null;
    for (var i = 0; i < ZOOMS.length; i++) {
      var r = sampleZ(lat, lon, ZOOMS[i]);
      if (r === undefined) continue;
      if (r !== r) return null;                       // no data at the finest loaded zoom (sea, void)
      var b = sq.bbox, f = sq.featherDeg;
      var edge = Math.min((lon - b[0]) / f[0], (b[2] - lon) / f[0], (lat - b[1]) / f[1], (b[3] - lat) / f[1]);
      return { h: r.h, w: clamp(edge, 0, 1) * clamp(r.cover, 0, 1), z: ZOOMS[i] };
    }
    return null;
  }
  function blend(lat, lon, base) {
    var r = height(lat, lon); if (!r) return null;
    base = +base || 0; return base + r.w * (r.h - base);
  }

  // ---------- loading ----------
  function decodeBlob(blob) {
    if (!cv) { cv = D.createElement('canvas'); cv.width = cv.height = 256; cg = cv.getContext('2d', { willReadFrequently: true }); }
    function fromImg(img) {
      cg.clearRect(0, 0, 256, 256); cg.drawImage(img, 0, 0, 256, 256);
      if (img.close) img.close();
      return decode(cg.getImageData(0, 0, 256, 256).data);
    }
    if (W.createImageBitmap) {
      return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }).then(fromImg);
    }
    return new Promise(function (res, rej) {
      var u = URL.createObjectURL(blob), im = new Image();
      im.onload = function () { URL.revokeObjectURL(u); try { res(fromImg(im)); } catch (e) { rej(e); } };
      im.onerror = function () { URL.revokeObjectURL(u); rej(new Error('decode')); };
      im.src = u;
    });
  }
  function getBlob(url) {
    var t0 = performance.now();
    function net() {
      return fetch(url, { mode: 'cors', credentials: 'omit' }).then(function (r) {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        var copy = swCache ? r.clone() : null;
        return r.blob().then(function (b) {
          var dt = (performance.now() - t0) / 1000;
          if (dt > 0.02 && b.size > 4000) { var s = b.size / dt; bwEwma = bwSamples ? bwEwma * 0.7 + s * 0.3 : s; bwSamples++; }
          stats.fetched++; stats.bytes += b.size;
          if (copy) swCache.put(url, copy).then(trimCache).catch(function () {});
          return b;
        });
      });
    }
    if (!swCache) return net();
    return swCache.match(url).then(function (hit) {
      if (hit) { stats.cacheHits++; return hit.blob(); }
      return net();
    }, net);
  }
  function trimCache() {
    if (++putCount % 50 || !swCache) return;
    swCache.keys().then(function (ks) { for (var i = 0; i < ks.length - 600; i++) swCache.delete(ks[i]); }).catch(function () {});
  }
  function pump() {
    while (active < CONCURRENCY && queue.length) {
      var k = queue.shift(), sq = sqHas(k);
      if (!sq || cache.has(k)) continue;
      var ent = { h: null, t: Date.now(), loading: true }; cache.set(k, ent); active++;
      (function (k, ent) {
        getBlob(urlFor(sq, k)).then(decodeBlob).then(function (h) {
          ent.h = h; ent.loading = false; ent.t = Date.now(); P.emit('lidar:tile', { key: k });
        }).catch(function () { cache.delete(k); stats.errors++; })
          .then(function () { active--; prune(); pump(); });
      })(k, ent);
    }
  }
  function prune() {
    var keep = {}; want.forEach(function (k) { keep[k] = 1; });
    var ok = []; cache.forEach(function (v, k) { if (v.h && !keep[k]) ok.push([k, v.t]); });
    var n = 0; cache.forEach(function (v) { if (v.h) n++; });
    if (n <= MAX_TILES) return;
    ok.sort(function (a, b) { return a[1] - b[1]; });
    for (var i = 0; i < ok.length && n > MAX_TILES; i++, n--) cache.delete(ok[i][0]);
  }

  function update() {
    if (!enabled || !index) return;
    var c = P.camLL(); if (!c || !isFinite(c.lat)) return;
    var sq = null;
    for (var i = 0; i < squares.length && !sq; i++) {
      var b = squares[i].bbox, m = 0.03;          // ~2-3 km margin: start loading before entering the square
      if (c.lon >= b[0] - m && c.lon <= b[2] + m && c.lat >= b[1] - m && c.lat <= b[3] + m) sq = squares[i];
    }
    if (!sq) { want = []; queue = []; usedZ = 0; setCredit(false); return; }
    var z = pickZoom({ agl: c.agl, speed: c.speed, lat: c.lat, bps: bps(), queue: queue.length + active,
                       zooms: sq.zooms, avgBytes: sq.avgBytes, conn: navigator.connection });
    lastZ = z;
    want = z ? ringFor(c.lat, c.lon, c.hdg || 0, z, function (k) { return sq.tiles[k] != null; }) : [];
    // z15/z14 parent of the centre too, so a coarser height is ready while z16 arrives
    if (z === 16) want = want.concat(ringFor(c.lat, c.lon, c.hdg || 0, 15, function (k) { return sq.tiles[k] != null; }).slice(0, 1));
    queue = want.filter(function (k) { return !cache.has(k); });
    pump();
    var r = height(c.lat, c.lon); usedZ = r ? r.z : 0;
    setCredit(!!r || cache.size > 0);
  }
  var creditOn = false;
  function setCredit(on) { if (on !== creditOn) { creditOn = on; P.credit('lidar', on ? CREDIT : null); } }

  function loadIndex() {
    return fetch(INDEX_URL, { mode: 'cors', credentials: 'omit' }).then(function (r) {
      if (!r.ok) throw new Error('HTTP ' + r.status); return r.json();
    }).then(function (j) {
      index = j;
      squares = (j.squares || []).filter(function (s) { return s && s.bbox && s.tiles && s.tiles_url; }).map(function (s) {
        var avg = {}; Object.keys(s.stats || {}).forEach(function (z) { if (s.stats[z].bytes_mean) avg[z] = s.stats[z].bytes_mean; });
        var latc = (s.bbox[1] + s.bbox[3]) / 2, fm = 1.5 * tileMetres(latc, 16);   // feather band: 1.5 z16 blocks
        return { id: s.id, bbox: s.bbox, zooms: s.zooms || ZOOMS, tiles: s.tiles, tiles_url: s.tiles_url, avgBytes: avg,
                 attribution: s.attribution || CREDIT,
                 featherDeg: [fm / (111320 * Math.cos(latc * Math.PI / 180)), fm / 110574] };
      });
      P.emit('lidar:index', { squares: squares.map(function (s) { return s.id; }) });
    });
  }

  function start() {
    if (started || OFF) return started;
    started = true; enabled = true;
    try { if (W.caches && W.isSecureContext) W.caches.open(CACHE_NAME).then(function (c) { swCache = c; }, function () {}); } catch (e) {}
    loadIndex().then(function () {
      if (typeof P.groundSource === 'function') P.groundSource(function (lat, lon, base) { return blend(lat, lon, base); });
      P.onFrame(function () { var t = Date.now(); if (t - (start.t || 0) > 250) { start.t = t; update(); } });
      update();
    }).catch(function () { enabled = false; index = null; });   // no index (not built yet): stay quiet, AWS as before
    return true;
  }

  P.lidar = {
    CREDIT: CREDIT, tileXY: tileXY, tileMetres: tileMetres, decode: decode, pickZoom: pickZoom, ringFor: ringFor,
    height: height, blend: blend, start: start,
    ground: function (lat, lon) {   // with the core hook PILOT.ground already includes LiDAR
      var b = P.ground(lat, lon); if (typeof P.groundSource === 'function') return b;
      var v = blend(lat, lon, b); return v == null ? b : v;
    },
    status: function () {
      var loaded = 0; cache.forEach(function (v) { if (v.h) loaded++; });
      return { enabled: enabled, hooked: typeof P.groundSource === 'function', index: INDEX_URL,
               squares: squares.map(function (s) { return s.id; }), zoom: lastZ, used: usedZ, want: want.slice(),
               loaded: loaded, queued: queue.length, active: active, bps: Math.round(bps()), bwSamples: bwSamples,
               fetched: stats.fetched, bytes: stats.bytes, errors: stats.errors, cacheHits: stats.cacheHits, credit: creditOn };
    },
    _cache: cache
  };

  if (!OFF && (FORCE || typeof P.groundSource === 'function')) P.ready(start);
})();

Test Pilot Geo

A test in the theme folder of Cosmic that checks Pilot Estate, using SHA-256 and haversine.

testcosmic / tools/explore/theme/test_pilot_geo.py · lines 1–103 of 103 · Entry point · pattern _node (shared by 2 files)

What it does
It tests its inputs. Defines 7 functions or classes, including _node, test_header_pins_sources_with_sha256, test_vendored_blocks_are_verbatim_and_file_is_current, test_upstream_suite_passes_against_our_copy, test_voltages_kv_engine_semantics. Uses libraries __future__, json, re, shutil, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 750kV (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: 750kV.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV.
Downstream impact
Used directly by 1 file: CI Chess Workflow (cosmic).
What it achieves
PILOT.estate / PILOT.geo (`theme/pilot-estate.js`): the shared geodesy and the engine's `voltagesKv` (W10 CAPSTAN-41). Its code works with 750 kV.
Why it matters
Run by CI Chess Workflow.
Application
cosmic · tools/explore/theme · test
Uses
Pilot Estate (script call), __future__, json, re, shutil, subprocess, pathlib, pytest, hashlib
Used by
run by CI Chess Workflow (workflow run)
Produces
test_header_pins_sources_with_sha256, test_vendored_blocks_are_verbatim_and_file_is_current, test_upstream_suite_passes_against_our_copy, test_voltages_kv_engine_semantics, test_vicinity_uses_engine_voltages_for_osm_tags, test_one_earth_radius_everywhere
Defines here
_node, test_header_pins_sources_with_sha256, test_vendored_blocks_are_verbatim_and_file_is_current, test_upstream_suite_passes_against_our_copy, test_voltages_kv_engine_semantics, test_vicinity_uses_engine_voltages_for_osm_tags, test_one_earth_radius_everywhere
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/test_pilot_geo.py:1-103 · blob 35c489a9f4d2a494d5bb24f689b87922d43b6d35 · 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: unknown
"""PILOT.estate / PILOT.geo (theme/pilot-estate.js): the shared geodesy and the engine's voltagesKv (W10 CAPSTAN-41).

Mirrors upstream tests exactly: grid-distance-maths@8e91b07 test/verify.mjs and test/verify_nearest.mjs are run,
unchanged, against pilot-estate.js through a two-line ES-module shim standing in for src/geodesy.mjs.
Needs node and the clone at /home/claude/src/grid-distance-maths (skips otherwise).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_geo.py
"""
from __future__ import annotations

import json, re, shutil, subprocess
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
ESTATE = HERE / 'pilot-estate.js'
GDM = Path('/home/claude/src/grid-distance-maths')
GDM_SHA = '8e91b07d8312acca5bcaef43e839f06a3b1d642a'
NODE = shutil.which('node')
needs_node = pytest.mark.skipif(not NODE, reason='node not installed')


def _node(js: str) -> str:
    r = subprocess.run([NODE, '-e', js], capture_output=True, text=True, cwd=HERE)
    assert r.returncode == 0, r.stderr
    return r.stdout


def test_header_pins_sources_with_sha256():
    head = ' '.join(ESTATE.read_text()[:4000].split())
    assert f'grid-distance-maths@{GDM_SHA} src/geodesy.mjs' in head
    assert 'ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/v9-geodesy.js' in head
    assert len(re.findall(r'file sha256 [0-9a-f]{64}', head)) == 5
    assert '6378.137' in head and 'screening approximation' in head


@pytest.mark.skipif(not (GDM / '.git').exists() or not Path('/home/claude/src/ventus-grid-engine/.git').exists(), reason='clones unavailable')
def test_vendored_blocks_are_verbatim_and_file_is_current():
    """Identity kept (ASTROLABE-44 STAR-4): each block = pinned source with only 'export ' removed; sha256 pins match."""
    import hashlib, importlib.util
    spec = importlib.util.spec_from_file_location('pe', HERE / 'pilot_estate.py'); pe = importlib.util.module_from_spec(spec); spec.loader.exec_module(pe)
    js = ESTATE.read_text()
    assert js == pe.build(), 'pilot-estate.js is stale: run python3 tools/explore/theme/pilot_estate.py'
    for name, repo, commit, path, a, b, names, lic in pe.BLOCKS:
        raw = pe.source(repo, commit, path)
        assert f'file sha256 {hashlib.sha256(raw).hexdigest()}' in js
        block = js.split(f'// >>> {name} begin\n', 1)[1].split(f'\n// <<< {name} end', 1)[0]
        orig = raw.decode().split('\n'); orig = orig[a - 1:b] if b else orig
        got = block.split('\n')
        assert len(got) == len(orig), name
        changed = [(o, g) for o, g in zip(orig, got) if o != g]
        assert all(o.startswith(('export ', 'import ')) for o, g in changed), (name, changed[:3])
        assert all(g == o[len('export '):] or (o.startswith('import ') and g.startswith('const {')) for o, g in changed), name


@needs_node
@pytest.mark.skipif(not (GDM / '.git').exists(), reason='grid-distance-maths clone not available')
@pytest.mark.parametrize('suite', ['verify.mjs', 'verify_nearest.mjs'])
def test_upstream_suite_passes_against_our_copy(tmp_path, suite):
    (tmp_path / 'src').mkdir(); (tmp_path / 'test').mkdir()
    (tmp_path / 'package.json').write_text('{"type": "module"}')
    names = ['R_ATLAS', 'R_MEAN', 'R_UK', 'WGS84', 'curvatureKm', 'localScaleKm', 'distanceKm', 'distanceEllipsoidalKm', 'pathLengthKm',
             'initialBearingDeg', 'destinationPoint', 'distanceToSegmentKm', 'distanceToLineKm', 'geodesicCircle',
             'circleApproximationError', 'polygonAreaKm2', 'areaUnits', 'SpatialIndex', 'STRAIGHT_LINE_CAVEAT']
    (tmp_path / 'src' / 'geodesy.mjs').write_text(
        "import { createRequire } from 'module';\n"
        f"const g = createRequire(import.meta.url)({json.dumps(str(ESTATE))}).geo;\n"
        + ''.join(f'export const {n} = g.{n};\n' for n in names))
    src = subprocess.run(['git', '-C', str(GDM), 'show', f'{GDM_SHA}:test/{suite}'], capture_output=True, text=True).stdout
    assert src, suite
    (tmp_path / 'test' / suite).write_text(src)
    r = subprocess.run([NODE, f'test/{suite}'], capture_output=True, text=True, cwd=tmp_path, timeout=300)
    assert r.returncode == 0, (r.stdout[-3000:], r.stderr[-2000:])


@needs_node
def test_voltages_kv_engine_semantics():
    out = json.loads(_node("const e=require('./pilot-estate.js');console.log(JSON.stringify(["
                           "e.voltagesKv({voltage:'33000;750'}), e.voltagesKv({voltage:'132000;33000'}), e.voltagesKv({kv:'400'}),"
                           "e.voltagesKv({kv:33, voltage:'33000'}), e.voltagesKv(null)]))"))
    assert out == [[33, 0.75], [132, 33], [400], [33], []]


@needs_node
def test_vicinity_uses_engine_voltages_for_osm_tags():
    out = json.loads(_node("const v=require('./pilot-vicinity.js');"
                           "const gj={features:[{type:'Feature',properties:{name:'Depot',voltage:'33000;750'},geometry:{type:'Point',coordinates:[-1,52]}}]};"
                           "console.log(JSON.stringify(v.parseSubs(gj).map(s=>s.kv)))"))
    assert out == [[33, 0.75]], 'a 750 V traction supply must not read as 750 kV'


@needs_node
def test_one_earth_radius_everywhere():
    """Review finding 2: the 0.112 % split between modules is gone; nothing uses 6371 km."""
    for p in [HERE / 'pilot.js'] + sorted(HERE.glob('pilot-*.js')):
        s = re.sub(r'//[^\n]*', '', re.sub(r'/\*.*?\*/', '', p.read_text(), flags=re.S))   # code, not comments
        if p.name == 'pilot-estate.js':
            continue
        if p.name == 'pilot-lightning.js' and 'P.geo' not in s and '6378.137' not in s:
            continue   # pending: pre-rework copy still on 6371 km; W08 FLASHOVER-31's rework moves it to R_ATLAS
        assert not re.search(r'6371(?:\.0088|008\.8|\b)', s), f'{p.name} uses the mean radius'
    d = float(_node("const g=require('./pilot-estate.js').geo;console.log(g.distM(51.5072,-0.1276,52.2053,0.1218))"))
    assert abs(d - 79_581.349) < 0.01, d   # London to Cambridge, independent haversine on R 6378.137 km