GLOBALGRID2050 / EXPLORE CODE

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

Visualise and 2 more files

A Python command-line tool in the explore folder of Cosmic that reads sections, communities, drift and wafer, using haversine and SHA-256.

700 lines of Python and JavaScript and HTML from cosmic, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1172 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. Explore — Visual render · cosmic / tools/explore/visual/app.js lines 701–971
  2. Template render · cosmic / tools/explore/visual/template.html lines 1–57
  3. Visualise storage · cosmic / tools/explore/visualise.py lines 1–372

Explore — Visual

A JavaScript file in the tools folder of Cosmic that builds wafer and grid, fits cam, calculates planar distances and draws on a canvas, using SHA-256 and Louvain.

rendercosmic / tools/explore/visual/app.js · lines 701–971 of 971 (continued from section 1171) · Not reached from any entry point (candidate for review) · pattern renderLegend (shared by 2 files)

What it does
It draws its content. Defines 83 functions or classes, including $, narrow, mapLike, esc, path. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: JSON file graph.json. Out: canvas drawing.
What it achieves
It maps like (`mapLike`), builds wafer (`buildWafer`) and builds grid (`buildGrid`). Explore Code visualiser. Vanilla canvas; reads `graph.json` (coordinates precomputed by `visualise.py`). It responds to resize, hashchange and input events.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/visual · script
Uses
none found
Used by
none found
Produces
$, narrow, mapLike, esc, path, title, human, repoName, secUrl, isOv, cat, catColour
Defines here
suggest, showSug, matches, shownIds, setMatch, choose, runCmd, setView, setColour, setRepo, select, applyAll, setLegend, writeHash, readHash, bind, up
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/visual/app.js:701-971 · blob 613252f7083767a8e4ab2b0da34e537da8b7d10e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unreached_review
  function suggest() {
    var s = q.value.trim().toLowerCase(); sugItems = []; sugOn = 0;
    if (!s) { sug.hidden = true; setMatch(''); return; }
    var mc = s.match(/^(repo|topic|role):(.*)$/);
    if (mc) {
      var list = mc[1] === 'repo' ? D.repos.map(function (r) { return r[0]; }) : mc[1] === 'topic' ? D.topics.map(function (t) { return t[0]; }) : D.roles.map(function (r) { return r[0]; });
      list.forEach(function (x) { if (x.toLowerCase().indexOf(mc[2]) >= 0 && sugItems.length < 14) sugItems.push({ cmd: mc[1] + ':' + x, label: mc[1] + ': ' + x }); });
    } else {
      VIEWS.concat(MODES.map(function (m) { return 'colour ' + m; })).forEach(function (c) { if (c.indexOf(s) === 0) sugItems.push({ cmd: c, label: '› ' + c }); });
      D.repos.forEach(function (r) { if (r[0].toLowerCase().indexOf(s) >= 0 && sugItems.length < 6) sugItems.push({ cmd: 'repo:' + r[0], label: 'repo: ' + r[0] + ' <small>' + r[3] + ' files</small>' }); });
      var idx = searchIndex(), hits = [];
      for (var i = 0; i < N; i++) { var p = idx[i].indexOf(s); if (p >= 0) hits.push([idx[i].indexOf(s) === 0 ? 0 : p < P.b[i].length ? 1 : 2, i]); }
      hits.sort(function (a, b) { return a[0] - b[0] || P.b[a[1]].length - P.b[b[1]].length || a[1] - b[1]; });
      if (hits.length > 1 && s.length >= 2) sugItems.unshift({ all: 1, label: '› show all ' + hits.length + ' matches on the map' });
      hits.slice(0, 14).forEach(function (h) { sugItems.push({ f: h[1], label: esc(P.b[h[1]]) + ' <small>' + esc(repoName(h[1]) + ' / ' + path(h[1])) + '</small>' }); });
    }
    sug.innerHTML = sugItems.map(function (it, k) { return '<div role="option" id="sug-' + k + '" data-k="' + k + '" aria-selected="' + (k === sugOn) + '" class="' + (k === sugOn ? 'on' : '') + '">' + it.label + '</div>'; }).join('');
    showSug(!!sugItems.length);
    setMatch(s.length >= 2 && !mc ? s : '');
  }
  function showSug(on) {
    sug.hidden = !on; q.setAttribute('aria-expanded', on ? 'true' : 'false');
    if (on && sugItems.length) q.setAttribute('aria-activedescendant', 'sug-' + sugOn); else q.removeAttribute('aria-activedescendant');
  }
  function matches() { var a = []; for (var i = 0; i < N; i++) if (lit(i)) a.push(i); return a; }
  function shownIds() { var a = []; for (var i = 0; i < N; i++) if (shown(i)) a.push(i); return a; }
  function setMatch(s) {
    V.q = s;
    if (!s) { matchSet = null; redraw(); return; }
    var idx = searchIndex(); matchSet = new Uint8Array(N);
    for (var i = 0; i < N; i++) if (idx[i].indexOf(s) >= 0) matchSet[i] = 1;
    redraw();
  }
  function choose(it) {
    if (!it) return;
    showSug(false);
    if (it.all) { if (V.view === 'flow') setView(narrow() ? 'map' : 'pipeline'); fitTo(matches(), 'match "' + V.q + '"'); return; }
    if (it.f !== undefined) { q.value = ''; setMatch(''); select(it.f, true, true); return; }
    if (it.cmd) runCmd(it.cmd);
  }
  function runCmd(c) {
    var m;
    if ((m = c.match(/^repo:(.*)$/))) { setRepo(m[1]); q.value = ''; setMatch(''); }
    else if ((m = c.match(/^topic:(.*)$/))) { var ti = D.topics.findIndex(function (t) { return t[0] === m[1]; }); V.topic = ti; $('ftopic').value = ti >= 0 ? m[1] : ''; q.value = ''; setMatch(''); applyAll(); if (ti >= 0) fitTo(shownIds(), 'in ' + D.topics[ti][1]); }
    else if ((m = c.match(/^role:(.*)$/))) {
      var ri = D.roles.findIndex(function (r) { return r[0] === m[1]; });
      setColour('role'); V.hidden = {}; D.roles.forEach(function (_, k) { if (k !== ri) V.hidden[k] = 1; }); q.value = ''; setMatch(''); applyAll();
      if (ri >= 0) fitTo(shownIds(), 'with role ' + D.roles[ri][0]);
    }
    else if ((m = c.match(/^colou?r (\w+)$/)) && MODES.indexOf(m[1]) >= 0) { setColour(m[1]); q.value = ''; setMatch(''); applyAll(); }
    else if (VIEWS.indexOf(c) >= 0) { q.value = ''; setMatch(''); setView(c); }
  }

  // ------------------------------------------------------------ state
  function setView(v, keep) {
    if (v === 'wafer' && !gridIx.wafer) { // positions are computed once the permanent repo numbers arrive
      if (!D.ov.wafer) v = 'map';
      else { ensureOv('wafer', function () { cams.wafer = null; setView('wafer', keep); }); return; }
    }
    var changed = V.view !== v;
    V.view = v;
    if (changed && !keep) { V.sel = -1; V.cell = null; V.hov = -1; showInfo(); } // a new view starts clean
    Array.prototype.forEach.call(document.querySelectorAll('#tabs button'), function (b) { b.setAttribute('aria-selected', b.dataset.view === v ? 'true' : 'false'); });
    flowEl.hidden = v !== 'flow'; $('legendbox').hidden = v === 'flow'; cv.style.visibility = v === 'flow' ? 'hidden' : 'visible'; tip.hidden = true;
    if (v === 'flow') renderFlow();
    renderLegend(); writeHash(changed); redraw();
  }
  function setColour(m) {
    if (V.colour !== m) { V.colour = m; V.hidden = {}; $('mode').value = m; }
    if (isOv(m) && !OV[m]) ensureOv(m, function () { if (V.colour === m) applyAll(); });
  }
  function setRepo(name) {
    V.repo = D.repos.findIndex(function (r) { return r[0] === name; });
    $('frepo').value = V.repo >= 0 ? name : ''; applyAll();
    if (V.repo >= 0) fitTo(shownIds(), 'in ' + name);
    redraw();
  }
  function select(i, centre, focus) {
    var changed = V.sel !== i;
    if (centre && i >= 0 && V.view === 'flow') setView(narrow() ? 'map' : 'pipeline', true);
    V.sel = i; V.cell = null; tip.hidden = true; V.hov = -1; showInfo(); writeHash(changed && i >= 0);
    if (centre && i >= 0) centreOn(i, mapLike(V.view) ? 1.2 : 0.9);
    if (focus && i >= 0) { var h2 = info.querySelector('h2'); if (h2) h2.focus({ preventScroll: true }); }
    redraw();
  }
  function applyAll(first) {
    bundleCache = null;
    if (V.sel >= 0 && !shown(V.sel)) V.sel = -1; // a filter that hides the selection closes its panel
    renderLegend(); showInfo();
    if (V.view === 'flow') renderFlow();
    writeHash(); redraw();
    if (first) { setView(V.view, true); if (V.sel >= 0) centreOn(V.sel, mapLike(V.view) ? 1.2 : 0.9); }
  }
  function setLegend(open) {
    legend.hidden = !open; $('legnote').hidden = !open;
    $('legtitle').setAttribute('aria-expanded', open ? 'true' : 'false'); $('legendbox').className = open ? '' : 'closed';
  }
  function writeHash(push) { // push: a new history step (selection or view), so Back walks the trail
    if (!D) return;
    var h = ['view=' + V.view];
    if (V.sel >= 0) h.push('file=' + V.sel);
    if (V.colour !== 'role') h.push('colour=' + V.colour);
    if (V.topic >= 0) h.push('topic=' + encodeURIComponent(D.topics[V.topic][0]));
    if (V.repo >= 0) h.push('repo=' + encodeURIComponent(D.repos[V.repo][0]));
    if (V.edges) h.push('edges=1');
    if (V.reach) h.push('reach=1');
    if (V.only) h.push('only=1');
    if (V.drift) h.push('drift=1');
    if (V.safe) h.push('safe=1');
    if (V.pulse) h.push('pulse=1');
    var hid = Object.keys(V.hidden); if (hid.length) h.push('hide=' + hid.join(','));
    var s = '#' + h.join('&');
    if (location.hash !== s) { history[push && location.hash.length > 1 ? 'pushState' : 'replaceState'](null, '', s); }
    lastHash = location.hash;
  }
  function readHash() {
    var o = {};
    location.hash.replace(/^#/, '').split('&').forEach(function (kv) { var p = kv.split('='); if (p[0]) o[p[0]] = decodeURIComponent(p[1] || ''); });
    V.view = VIEWS.indexOf(o.view) >= 0 ? o.view : (narrow() ? 'map' : 'pipeline'); // phones open on the Estate galaxy
    V.colour = MODES.indexOf(o.colour) >= 0 ? o.colour : 'role'; $('mode').value = V.colour;
    if (isOv(V.colour)) setColour(V.colour);
    V.sel = o.file !== undefined && o.file !== '' && +o.file >= 0 && +o.file < N ? +o.file : -1;
    V.topic = o.topic ? D.topics.findIndex(function (t) { return t[0] === o.topic; }) : -1; $('ftopic').value = V.topic >= 0 ? o.topic : '';
    V.repo = o.repo ? D.repos.findIndex(function (r) { return r[0] === o.repo; }) : -1; $('frepo').value = V.repo >= 0 ? o.repo : '';
    V.edges = o.edges === '1'; V.reach = o.reach === '1'; V.only = o.only === '1';
    $('tedges').checked = V.edges; $('treach').checked = V.reach; $('tonly').checked = V.only;
    V.drift = !!D.ov.drift && o.drift === '1'; V.safe = !!D.ov.drift && o.safe === '1';
    if ($('tdrift')) { $('tdrift').checked = V.drift; $('tsafe').checked = V.safe; }
    if (V.drift || V.safe) ensureOv('drift', function () { applyAll(); });
    V.pulse = !!D.ov.faraday && o.pulse === '1'; if ($('tfaraday')) $('tfaraday').checked = V.pulse;
    if (V.pulse) ensureOv('faraday', function () { applyAll(); });
    V.hidden = {}; if (o.hide) o.hide.split(',').forEach(function (k) { V.hidden[k] = 1; });
  }

  // ------------------------------------------------------------ input
  function bind() {
    window.addEventListener('resize', function () { resize(); });
    window.addEventListener('hashchange', function () { // Back / Forward / an edited link
      if (location.hash === lastHash) return;
      lastHash = location.hash; readHash(); applyAll(true);
    });
    Array.prototype.forEach.call(document.querySelectorAll('#tabs button'), function (b) { b.onclick = function () { setView(b.dataset.view); }; });
    $('ftoggle').onclick = function () {
      var open = $('bar').classList.toggle('open'); this.setAttribute('aria-expanded', open ? 'true' : 'false'); resize();
    };
    if ($('tdrift')) {
      $('tdrift').onchange = function () { V.drift = this.checked; ensureOv('drift', function () { applyAll(); }); writeHash(); };
      $('tsafe').onchange = function () {
        V.safe = this.checked; writeHash();
        ensureOv('drift', function () { applyAll(); if (V.safe) fitTo(shownIds(), 'for safe review'); });
      };
    }
    if ($('tfaraday')) {
      $('tfaraday').onchange = function () {
        V.pulse = this.checked; pulseFor = -1; writeHash();
        ensureOv('faraday', function () { applyAll(); if (V.pulse && V.sel < 0) toast('Tap a file to send the pulse to the files that use it', 3500); });
      };
    }
    $('mode').onchange = function () { setColour(this.value); applyAll(); };
    $('ftopic').onchange = function () {
      var v = this.value; V.topic = v === '' ? -1 : D.topics.findIndex(function (t) { return t[0] === v; }); applyAll();
      if (V.topic >= 0) fitTo(shownIds(), 'in ' + D.topics[V.topic][1]); else $('fit').onclick();
    };
    $('frepo').onchange = function () { setRepo(this.value); };
    $('tedges').onchange = function () { V.edges = this.checked; writeHash(); redraw(); };
    $('treach').onchange = function () { V.reach = this.checked; applyAll(); };
    $('tonly').onchange = function () { V.only = this.checked; if (V.only && !V.reach) { V.reach = true; $('treach').checked = true; } applyAll(); };
    $('fit').onclick = function () { if (V.view !== 'flow') { cams[V.view] = fitCam(V.view); redraw(); } };
    $('legtitle').onclick = function () { setLegend(legend.hidden); };
    legend.onclick = function (ev) {
      var li = ev.target.closest('li'); if (!li) return;
      if (li.dataset.k === 'all') V.hidden = {}; else if (V.hidden[li.dataset.k]) delete V.hidden[li.dataset.k]; else V.hidden[li.dataset.k] = 1;
      applyAll();
    };
    legend.ondblclick = function (ev) {
      var li = ev.target.closest('li'); if (!li || li.dataset.k === 'all') return;
      V.hidden = {}; Array.prototype.forEach.call(legend.querySelectorAll('li[data-k]'), function (x) { if (x.dataset.k !== li.dataset.k && x.dataset.k !== 'all') V.hidden[x.dataset.k] = 1; });
      applyAll(); fitTo(shownIds(), 'in ' + catTitle(+li.dataset.k));
    };
    info.onclick = function (ev) {
      var t = ev.target.closest('[data-f],[data-act]'); if (!t) return;
      if (t.dataset.act === 'close') { V.sel = -1; V.cell = null; showInfo(); writeHash(); redraw(); return; }
      select(+t.dataset.f, true, true);
    };
    flowEl.onclick = function (ev) {
      var td = ev.target.closest('td.c'); if (!td) return;
      V.sel = -1; V.cell = { a: +td.dataset.a, b: +td.dataset.b, n: +td.dataset.n, stage: td.dataset.st === '1' }; showInfo();
    };
    q.addEventListener('input', suggest);
    q.addEventListener('keydown', function (ev) {
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
        ev.preventDefault(); if (!sugItems.length) return;
        sugOn = (sugOn + (ev.key === 'ArrowDown' ? 1 : sugItems.length - 1)) % sugItems.length;
        Array.prototype.forEach.call(sug.children, function (d, k) { d.className = k === sugOn ? 'on' : ''; d.setAttribute('aria-selected', k === sugOn ? 'true' : 'false'); });
        showSug(true);
      } else if (ev.key === 'Enter') {
        ev.preventDefault(); var raw = q.value.trim();
        if (/^(repo|topic|role):\S+$|^(pipeline|map|flow|wafer)$|^colou?r \w+$/.test(raw) && !(sugItems[sugOn] && sugItems[sugOn].f !== undefined)) runCmd(raw); else choose(sugItems[sugOn]);
        showSug(false);
      } else if (ev.key === 'Escape') { q.value = ''; suggest(); q.blur(); }
    });
    sug.addEventListener('mousedown', function (ev) { var d = ev.target.closest('[data-k]'); if (d) { ev.preventDefault(); choose(sugItems[+d.dataset.k]); } });
    q.addEventListener('blur', function () { setTimeout(function () { showSug(false); }, 150); });
    document.addEventListener('keydown', function (ev) {
      if (ev.target.tagName === 'INPUT' || ev.target.tagName === 'SELECT' || ev.ctrlKey || ev.metaKey || ev.altKey) return;
      var k = ev.key;
      if (k === '1') setView('pipeline'); else if (k === '2') setView('map'); else if (k === '3') setView('flow');
      else if (k === '4' && D.ov.wafer) setView('wafer');
      else if (k === 'l') setLegend(legend.hidden);
      else if (k === 'd' && $('tdrift')) { $('tdrift').checked = !V.drift; $('tdrift').onchange(); }
      else if (k === 'p' && $('tfaraday')) { $('tfaraday').checked = !V.pulse; $('tfaraday').onchange(); }
      else if (k === '/') { ev.preventDefault(); q.focus(); }
      else if (k === 'c') { setColour(MODES[(MODES.indexOf(V.colour) + 1) % MODES.length]); applyAll(); }
      else if (k === 'e') { V.edges = !V.edges; $('tedges').checked = V.edges; writeHash(); redraw(); }
      else if (k === 'r') { V.reach = !V.reach; $('treach').checked = V.reach; applyAll(); }
      else if (k === '0') $('fit').onclick();
      else if (k === 'Escape') { V.sel = -1; V.cell = null; showInfo(); writeHash(); redraw(); }
      else if (k === '+' || k === '=') zoomAt(W / 2, H / 2, 1.4); else if (k === '-') zoomAt(W / 2, H / 2, 1 / 1.4);
    });
    // pointer: pan, pinch, tap-select, hover
    var pts = {}, moved = 0, pinch = null, last = null;
    cv.addEventListener('wheel', function (ev) {
      ev.preventDefault();
      var r = cv.getBoundingClientRect(), f = Math.exp(-ev.deltaY * (ev.deltaMode ? 0.05 : 0.0015));
      if (ev.shiftKey) { var c = cam(); c.y -= ev.deltaY; redraw(); return; }
      zoomAt(ev.clientX - r.left, ev.clientY - r.top, f);
    }, { passive: false });
    cv.addEventListener('pointerdown', function (ev) {
      cv.setPointerCapture(ev.pointerId); pts[ev.pointerId] = [ev.clientX, ev.clientY]; moved = 0;
      var ids = Object.keys(pts);
      if (ids.length === 2) { var a = pts[ids[0]], b = pts[ids[1]]; pinch = { d: Math.hypot(a[0] - b[0], a[1] - b[1]), mx: (a[0] + b[0]) / 2, my: (a[1] + b[1]) / 2 }; }
      last = [ev.clientX, ev.clientY];
    });
    cv.addEventListener('pointermove', function (ev) {
      var r = cv.getBoundingClientRect(), sx = ev.clientX - r.left, sy = ev.clientY - r.top;
      if (pts[ev.pointerId]) {
        var prev = pts[ev.pointerId]; pts[ev.pointerId] = [ev.clientX, ev.clientY];
        var ids = Object.keys(pts), c = cam();
        if (ids.length === 2 && pinch) {
          var a = pts[ids[0]], b = pts[ids[1]], d = Math.hypot(a[0] - b[0], a[1] - b[1]), mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;
          c.x += mx - pinch.mx; c.y += my - pinch.my; zoomAt(mx - r.left, my - r.top, d / pinch.d);
          pinch = { d: d, mx: mx, my: my }; moved += 10; return;
        }
        var dx = ev.clientX - prev[0], dy = ev.clientY - prev[1]; moved += Math.abs(dx) + Math.abs(dy);
        if (moved > 4) { c.x += dx; c.y += dy; tip.hidden = true; redraw(); }
        return;
      }
      if (ev.pointerType === 'mouse') {
        var i = hit(sx, sy);
        if (i !== V.hov) { V.hov = i; cv.style.cursor = i >= 0 ? 'pointer' : 'crosshair'; redraw(); }
        showTip(i, sx, sy);
      }
    });
    function up(ev) {
      var r = cv.getBoundingClientRect(), wasTap = pts[ev.pointerId] && moved <= 4 && Object.keys(pts).length === 1;
      delete pts[ev.pointerId]; if (Object.keys(pts).length < 2) pinch = null;
      if (wasTap && ev.type === 'pointerup') {
        var i = hit(ev.clientX - r.left, ev.clientY - r.top);
        select(i, false);
        V.hov = -1; showTip(-1);
      }
    }
    cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
    cv.addEventListener('pointerleave', function () { if (V.hov >= 0) { V.hov = -1; redraw(); } tip.hidden = true; });
    cv.addEventListener('dblclick', function (ev) { var r = cv.getBoundingClientRect(); zoomAt(ev.clientX - r.left, ev.clientY - r.top, 2); });
  }

  // test hook: wafer positions in die units, to check them against tools/explore/lab/wafer.py
  window.__wafer = function () { return WL ? Array.prototype.slice.call(WL.raw) : null; };
  load();
})();

Template

A web page in the visual folder of Cosmic that reads inputs for mode, ftopic and frepo. Published at https://ventusltd.github.io/cosmic/tools/explore/visual/template.html.

rendercosmic / tools/explore/visual/template.html · lines 1–57 of 57 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/visual/template.html.
What it achieves
The GlobalGrid2050 code estate drawn as a pipeline (ingest, transform, engineering output), an estate map and an import flow matrix, coloured by function.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/visual · page
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/visual/template.html:1-57 · blob 6bb7a8b489bb4998b31b50c3fde2a9f47f7d936e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Explore Code visualiser — GlobalGrid2050</title>
<meta name="author" content="Ventus Ltd — GlobalGrid2050">
<meta name="description" content="The GlobalGrid2050 code estate drawn as a pipeline (ingest, transform, engineering output), an estate map and an import flow matrix, coloured by function.">
<style>
{{CSS}}
</style>
</head>
<body>
<a class="skip" href="#plain">Skip to the plain list</a>
<header id="bar" data-gen="{{GEN}}">
  <a class="brand" href="../index.html" title="Explore Code home">EXPLORE CODE</a>
  <nav id="tabs" role="tablist" aria-label="Views">
    <button role="tab" data-view="pipeline" title="Pipeline (1)"><span class="k">1 </span>Pipeline</button>
    <button role="tab" data-view="map" title="Estate map (2)"><span class="k">2 </span>Estate</button>
    <button role="tab" data-view="flow" title="Flow matrix (3)"><span class="k">3 </span>Flow</button>
    {{WAFER_TAB}}
  </nav>
  <div id="cmd"><label for="q" class="vh">Search files, or type a command</label><input id="q" type="search" autocomplete="off" spellcheck="false" placeholder="/ search file, repo, path, function" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="sug"><div id="sug" role="listbox" aria-label="Suggestions" hidden></div></div>
  <button id="ftoggle" aria-expanded="false" aria-controls="bar">filters</button>
  <label class="more">colour <select id="mode" aria-label="Colour mode"><option value="role">role</option><option value="topic">topic</option><option value="stage">stage</option><option value="pattern">pattern</option>{{OV_OPTIONS}}</select></label>
  <select id="ftopic" class="more" aria-label="Filter by topic"><option value="">all topics</option></select>
  <select id="frepo" class="more" aria-label="Filter by repository"><option value="">all repos</option></select>
  <label class="more" title="All edges (e)"><input type="checkbox" id="tedges"> all edges</label>
  <label class="more" title="Reachability overlay (r)"><input type="checkbox" id="treach"> reachability</label>
  <label class="more" title="Show only files not reached from an entry point"><input type="checkbox" id="tonly"> only candidates for review</label>
  {{OV_CONTROLS}}
  <button id="fit" class="more" title="Fit (0)">fit</button>
</header>
<main id="stage">
  <canvas id="cv" aria-label="Code estate drawing; use the search bar or the plain list below to navigate"></canvas>
  <div id="flow" hidden></div>
  <div id="tip" hidden></div>
  <aside id="legendbox" aria-label="Legend"><button id="legtitle" aria-expanded="true" aria-controls="legend">role</button><ul id="legend">{{LEGEND}}</ul><div id="legnote"></div></aside>
  <aside id="info" hidden aria-live="polite" aria-label="Selected file"></aside>
  <div id="toast" role="status" aria-live="polite" hidden></div>
  <div id="load" role="progressbar" aria-label="Loading the map" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" data-bytes="{{GBYTES}}"><div id="loadbar"></div><span id="loadtxt">Loading map ({{GSIZE}})…</span></div>
  <div id="status" aria-live="polite">Loading map ({{GSIZE}})…</div>
</main>
<noscript><p class="ns">This visualiser draws with JavaScript. Without it, browse the code by <a href="../index.html">topic</a>, <a href="../search.html">search</a>, or the lists below.</p></noscript>
<section id="plain" tabindex="-1">
  <h1>Explore Code visualiser — GlobalGrid2050</h1>
  <p>{{NFILES}} files in {{NREPOS}} repositories, drawn as an Ingest → Transform → Engineering output pipeline, an estate map and an import flow matrix. Plain navigation:</p>
  <h2>Topics</h2><ul>{{TOPIC_LIST}}</ul>
  <h2>Largest repositories</h2><ul>{{REPO_LIST}}</ul>
  <p>The drawing above has {{NFILES}} files · {{NREPOS}} repos · {{NEDGES}} imports · cut {{CUT}}.</p>
  <p><a href="../index.html">All topics</a> · <a href="../search.html">Search</a> · <a href="README.md">About this page</a></p>
</section>
<script>
{{JS}}
</script>
</body>
</html>

Visualise

A Python command-line tool in the explore folder of Cosmic that reads sections, communities, drift and wafer, using haversine and SHA-256.

storagecosmic / tools/explore/visualise.py · lines 1–372 of 986 · Entry point · pattern render_page (shared by 2 files)

What it does
It loads sections, communities, drift and wafer. Defines 36 functions or classes, including slug, words_of, clip, fnv1a, pattern_colour. Uses libraries argparse, colorsys, glob, html, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: 132kV, 33kV, 11kV. README: "`build_graph.json` (see `GRAPH-CONTRACT.md`) feeds `visualise.py`, which writes `visual/index.html`: pipeline (Ingest / Transform / Output), estate map and topic flow, coloured by role, topic, stage or pattern, with a reachability overlay."
Inputs & outputs
In: Parquet file files.parquet; Parquet file sections.parquet; JSON file keys.json; JSON file communities.json; JSON file drift.json; JSON file wafer.json; JSON file graph.json; JSON file build_graph.json. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 132kV, 33kV, 11kV.
Downstream impact
Used directly by 3 files: Extras (cosmic); Ship (cosmic); Test Visualise (cosmic). Reached from 2 other entry points, including Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It compiles visual (`compile_visual`), reads lab (`read_lab`) and reads clarity (`read_clarity`). Explore Code visualiser: `build_graph.json` -> `visual/index.html` + `visual/graph.json`. It accepts `--graph`, `--from-parquet` and `--out`.
Why it matters
Run by Extras and Ship. Checked by Test Visualise.
Application
cosmic · tools/explore · Python CLI
Uses
argparse, colorsys, glob, html, json, math, os, posixpath
Used by
run by Extras (script call), run by Ship (script call), imported by Test Visualise (import)
Produces
slug, words_of, clip, fnv1a, pattern_colour, humanise, approx_role, graph_from_parquet, pack_siblings, layout_pipeline, layout_map, compile_visual
Defines here
slug, words_of, clip, fnv1a, pattern_colour, humanise, approx_role, graph_from_parquet, _place, _intersects, _N, __init__, _score, pack_siblings
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/visualise.py:1-372 · blob cbccadf5dbc61cc1c38999234caa158e951504ea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Explore Code visualiser: build_graph.json -> visual/index.html + visual/graph.json.

    python tools/explore/visualise.py --graph <explore-code>/build_graph.json --out <explore-code>/visual
    python tools/explore/visualise.py --from-parquet <explore-code>/data --out <explore-code>/visual

Reads the build graph (GRAPH-CONTRACT.md, schema explore-build-graph-v1) and writes:

  visual/graph.json  compact columnar data with every node's x/y precomputed here, deterministically,
                     for two layouts: the Pipeline (columns Ingest | Transform | Output | Unknown, repos
                     stacked inside each column) and the Estate map (repos packed as circles sized by
                     lines, top-level folders packed inside, files on a sunflower spiral in each folder).
  visual/index.html  one self-contained page (vanilla canvas, no library, works offline) with the
                     Pipeline, Estate map and Flow views, colour modes role | topic | stage | pattern,
                     a reachability overlay, search/command bar, filters and shareable URL hash state.
  visual/README.md   what the page shows and how it was made.

--from-parquet synthesises a contract-shaped graph from the build's Parquet tables (files.parquet,
sections.parquet) for use before build_graph.json exists: titles come from paths, `achieves` from the
stated capability, imports from the "Uses" links on the section pages (if ../s/ is beside the data
directory), role is approximated from path and capability words, stage is "unknown", entry/reachable
are null and pattern is the file name when the same name appears in 3+ files.

Same graph in, byte-identical files out: no clocks, no randomness, all orders sorted, coordinates
rounded to integers.

Optional overlays (generator 2.x). Each is read only when its flag is given and its data loads and lines
up with the graph; otherwise a warning is printed and the overlay, and its button, are left out:

  --lab DIR        lab output (tools/explore/lab/run.py): communities.json (community colour mode),
                   drift.json (near-copy edges + "safe review" filter), wafer.json (permanent repo numbers
                   for the Wafer view, whose positions the browser computes from each file's repo/path key).
                   Files are matched by key (repo/path) through DIR/keys.json, else by id when the cut matches.
  --clarity FILE   clarity.json (translator Clarity group: unique and in use | copy | via copies | not reached)
  --periodic FILE  periodic.json (explore-periodic-v1: each file's element, coloured by period)
  --laws PATH      a laws overlay file, or a directory of them (per-file law classes, see read_categorical)
  --faraday FILE   laws.json: the Faraday pulse (law FA, measured rate users change with the file they use)
"""
import argparse
import colorsys
import glob
import html
import json
import math
import os
import posixpath
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ASSETS = os.path.join(HERE, 'visual')

# 1.x: Pipeline / Estate / Flow. 2.0.0: phone-first page (Estate default on phones, folded controls,
# collapsed legend, zoom to matches, pushState trail, loading bar, plain list for screen readers) and the
# optional overlays community, drift, wafer, clarity, periodic, laws. See tools/explore/CHANGELOG.md.
GENERATOR_VERSION = '2.1.0'

STAGES = ['ingest', 'transform', 'output', 'unknown']
STAGE_TITLES = ['Ingest', 'Transform', 'Engineering output', 'Unknown']
STAGE_COLOURS = ['#66ccff', '#00ff88', '#ff6666', '#4c5a65']

# Fallback palette, identical to GRAPH-CONTRACT.md "Palette" (website + Pipeline News scheme).
ROLES = [
    ('geodesy', 'Geodesy and coordinates', '#00ffff'),
    ('electrical', 'Electrical engineering', '#ffae00'),
    ('energy-data', 'Energy and market data', '#ffff00'),
    ('ingest', 'Ingest: fetch, load, parse', '#66ccff'),
    ('transform', 'Transform: maths, sorting, converting', '#00ff88'),
    ('render', 'Render: DOM, canvas, maps, HTML', '#ff6666'),
    ('interaction', 'Interaction: events, input, routing', '#ffd24a'),
    ('storage', 'Storage: DuckDB, Parquet, files', '#86e1d1'),
    ('test', 'Tests and checks', '#aef7d1'),
    ('automation', 'Automation, CI and build', '#8d95a3'),
    ('docs-config', 'Docs, config and manifests', '#a6adbb'),
    ('other', 'Other', '#4c5a65'),
]
TOPIC_TITLES = {
    'cables': 'Cables and conductors', 'solar-storage': 'Solar and storage design',
    'grid-network': 'Grid network and substations', 'maps-gis': 'Maps, GIS and field navigation',
    'markets-data': 'Electricity markets and data pipelines', 'kuiper-cosmos': 'Kuiper, cosmos and drawing engines',
    'agents-ai': 'AI agents and coordination', 'automation': 'Automation and CI', 'web-apps': 'Websites and apps',
}
# Topic colours: the same website/Pipeline News hues, in a different order so topic mode reads apart from role.
TOPIC_COLOURS = ['#ffae00', '#ffff00', '#0066ff', '#00ffff', '#00ff88', '#ff6666', '#ffd24a', '#8d95a3',
                 '#86e1d1', '#aef7d1', '#66ccff', '#a6adbb']
UNIQUE_GREY = '#2a3038'

# Pipeline layout (world units)
P_DOT, P_COLS, P_GAP, P_HEAD, P_GROUP_GAP, P_MARGIN = 22, 36, 520, 34, 26, 40
P_COLW = P_DOT * P_COLS
# Estate map layout
M_DOT, M_K, M_PAD = 10.0, 0.8, 6.0

TEXT_MAX = {'title': 100, 'achieves': 220, 'why': 180}
DEFINES_MAX = 12


# ---------------------------------------------------------------- utilities
def slug(s):
    return re.sub(r'[^a-z0-9]+', '-', s.lower()).strip('-') or 'x'


def words_of(s):
    s = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s or '')
    return [w for w in re.split(r'[^a-z0-9]+', s.lower()) if w]


def clip(s, n):
    s = ' '.join(str(s or '').split())
    return s if len(s) <= n else s[:n - 1].rstrip() + '…'


def fnv1a(s):
    h = 0x811c9dc5
    for b in s.encode('utf-8'):
        h = ((h ^ b) * 0x01000193) & 0xffffffff
    return h


def pattern_colour(key):
    """A stable, vivid hue per pattern key that sits on the black/cyan base."""
    h = fnv1a(key)
    hue = (h % 360) / 360.0
    light = 0.58 + ((h >> 9) % 3) * 0.06
    sat = 0.9 + ((h >> 13) % 2) * 0.1
    r, g, b = colorsys.hls_to_rgb(hue, light, sat)
    lum = lambda r, g, b: 0.2126 * r + 0.7152 * g + 0.0722 * b
    while lum(r, g, b) < 0.42:  # lift dark hues (blues, violets) so every pattern reads on black
        r, g, b = r + (1 - r) * 0.12, g + (1 - g) * 0.12, b + (1 - b) * 0.12
    return '#%02x%02x%02x' % (round(r * 255), round(g * 255), round(b * 255))


def humanise(path):
    base = posixpath.basename(path)
    stem = base.rsplit('.', 1)[0] if '.' in base[1:] else base
    w = ' '.join(re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', stem).replace('_', ' ').replace('-', ' ').split())
    return (w[:1].upper() + w[1:]) if w else base


LANG = {'py': 'Python', 'js': 'JavaScript', 'mjs': 'JavaScript', 'cjs': 'JavaScript', 'ts': 'TypeScript',
        'html': 'HTML', 'htm': 'HTML', 'css': 'CSS', 'json': 'JSON', 'yml': 'YAML', 'yaml': 'YAML',
        'sh': 'Shell', 'md': 'Markdown', 'toml': 'TOML', 'sql': 'SQL', 'geojson': 'JSON'}

ROLE_WORDS = [  # adapter approximation only; build.py's own rule wins when build_graph.json exists
    ('geodesy', 'geo geodesy geodesic coord coords coordinates bearing bearings projection proj haversine lat lon '
                'latlon distance distances gis lidar terrain utm wgs84 osgb gps elevation'),
    ('electrical', 'cable cables voltage kv 132kv 33kv 11kv derating impedance ampacity conductor conductors '
                   'substation transformer current power fault busbar switchgear sld electrical'),
    ('energy-data', 'generation price prices market markets repd pipeline elexon bmrs energy tracking '
                    'interconnector interconnectors capacity'),
    ('ingest', 'fetch fetcher load loader loaders parse parser read reader import importer scrape scraper ingest '
               'crawler crawl download decode harvest'),
    ('storage', 'storage store db duckdb parquet sqlite cache persist save writer'),
    ('render', 'render renderer draw drawing canvas webgl svg view views ui chart charts paint style styles theme '
               'template templates page'),
    ('interaction', 'event events input nav navigation router routing controls control keyboard touch click'),
    ('transform', 'calc calcs calculate calculations compute math maths util utils convert converter sort index '
                  'transform engine model solver'),
]
ROLE_WORDSETS = [(r, set(w.split())) for r, w in ROLE_WORDS]


def approx_role(path, capability):
    e = path.rsplit('.', 1)[-1].lower() if '.' in posixpath.basename(path) else ''
    pw = set(words_of(path))
    if pw & {'test', 'tests', 'spec', 'smoke', 'proof', 'check', 'checks'} or re.search(r'(^|/)test_|_test\.|\.test\.|\.spec\.', path):
        return 'test'
    if '.github/workflows/' in path or pw & {'workflow', 'workflows', 'ci', 'build', 'release', 'deploy', 'makefile'}:
        return 'automation'
    if e in ('json', 'toml', 'yaml', 'yml', 'md', 'txt', 'cfg', 'ini', 'xml') and e != 'geojson':
        return 'docs-config'
    ws = pw | set(words_of(capability))
    for r, s in ROLE_WORDSETS:
        if ws & s:
            return r
    if e in ('html', 'htm', 'css'):
        return 'render'
    if e == 'sh':
        return 'automation'
    return 'other'


# ---------------------------------------------------------------- Parquet adapter
def graph_from_parquet(data_dir):
    import pyarrow.parquet as pq
    rows = pq.read_table(os.path.join(data_dir, 'files.parquet')).to_pylist()
    secs = pq.read_table(os.path.join(data_dir, 'sections.parquet')).to_pylist()
    rows.sort(key=lambda r: (r['section'], r['block']))
    files, key_of, at = [], {}, {}
    repo_commit = {}
    for r in rows:
        k = (r['repo'], r['path'])
        at[(r['section'], r['block'])] = k
        repo_commit.setdefault(r['repo'], r['commit_sha'])
        if k not in key_of:
            key_of[k] = len(files)
            files.append({'repo': r['repo'], 'path': r['path'], 'section': r['section'], 'block': r['block'],
                          'topic': r['topic'], 'capability': r['capability'] or '', 'lines': 0})
        f = files[key_of[k]]
        f['lines'] = max(f['lines'], r['line_to'])
        if not f['capability'] and r['capability']:
            f['capability'] = r['capability']
    # Imports from the "Uses" links of the section pages, when the pages sit beside data/.
    imports = {}
    sdir = os.path.join(os.path.dirname(os.path.abspath(data_dir)), 's')
    rx_sec = re.compile(r'<section id="f(\d+)">(.*?)</section>', re.S)
    rx_uses = re.compile(r'<dt>Uses</dt><dd>(.*?)</dd>', re.S)
    rx_link = re.compile(r'href="\.\./s/(\d+)\.html#f(\d+)"')
    for page in sorted(glob.glob(os.path.join(sdir, '*.html'))):
        m = re.match(r'(\d+)\.html$', os.path.basename(page))
        if not m:
            continue
        si = int(m.group(1))
        with open(page, encoding='utf-8') as fh:
            text = fh.read()
        for sm in rx_sec.finditer(text):
            src = at.get((si, int(sm.group(1))))
            um = rx_uses.search(sm.group(2))
            if src is None or not um:
                continue
            for lm in rx_link.finditer(um.group(1)):
                dst = at.get((int(lm.group(1)), int(lm.group(2))))
                if dst and dst != src:
                    imports.setdefault(key_of[src], set()).add(key_of[dst])
    names = {}
    for f in files:
        names[posixpath.basename(f['path'])] = names.get(posixpath.basename(f['path']), 0) + 1
    out_files, dependents = [], {}
    for i, f in enumerate(files):
        for j in imports.get(i, ()):
            dependents.setdefault(j, set()).add(i)
    width = max(4, len(str(len(secs))))
    for i, f in enumerate(files):
        base = posixpath.basename(f['path'])
        e = base.rsplit('.', 1)[-1].lower() if '.' in base else ''
        out_files.append({
            'id': i, 'repo': f['repo'], 'path': f['path'],
            'folder_hierarchy': [f['repo']] + f['path'].split('/')[:-1],
            'lang': LANG.get(e, e.upper() or 'Text'), 'lines': f['lines'],
            'section': f['section'], 'block': f['block'], 'topic': f['topic'],
            'title': humanise(f['path']), 'achieves': f['capability'], 'why': '', 'context': '',
            'essay_status': 'auto', 'stage': 'unknown',
            'imports': sorted(imports.get(i, ())), 'imports_external': [],
            'dependents': sorted(dependents.get(i, ())), 'defines': [], 'pure': False,
            'role': approx_role(f['path'], f['capability']),
            'pattern': base if names[base] >= 3 else '', 'entry': None, 'reachable': None,
        })
    tcount = {}
    for s in secs:
        tcount[s['topic']] = tcount.get(s['topic'], 0) + 1
    topics = [{'id': k, 'title': TOPIC_TITLES.get(k, k), 'sections': tcount[k]} for k in
              [t for t in TOPIC_TITLES if t in tcount] + sorted(t for t in tcount if t not in TOPIC_TITLES)]
    return {
        'schema': 'explore-build-graph-v1', 'cut': secs[0]['cut'] if secs else '',
        'base': 'https://code.globalgrid2050.com/explore-code/',
        'topics': topics,
        'repos': [{'repo': r, 'commit': c, 'license': '', 'license_file': None, 'citation': False,
                   'readme_summary': ''} for r, c in sorted(repo_commit.items())],
        'sections': [{'section': s['section'], 'url': 's/%0*d.html' % (width, s['section']), 'topic': s['topic'],
                      'repos': list(s['repos']), 'lines': s['lines'], 'title': s['summary']} for s in secs],
        'files': out_files,
        'roles': [{'id': a, 'title': b, 'colour': c} for a, b, c in ROLES],
        'adapter': 'parquet',
    }


# ---------------------------------------------------------------- circle packing (port of d3 packSiblings)
def _place(b, a, c):
    dx, dy = b[0] - a[0], b[1] - a[1]
    d2 = dx * dx + dy * dy
    if d2:
        a2 = (a[2] + c[2]) ** 2
        b2 = (b[2] + c[2]) ** 2
        if a2 > b2:
            x = (d2 + b2 - a2) / (2 * d2)
            y = math.sqrt(max(0.0, b2 / d2 - x * x))
            c[0], c[1] = b[0] - x * dx - y * dy, b[1] - x * dy + y * dx
        else:
            x = (d2 + a2 - b2) / (2 * d2)
            y = math.sqrt(max(0.0, a2 / d2 - x * x))
            c[0], c[1] = a[0] + x * dx - y * dy, a[1] + x * dy + y * dx
    else:
        c[0], c[1] = a[0] + c[2], a[1]


def _intersects(a, b):
    dr = a[2] + b[2] - 1e-6
    dx, dy = b[0] - a[0], b[1] - a[1]
    return dr > 0 and dr * dr > dx * dx + dy * dy


class _N:
    __slots__ = ('c', 'next', 'prev')

    def __init__(self, c):
        self.c, self.next, self.prev = c, None, None


def _score(node):
    a, b = node.c, node.next.c
    ab = a[2] + b[2]
    dx = (a[0] * b[2] + b[0] * a[2]) / ab
    dy = (a[1] * b[2] + b[1] * a[2]) / ab
    return dx * dx + dy * dy


def pack_siblings(circles):
    """circles: list of [x, y, r] (mutated in place, centred on the origin). Returns the enclosing radius."""
    n = len(circles)
    if not n:
        return 0.0
    a = circles[0]
    a[0] = a[1] = 0.0
    if n == 1:
        return a[2]
    b = circles[1]
    a[0], b[0], b[1] = -b[2], a[2], 0.0
    if n > 2:
        _place(b, a, circles[2])
        a, b, c = _N(circles[0]), _N(circles[1]), _N(circles[2])
        a.next = c.prev = b
        b.next = a.prev = c
        c.next = b.prev = a
        i = 3
        while i < n:
            cc = circles[i]
            _place(a.c, b.c, cc)
            c = _N(cc)
            j, k, sj, sk = b.next, a.prev, b.c[2], a.c[2]
            retry = False
            while True:
                if sj <= sk:
                    if _intersects(j.c, c.c):
                        b = j
                        a.next, b.prev = b, a
                        retry = True
                        break
                    sj += j.c[2]
                    j = j.next
                else:
                    if _intersects(k.c, c.c):
                        a = k
                        a.next, b.prev = b, a
                        retry = True
                        break
                    sk += k.c[2]
                    k = k.prev
                if j is k.next:
                    break
            if retry:
                continue
            c.prev, c.next = a, b
            a.next = b.prev = c
            b = c
            aa = _score(a)
            c = c.next
            while c is not b:
                ca = _score(c)
                if ca < aa:
                    a, aa = c, ca
                c = c.next
            b = a.next
            i += 1
    # Enclosing circle: bounding-box centre, radius to the farthest edge (slightly loose, deterministic).
    x0 = min(c[0] - c[2] for c in circles)
    x1 = max(c[0] + c[2] for c in circles)
    y0 = min(c[1] - c[2] for c in circles)
    y1 = max(c[1] + c[2] for c in circles)
    cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
    r = max(math.hypot(c[0] - cx, c[1] - cy) + c[2] for c in circles)
    for c in circles:
        c[0] -= cx