GLOBALGRID2050 / EXPLORE CODE

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

Props and 1 more file

A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, elements and periodic, using SHA-256. It loads ctx (`load_ctx`) and computes element (`compute_element`).

700 lines of Python and JavaScript from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1122 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. Periodic interaction · cosmic / tools/explore/periodic/page/periodic.js lines 1–240
  2. Props storage · cosmic / tools/explore/periodic/props.py lines 1–460

Periodic

A JavaScript file in the page folder of Cosmic that draws cards. It builds chem (`buildChem`), opens chem (`openChem`) and sets view (`setView`).

interactioncosmic / tools/explore/periodic/page/periodic.js · lines 1–240 of 240 · Not reached from any entry point (candidate for review) · pattern openCard (shared by 6 files)

What it does
It draws cards. Defines 20 functions or classes, including h, numLabel, stateLabel, gcol, pad4. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file cards.json; browser storage (getItem). Out: browser storage (setItem).
What it achieves
Periodic table page behaviour (`feed.py`, LATTICE-62). It reads `cards.json`. It responds to click, keydown and change events.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/periodic/page · script
Uses
none found
Used by
none found
Produces
h, numLabel, stateLabel, gcol, pad4, fmt, ink, colorFn, bin, paint, buildChem, openChem
Defines here
h, numLabel, stateLabel, gcol, pad4, fmt, ink, colorFn, bin, paint, buildChem, openChem, setView, loadCards, showCard, openCard, fillMore, closeCard, byFiles, mark
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/page/periodic.js:1-240 · blob 3e375ab2762076b97c75e3bdba270ec23c30f3b7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: unknown · users: none · canonical: unreached_review
/* Periodic table page behaviour (feed.py, LATTICE-62). Progressive enhancement: every tile is a plain link without JS. */
(function () {
  'use strict';
  var D = document, node = D.getElementById('pt-data');
  if (!node) return;
  var data = JSON.parse(node.textContent), cols = data.cols, E = [], bySym = {}, G = {};
  data.elements.forEach(function (row, j) {
    var e = { props: {} }; cols.forEach(function (c, i) { e[c] = row[i]; });
    data.props.forEach(function (p) { var v = data.pv[p.key][j]; if (v != null) e.props[p.key] = v; });
    E.push(e); bySym[e.sym] = e;
  });
  data.groups.forEach(function (g) { G[g.id] = g; });
  var estate = D.getElementById('pt-estate'), chem = D.getElementById('pt-chem'), legend = D.getElementById('pt-legend');
  var sel = D.getElementById('pt-color'), card = D.getElementById('pt-card'), body = D.getElementById('pt-card-body');
  var cards = null, cardsP = null, lastFocus = null;
  var PAL = ['#00ffff', '#ffae00', '#00ff88', '#ff6666', '#66ccff', '#ffd24a', '#86e1d1', '#aef7d1', '#ffff00'];
  var SEQ = ['#0d3b52', '#0f5f7a', '#1384a3', '#2fb3cc', '#00ffff'];
  var STATE_C = { settled: '#00ff88', unsettled: '#ffd24a', numbered: '#66ccff', candidate: '#a6adbb' };

  function h(tag, attrs, kids) {
    var n = D.createElement(tag);
    Object.keys(attrs || {}).forEach(function (k) {
      if (k === 'text') n.textContent = attrs[k]; else if (k === 'style') n.style.cssText = attrs[k]; else n.setAttribute(k, attrs[k]);
    });
    (kids || []).forEach(function (c) { if (c != null) n.appendChild(typeof c === 'string' ? D.createTextNode(c) : c); });
    return n;
  }
  function numLabel(e) { return e.cand || e.n == null ? 'CANDIDATE' : String(e.n); }
  function stateLabel(e, nvals) {
    if (e.cand) return 'CANDIDATE (proposal, no number)';
    if (e.state === 'unsettled') return 'unsettled' + (nvals ? ': ' + nvals + ' values in the wild' : '');
    return data.stateText[e.state] || e.state;
  }
  function gcol(e) { return (G[e.group] && G[e.group].colour) || data.candidateColor; }
  function pad4(n) { return ('000' + n).slice(-4); }

  // ------------------------------------------------------------------ colouring
  function fmt(x) { return Math.abs(x) >= 100 ? String(Math.round(x)) : String(Math.round(x * 100) / 100); }
  function ink(hex) {
    var r = parseInt(hex.substr(1, 2), 16), g = parseInt(hex.substr(3, 2), 16), b = parseInt(hex.substr(5, 2), 16);
    return (0.299 * r + 0.587 * g + 0.114 * b) > 140 ? '#000' : '#fff';
  }
  function colorFn(mode) {
    if (mode === 'group') {
      return { of: function (e) { return [gcol(e), false]; },
        legend: data.groups.filter(function (g) { return E.some(function (e) { return e.group === g.id; }); }).map(function (g) { return [g.title, g.colour]; }) };
    }
    if (mode === 'state') {
      return { of: function (e) { return [STATE_C[e.state] || '#2f343d', true]; },
        legend: Object.keys(STATE_C).filter(function (s) { return E.some(function (e) { return e.state === s; }); }).map(function (s) { return [s, STATE_C[s]]; }) };
    }
    var key = mode.slice(2), prop = data.props.filter(function (p) { return p.key === key; })[0] || { kind: 'category' };
    var vals = E.map(function (e) { return e.props[key]; }).filter(function (v) { return v != null; });
    if (prop.kind === 'number') {
      // quantile bins, so one very large element does not flatten the rest
      var sorted = vals.slice().sort(function (x, y) { return x - y; }), cuts = [];
      for (var i = 1; i < SEQ.length; i++) { var c = sorted[Math.floor(i * sorted.length / SEQ.length)]; if (cuts.indexOf(c) < 0 && c > sorted[0]) cuts.push(c); }
      var nb = cuts.length + 1, pal = SEQ.slice(SEQ.length - nb);
      var bin = function (v) { var k = 0; while (k < cuts.length && v >= cuts[k]) k++; return k; };
      var u = prop.unit && prop.unit.length < 12 ? ' ' + prop.unit : '';
      var leg = pal.map(function (c, k) {
        var lo = k ? cuts[k - 1] : sorted[0], hi = k < cuts.length ? cuts[k] : sorted[sorted.length - 1];
        return [(k < cuts.length ? fmt(lo) + ' to <' + fmt(hi) : fmt(lo) + ' to ' + fmt(hi)) + u, c];
      });
      leg.push(['no value', '#2f343d']);
      return { of: function (e) { var v = e.props[key]; return v == null ? ['#2f343d', false] : [pal[bin(v)], true]; }, legend: leg };
    }
    var cats = []; vals.forEach(function (v) { v = String(v); if (cats.indexOf(v) < 0) cats.push(v); });
    var leg2 = cats.slice(0, 12).map(function (c, i) { return [c, PAL[i % PAL.length]]; });
    if (cats.length > 12) leg2.push(['(' + (cats.length - 12) + ' more values, colours repeat)', '#2f343d']);
    leg2.push(['no value', '#2f343d']);
    return { of: function (e) { var v = e.props[key]; return v == null ? ['#2f343d', false] : [PAL[cats.indexOf(String(v)) % PAL.length], true]; }, legend: leg2 };
  }
  function paint() {
    var mode = sel ? sel.value : 'group', cf = colorFn(mode);
    estate.querySelectorAll('.pt-el[data-sym]').forEach(function (a) {
      var e = bySym[a.getAttribute('data-sym')]; if (!e) return;
      var c = cf.of(e);
      a.style.setProperty('--c', c[0]); a.style.setProperty('--fill', c[0]);
      a.classList.toggle('pt-solid', !!c[1]);
      if (c[1]) a.style.setProperty('--ink', ink(c[0])); else a.style.removeProperty('--ink');
    });
    legend.textContent = '';
    cf.legend.forEach(function (it) { legend.appendChild(h('span', {}, [h('i', { style: '--c:' + it[1] }), it[0]])); });
  }

  // ------------------------------------------------------------------ chemical analogy view
  var chemBuilt = false, atZ = {};
  function buildChem() {
    if (chemBuilt) return; chemBuilt = true;
    E.forEach(function (e) { if (e.analogy && e.analogy[0]) (atZ[e.analogy[0]] = atZ[e.analogy[0]] || []).push(e); });
    data.chem.forEach(function (c) {
      var z = c[0], list = atZ[z] || [];
      var kids = [h('span', { class: 'pt-n', text: String(z) }), h('b', { text: c[1] }),
        h('span', { class: 'pt-cnt', text: list.length ? list.length + ' code' : '' })];
      var st = 'grid-row:' + c[3] + ';grid-column:' + c[4];
      if (list.length) {
        var dom = {}; list.forEach(function (e) { dom[e.group] = (dom[e.group] || 0) + 1; });
        var top = Object.keys(dom).sort(function (a, b) { return dom[b] - dom[a]; })[0];
        chem.appendChild(h('button', { type: 'button', class: 'pt-el pt-z', 'data-z': String(z), style: st + ';--c:' + ((G[top] && G[top].colour) || '#a6adbb'),
          'aria-label': c[2] + ' (Z=' + z + '): ' + list.length + ' code elements' }, kids));
      } else {
        chem.appendChild(h('span', { class: 'pt-el pt-z pt-empty', style: st, title: c[2] + ' (Z=' + z + '): no code element' }, kids));
      }
    });
    var none = E.filter(function (e) { return !e.analogy || !e.analogy[0]; }).length;
    var frame = D.getElementById('pt-frame');
    frame.parentNode.insertBefore(h('p', { class: 'k pt-chemnote', id: 'pt-chemnote', text: 'Chemical analogy: a playful lens from the mapper; it never replaces an element\'s number or symbol. Tap a chemical element to see which code elements are like it.' + (none ? ' ' + none + ' element(s) have no analogy in the input.' : '') }), frame);
  }
  function openChem(z) {
    var c = data.chem[z - 1], list = (atZ[z] || []).slice().sort(function (a, b) { return a.cand - b.cand || (a.n || 1e6) - (b.n || 1e6); });
    lastFocus = D.activeElement; body.textContent = '';
    body.appendChild(h('h2', { id: 'pt-card-h', style: 'font-size:18px;margin:4px 0 8px' }, [h('span', { class: 'pt-big', style: '--c:#a6adbb', text: c[1] }), c[2] + ' (Z=' + z + ')']));
    body.appendChild(h('p', { class: 'k', text: list.length + ' code element(s) are like ' + c[2] + '.' }));
    var rules = {}; list.forEach(function (e) { var r = e.analogy[3]; if (r) rules[r] = (rules[r] || 0) + 1; });
    Object.keys(rules).forEach(function (r) { body.appendChild(h('p', { class: 'k', text: 'Why: ' + (data.rules[r] || r) + ' (' + rules[r] + ')' })); });
    body.appendChild(h('div', { class: 'pt-cellg pt-cardtiles' }, list.map(function (e) {
      return h('a', { class: 'pt-el' + (e.cand ? ' pt-cand' : '') + (e.state === 'unsettled' ? ' pt-un' : ''), href: e.page, 'data-sym': e.sym,
        style: '--c:' + gcol(e), title: e.name, 'aria-label': e.sym + ' ' + e.name }, [h('span', { class: 'pt-n', text: e.cand ? '?' : String(e.n) }), h('b', { text: e.sym })]);
    })));
    showCard();
  }
  function setView(v) {
    D.querySelectorAll('[data-view]').forEach(function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-view') === v)); });
    if (v === 'chem') buildChem();
    estate.hidden = v === 'chem'; chem.hidden = v !== 'chem';
    if (sel) sel.disabled = v === 'chem';
    legend.hidden = v === 'chem';
    var note = D.getElementById('pt-chemnote'); if (note) note.hidden = v !== 'chem';
    var hint = D.querySelector('.pt-hint'); if (hint) hint.hidden = v === 'chem';
    try { localStorage.setItem('ec-pt:view', v); } catch (e) { /* storage off */ }
  }

  // ------------------------------------------------------------------ card
  function loadCards() {
    if (!cardsP) cardsP = fetch('cards.json').then(function (r) { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then(function (j) { cards = j; return j; });
    return cardsP;
  }
  function showCard() { card.hidden = false; D.body.classList.add('pt-modal'); D.getElementById('pt-x').focus(); }
  function openCard(sym, push) {
    var e = bySym[sym]; if (!e) return;
    if (card.hidden) lastFocus = D.activeElement;
    body.textContent = '';
    body.appendChild(h('h2', { id: 'pt-card-h', style: 'font-size:18px;margin:4px 0 8px' },
      [h('span', { class: 'pt-big' + (e.cand ? ' pt-cand' : ''), style: '--c:' + gcol(e), text: e.sym }), e.name]));
    var g = G[e.group] || { title: e.group }, per = data.periods.filter(function (p) { return p.n === e.period; })[0];
    var dl = h('dl', { class: 'v' }, [h('dt', { text: 'number' }), h('dd', { text: numLabel(e) }),
      h('dt', { text: 'state' }), h('dd', { class: 'pt-state', text: stateLabel(e) }),
      h('dt', { text: 'group' }), h('dd', { text: g.title }), h('dt', { text: 'period' }), h('dd', { text: per ? per.title : String(e.period) })]);
    if (e.analogy) {
      var why = data.rules[e.analogy[3]] || e.analogy[3];
      dl.appendChild(h('dt', { text: 'chemical analogy' }));
      dl.appendChild(h('dd', { text: 'like ' + e.analogy[2] + ' (' + e.analogy[1] + (e.analogy[0] ? ', Z=' + e.analogy[0] : '') + ')' + (why ? ': ' + why : '') }));
    }
    body.appendChild(dl);
    var shown = data.props.filter(function (p) { return e.props[p.key] != null; });
    var more = h('div', { class: 'pt-more' }, [h('p', { class: 'k', text: 'Loading values, evidence and files…' })]);
    body.appendChild(more);
    if (shown.length) {
      body.appendChild(h('h2', { text: 'Properties' }));
      body.appendChild(h('table', {}, [h('tbody', {}, shown.map(function (p) {
        return h('tr', {}, [h('th', { scope: 'row', text: p.label }), h('td', { text: String(e.props[p.key]) + (p.unit ? ' ' + p.unit : '') })]);
      }))]));
    }
    body.appendChild(h('p', {}, [h('a', { class: 'pt-tap', href: e.page, text: 'Open the page for ' + e.sym })]));
    showCard();
    if (push !== false) history.replaceState(null, '', location.pathname + location.search + '#' + encodeURIComponent(sym));
    loadCards().then(function (j) { fillMore(more, e, j); }, function () {
      more.textContent = ''; more.appendChild(h('p', { class: 'k' }, ['Card details could not be loaded here; ', h('a', { class: 'pt-tap', href: e.page, text: 'open the page for ' + e.sym }), '.']));
    });
  }
  function fillMore(more, e, j) {
    var c = j.elements[e.sym]; more.textContent = '';
    if (!c) return;
    if (c.values.length) {
      D.querySelector('.pt-state').textContent = stateLabel(e, c.values.length);
      more.appendChild(h('h2', { text: 'Unsettled values, side by side' }));
      more.appendChild(h('div', { class: 'pt-vals' }, c.values.map(function (v, i) {
        return h('div', { class: 'pt-val' }, [h('p', { class: 'k', text: 'form ' + (i + 1) + (v.count ? ' · ' + v.count + ' files' : '') }),
          h('p', { class: 'pt-v' }, [h('code', { text: v.value })]),
          v.evidence.length ? h('ul', { class: 'pt-ev' }, v.evidence.map(function (k) { return h('li', {}, [h('code', { text: k })]); })) : null]);
      })));
    }
    more.appendChild(h('h2', { text: 'Evidence keys' }));
    more.appendChild(c.evidence.length ? h('ul', { class: 'pt-ev' }, c.evidence.map(function (k) { return h('li', {}, [h('code', { text: k })]); }))
      : h('p', { class: 'k', text: 'No evidence key given for this element in the input.' }));
    more.appendChild(h('h2', { text: 'Files (' + c.files.length + ')' }));
    if (!c.files.length) { more.appendChild(h('p', { class: 'k', text: 'No Explore Code file is mapped to this element yet.' })); return; }
    var LIMIT = 40;
    more.appendChild(h('ul', { class: 'pt-files' }, c.files.slice(0, LIMIT).map(function (f) {
      var inner = [j.repos[f[1]] + '/' + f[2], h('span', { class: 'k', text: f[6] + ' · ' + f[5] + ' lines' })];
      return h('li', {}, [f[3] ? h('a', { class: 'pt-file', href: '../s/' + pad4(f[3]) + '.html#f' + (f[4] || 1) }, inner) : h('span', {}, inner)]);
    })));
    if (c.files.length > LIMIT) more.appendChild(h('p', {}, [h('a', { class: 'pt-tap', href: e.page, text: 'All ' + c.files.length + ' files on the page for ' + e.sym })]));
  }
  function closeCard() {
    card.hidden = true; D.body.classList.remove('pt-modal');
    if (location.hash) history.replaceState(null, '', location.pathname + location.search);
    if (lastFocus && lastFocus.focus) lastFocus.focus();
  }

  D.addEventListener('click', function (ev) {
    if (ev.metaKey || ev.ctrlKey || ev.shiftKey || !ev.target.closest) return;
    var a = ev.target.closest('a.pt-el[data-sym]');
    if (a) { ev.preventDefault(); openCard(a.getAttribute('data-sym')); return; }
    var z = ev.target.closest('button.pt-z[data-z]');
    if (z) openChem(Number(z.getAttribute('data-z')));
  });
  D.getElementById('pt-x').addEventListener('click', closeCard);
  card.addEventListener('click', function (ev) { if (ev.target === card) closeCard(); });
  D.addEventListener('keydown', function (ev) { if (ev.key === 'Escape' && !card.hidden) closeCard(); });
  if (sel) {
    try { var sv = localStorage.getItem('ec-pt:color'); if (sv && [].some.call(sel.options, function (o) { return o.value === sv; })) sel.value = sv; } catch (e) { /* off */ }
    sel.addEventListener('change', function () { paint(); try { localStorage.setItem('ec-pt:color', sel.value); } catch (e) { /* off */ } });
  }
  D.querySelectorAll('[data-view]').forEach(function (b) { b.addEventListener('click', function () { if (!b.disabled) setView(b.getAttribute('data-view')); }); });
  paint();

  // deep links: ?view=chem, #Sym, ?file=ID, ?sec=N (element badge / Periodic mode)
  var q = new URLSearchParams(location.search), target = null, cb = D.querySelector('[data-view=chem]');
  var v0 = q.get('view'); try { v0 = v0 || localStorage.getItem('ec-pt:view'); } catch (e) { /* off */ }
  if (v0 === 'chem' && cb && !cb.disabled) setView('chem');
  if (location.hash.length > 1) target = decodeURIComponent(location.hash.slice(1));
  function byFiles(test) {
    return loadCards().then(function (j) { return E.filter(function (e) { return (j.elements[e.sym] || { files: [] }).files.some(test); }); });
  }
  function mark(list) {
    list.forEach(function (e) { var t = estate.querySelector('.pt-el[data-sym="' + e.sym.replace(/"/g, '') + '"]'); if (t) t.classList.add('pt-hit'); });
    if (list[0]) { var t0 = estate.querySelector('.pt-el.pt-hit'); if (t0) t0.scrollIntoView({ block: 'nearest', inline: 'nearest' }); }
  }
  if (bySym[target]) openCard(target, false);
  else if (q.get('file')) {
    var fid = Number(q.get('file'));
    byFiles(function (f) { return f[0] === fid; }).then(function (l) { mark(l); if (l.length) openCard(l[0].sym, false); }, function () { /* no data */ });
  } else if (q.get('sec')) {
    var sec = Number(q.get('sec'));
    byFiles(function (f) { return f[3] === sec; }).then(function (l) { mark(l); if (l.length === 1) openCard(l[0].sym, false); }, function () { /* no data */ });
  }
})();

Props

A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, elements and periodic, using SHA-256. It loads ctx (`load_ctx`) and computes element (`compute_element`).

storagecosmic / tools/explore/periodic/props.py · lines 1–460 of 534 · Entry point · pattern evidence_key (shared by 2 files)

What it does
It loads build graph, identity, elements and periodic. Defines 28 functions or classes, including _read_json, stamp_time, masked, load_ctx, dev_ctx. Uses libraries collections, datetime, hashlib, json, math. Side effects: reads or writes files.
Inputs & outputs
In: JSON file build_graph.json; JSON file identity-files.json; JSON file elements.json; JSON file periodic.json; JSON file props.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: Extras (cosmic); Exp (cosmic); Test Props (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Measurable PROPERTIES of every code element (PHYSICIST, QUANTA-19). It accepts `--site`, `--graph` and `--periodic`.
Why it matters
Imported by Exp. Run by Extras. Checked by Test Props.
Application
cosmic · tools/explore/periodic · Python CLI
Uses
collections, datetime, hashlib, json, math, os, re, sys
Used by
run by Extras (script call), imported by Exp (sys.path import), imported by Test Props (import)
Produces
stamp_time, masked, load_ctx, dev_ctx, element_members, file_mass, file_valence, version_family, mass, valence, in_reach, electronegativity
Defines here
_read_json, stamp_time, masked, load_ctx, dev_ctx, _member_ids_from_periodic, element_members, file_mass, file_valence, version_family, mass, valence, in_reach, electronegativity, _rev_index, near_copies, relatives, isotopes, _median, half_life, stability, reactivity, spectrum, evidence_key, compute_element
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/props.py:1-460 · blob 77ab3670770b6dd5a8cf72f344230dae9c57c307 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""tools/explore/periodic/props.py - measurable PROPERTIES of every code element (PHYSICIST, QUANTA-19).

Every property is a deterministic formula over evidence already in the estate; nothing is guessed.
Inputs (read only):
  graph      Explore Code build_graph.json (files, edges, roles)          default /tmp/site8/explore-code/build_graph.json
  identity   identity-files.json (Elements blocks, verdicts, Vedic, twins) default /tmp/vk/7/identity-files.json
  catalogue  elements repo catalogue/elements.json (permanent block keys)  default /home/claude/src/elements/catalogue/elements.json
  periodic   MAPPER's periodic.json, used for membership when present      default /tmp/vk/periodic/periodic.json
  blobs      estate-blobs.tsv (every path at HEAD: older stamped versions)  default /tmp/vk/7/estate-blobs.tsv
Output: props.json (schema explore-periodic-props-v1).

CLI (build_graph alone is enough; every extra is an optional flag):
  python3 props.py --graph build_graph.json --out props.json
  python3 props.py --site _site/explore-code --periodic periodic.json [--identity F] [--blobs F] [--src clones]
  python3 props.py --dev   # team machine: all /tmp/vk inputs, writes /tmp/vk/periodic/props.json

Importable API (all pure functions of ctx; ids are build_graph file ids):
  load_ctx(...) -> ctx            element_members(ctx) -> [element dicts with 'members']
  mass(ctx, ids)                  valence(ctx, ids)            electronegativity(ctx, ids)
  isotopes(ctx, ids)              half_life(ctx, ids)          stability(ctx, ids, state=None)
  relatives(ctx, ids)  near_copies(ctx, ids)
  reactivity(ctx, ids)            spectrum(ctx, ids)           in_reach(ctx, ids)
  file_mass(ctx, i)  file_valence(ctx, i)  version_family(ctx, i)  stamp_time(path)
  compute_element(ctx, el)        compute_all(ctx)             PROPERTIES (formulas, also in EXPERIMENTS.md)
"""
import collections
import datetime
import hashlib
import json
import math
import os
import re
import sys

SCHEMA = 'explore-periodic-props-v1'
RULES = 'periodic-props-v1'
DEFAULTS = {
    'graph': '/tmp/site8/explore-code/build_graph.json',
    'identity': '/tmp/vk/7/identity-files.json',
    'catalogue': '/home/claude/src/elements/catalogue/elements.json',
    'periodic': '/tmp/vk/periodic/periodic.json',
    'blobs': '/tmp/vk/7/estate-blobs.tsv',
    'out': '/tmp/vk/periodic/props.json',
}
# Same stamp rule as build.py (paths equal once 20YYMMDD[hhmm] stamps are masked are one family).
STAMP = re.compile(r'(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)')
EXCLUDED_EDGE_KINDS = {'comment-url'}  # same exclusion as the lab: a URL in a comment is not a dependency
VEDIC_JACCARD = 0.5                     # Vedic cluster Jaccard for a near-copy isotope
VEDIC_MIN_CLUSTERS = 2

PROPERTIES = [
    {'key': 'mass', 'label': 'Mass', 'unit': 'lines',
     'formula': 'sum(lines) over member files'},
    {'key': 'valence', 'label': 'Valence', 'unit': 'count',
     'formula': '|resolved import targets outside the element  U  external import strings| + |distinct defined names (exports)|'},
    {'key': 'in_degree', 'label': 'Dependents', 'unit': 'files',
     'formula': 'distinct non-member files with a resolved edge (not comment-url) into a member'},
    {'key': 'reach', 'label': 'Reverse reach', 'unit': 'files',
     'formula': 'distinct non-member files that transitively depend on a member (reverse BFS over resolved edges)'},
    {'key': 'electronegativity', 'label': 'Electronegativity', 'unit': 'bits',
     'formula': '0.5*log2(1+in_degree) + 0.5*log2(1+reach)'},
    {'key': 'electronegativity_pauling', 'label': 'Electronegativity (0.7-4.0 scale)', 'unit': 'scaled',
     'formula': '0.7 + 3.3*electronegativity/max(electronegativity over all elements); 0.7 when nothing pulls'},
    {'key': 'isotopes', 'label': 'Isotopes', 'unit': 'count',
     'formula': 'near_copies + verbatim_copies + versions; near_copies = distinct non-member graph files with the same sha256 '
                'or an identity near-copy-of verdict (line Jaccard >= 0.8) either way; '
                'verbatim_copies = sum of identity verdict.estate_verbatim_copies (same bytes elsewhere in the estate); '
                'versions = other stamped paths in the estate whose stamp-masked path equals a member path and whose blob '
                'differs from the member (same-blob versions are already verbatim copies)'},
    {'key': 'relatives', 'label': 'Relatives (not isotopes)', 'unit': 'files',
     'formula': 'non-member graph files linked by a Quantum Twin or Vedic cluster Jaccard >= 0.5 (>= 2 clusters), minus near copies'},
    {'key': 'half_life_days', 'label': 'Half-life', 'unit': 'days',
     'formula': 'median gap in days between consecutive stamps in the members\' version families (null: no stamped versions)'},
    {'key': 'stability', 'label': 'Stability', 'unit': 'settled|unsettled',
     'formula': 'catalogue state when the element has one; else unsettled if any member has drift constants, '
                'duplication_disagree functions or >= 2 versions, otherwise settled'},
    {'key': 'reactivity', 'label': 'Reactivity', 'unit': 'edges',
     'formula': 'resolved edges (not comment-url) with one end in the element and the other end in a different repository'},
    {'key': 'spectrum', 'label': 'Spectrum', 'unit': 'shares',
     'formula': 'share of member files in each build_graph role, in the graph\'s role order (12 lines)'},
]


# ------------------------------------------------------------------ loading
def _read_json(path):
    with open(path, encoding='utf-8') as fh:
        return json.load(fh)


def stamp_time(path):
    """Latest 20YYMMDD[hhmm[ss]] stamp in a path as a datetime (UTC), or None."""
    best = None
    for m in STAMP.finditer(path):
        s = m.group(1).replace('T', '').replace('Z', '')
        try:
            d = datetime.datetime.strptime(s[:8], '%Y%m%d')
        except ValueError:
            continue
        rest = s[8:]
        if len(rest) >= 4:
            hh, mm = int(rest[:2]), int(rest[2:4])
            if hh < 24 and mm < 60:
                d = d.replace(hour=hh, minute=mm)
        if best is None or d > best:
            best = d
    return best


def masked(path):
    return STAMP.sub('#', path)


def load_ctx(graph=None, identity=None, catalogue=None, periodic=None, blobs=None, g=None, ident=None):
    """Load everything once. g / ident may be passed already parsed (tests, furnace)."""
    graph = graph or DEFAULTS['graph']
    g = g if g is not None else _read_json(graph)
    ctx = {'graph_path': graph, 'graph_cut': g.get('cut'), 'files': g['files'], 'roles': [r['id'] for r in g['roles']],
           'repo_commit': {r['repo']: r['commit'] for r in g['repos']}}
    n = len(g['files'])
    out_adj = [set() for _ in range(n)]
    in_adj = [set() for _ in range(n)]
    edges = []
    for e in g['edges']:
        a, b, kind = e[0], e[1], e[2]
        if kind in EXCLUDED_EDGE_KINDS or a == b:
            continue
        edges.append((a, b, kind))
        out_adj[a].add(b)
        in_adj[b].add(a)
    ctx.update(edges=edges, out_adj=out_adj, in_adj=in_adj)
    ctx['by_repo_path'] = {(f['repo'], f['path']): f['id'] for f in g['files']}

    ipath = identity
    if ident is None and ipath and os.path.exists(ipath):
        ident = _read_json(ipath)
    idf = {}
    if ident:
        for k, v in ident['files'].items():
            idf[int(k)] = v
    ctx['identity'] = idf
    ctx['identity_graph_sha'] = (ident or {}).get('graph', {}).get('sha256')
    # sha256 index and Vedic cluster index
    by_sha = collections.defaultdict(list)
    by_cluster = collections.defaultdict(list)
    for i, v in idf.items():
        sha = v.get('keys', {}).get('sha256')
        if sha:
            by_sha[sha].append(i)
        for c in v.get('vedic', {}).get('clusters', []):
            by_cluster[c].append(i)
    ctx['by_sha'] = by_sha
    ctx['by_cluster'] = by_cluster

    cpath = catalogue
    ctx['catalogue'] = _read_json(cpath) if cpath and os.path.exists(cpath) else []
    ppath = periodic
    ctx['periodic'] = _read_json(ppath) if ppath and os.path.exists(ppath) else None
    ctx['periodic_path'] = ppath if ctx['periodic'] else None

    bpath = blobs
    fam = collections.defaultdict(list)
    if bpath and os.path.exists(bpath):
        with open(bpath, encoding='utf-8') as fh:
            for line in fh:
                parts = line.rstrip('\n').split('\t')
                if len(parts) != 3:
                    continue
                blob, repo, path = parts
                if STAMP.search(path):
                    fam[(repo, masked(path))].append((path, blob))
    ctx['stamp_families'] = fam
    ctx['_reach_cache'] = {}
    ctx['inputs'] = {'graph': graph, 'identity': ipath if idf else None, 'catalogue': cpath if ctx['catalogue'] else None,
                     'periodic': ctx['periodic_path'], 'blobs': bpath if fam else None}
    return ctx


def dev_ctx():
    """The team's local inputs (DEFAULTS); for experiments and tests on the dev machine only."""
    return load_ctx(**{k: (v if os.path.exists(v) else None) for k, v in DEFAULTS.items() if k != 'out'})


# ------------------------------------------------------------------ membership
def _member_ids_from_periodic(ctx, el):
    ids = set()
    for f in el.get('files') or []:
        if isinstance(f, int):
            ids.add(f)
        elif isinstance(f, dict) and isinstance(f.get('id'), int):
            ids.add(f['id'])
        elif isinstance(f, dict) and isinstance(f.get('file_id'), int):
            ids.add(f['file_id'])
    return ids


def element_members(ctx):
    """[{symbol, number, key, name, category, state, source, members:[ids]}], ordered by number then symbol."""
    out = []
    if ctx['periodic'] and isinstance(ctx['periodic'].get('elements'), list):
        for el in ctx['periodic']['elements']:
            sym = el.get('symbol') or el.get('proposed_symbol') or el.get('key')
            if not sym:
                continue
            out.append({'symbol': sym, 'number': el.get('number'), 'key': el.get('key') or 'block:%s' % sym,
                        'name': el.get('title') or el.get('name') or sym,
                        'category': el.get('category') or el.get('star_family') or el.get('group'),
                        'state': (el.get('state') or '').upper() or None,
                        'analogy': el.get('analogue') or el.get('analogy') or el.get('like'),
                        'status': el.get('status') or ('numbered' if el.get('number') is not None else 'candidate'),
                        'period': el.get('period'), 'group': el.get('group'),
                        'source': 'periodic.json', 'members': sorted(_member_ids_from_periodic(ctx, el))})
    elif not ctx['catalogue'] and not ctx['identity']:
        groups = collections.defaultdict(list)
        for f in ctx['files']:
            groups[(f['repo'], f['role'])].append(f['id'])
        for (repo, role), ids in sorted(groups.items()):
            k = 'graph:%s:%s' % (repo, role)
            out.append({'symbol': k, 'number': None, 'key': k, 'name': '%s %s files' % (repo, role), 'category': role,
                        'state': None, 'analogy': None, 'status': 'candidate', 'period': None, 'group': role,
                        'source': 'build_graph repo x role (no periodic.json given)', 'members': sorted(ids)})
    else:
        block_files = collections.defaultdict(set)
        for i, v in ctx['identity'].items():
            for b in v.get('elements', {}).get('blocks', []):
                block_files[b].add(i)
        for el in ctx['catalogue']:
            ids = set(block_files.get(el['key'], ()))
            for f in el.get('files') or []:
                repo = f.get('repo', '').split('/')[-1]
                i = ctx['by_repo_path'].get((repo, f.get('path')))
                if i is not None:
                    ids.add(i)
            out.append({'symbol': el['symbol'], 'number': el.get('number'), 'key': el['key'], 'name': el.get('title'),
                        'category': el.get('category'), 'state': el.get('state'), 'analogy': None,
                        'status': 'numbered', 'period': None, 'group': None,
                        'source': 'elements/catalogue/elements.json + identity blocks', 'members': sorted(ids)})
    out.sort(key=lambda e: (e['number'] is None, e['number'] or 0, e['symbol']))
    return out


# ------------------------------------------------------------------ file-level
def file_mass(ctx, i):
    return int(ctx['files'][i].get('lines') or 0)


def file_valence(ctx, i):
    f = ctx['files'][i]
    return len(set(f.get('imports') or []) | set(f.get('imports_external') or [])) + len(set(f.get('defines') or []))


def version_family(ctx, i):
    """Stamped versions of file i in the estate: [(datetime, path, blob)] oldest first; [] when unstamped."""
    f = ctx['files'][i]
    if not STAMP.search(f['path']):
        return []
    rows = ctx['stamp_families'].get((f['repo'], masked(f['path'])), [])
    out = []
    for path, blob in rows:
        t = stamp_time(path)
        if t is not None:
            out.append((t, path, blob))
    if not any(p == f['path'] for _, p, _ in out):
        t = stamp_time(f['path'])
        if t is not None:
            out.append((t, f['path'], None))
    out.sort()
    return out


# ------------------------------------------------------------------ element properties
def mass(ctx, ids):
    return sum(file_mass(ctx, i) for i in ids)


def valence(ctx, ids):
    ids = set(ids)
    imp, defs = set(), set()
    for i in ids:
        f = ctx['files'][i]
        imp.update(('f', t) for t in (f.get('imports') or []) if t not in ids)
        imp.update(('x', s) for s in (f.get('imports_external') or []))
        defs.update(f.get('defines') or [])
    return len(imp) + len(defs)


def in_reach(ctx, ids):
    """(in_degree, reach): direct and transitive non-member dependents."""
    ids = frozenset(ids)
    key = ids
    if key in ctx['_reach_cache']:
        return ctx['_reach_cache'][key]
    in_adj = ctx['in_adj']
    direct = set()
    for i in ids:
        direct |= in_adj[i]
    direct -= ids
    seen = set(ids)
    stack = list(ids)
    while stack:
        x = stack.pop()
        for y in in_adj[x]:
            if y not in seen:
                seen.add(y)
                stack.append(y)
    res = (len(direct), len(seen - ids))
    ctx['_reach_cache'][key] = res
    return res


def electronegativity(ctx, ids):
    d, r = in_reach(ctx, ids)
    return round(0.5 * math.log2(1 + d) + 0.5 * math.log2(1 + r), 4)


def _rev_index(ctx):
    rev = ctx.get('_rev')
    if rev is None:
        rev = {'near': collections.defaultdict(set), 'twin': collections.defaultdict(set)}
        for j, v in ctx['identity'].items():
            vd = v.get('verdict', {})
            if vd.get('verdict') == 'near-copy-of' and isinstance(vd.get('of_file'), int):
                rev['near'][vd['of_file']].add(j)
            tw = (v.get('quantum') or {}).get('twin') or {}
            if isinstance(tw.get('file'), int):
                rev['twin'][tw['file']].add(j)
        ctx['_rev'] = rev
    return rev


def near_copies(ctx, ids):
    """Non-member graph files that are near-copies of a member: same sha256, or an identity near-copy-of verdict
    (line Jaccard >= 0.8) in either direction."""
    ids = set(ids)
    out = set()
    rev = _rev_index(ctx)
    for i in ids:
        v = ctx['identity'].get(i)
        if not v:
            continue
        sha = v.get('keys', {}).get('sha256')
        if sha:
            out.update(ctx['by_sha'].get(sha, ()))
        vd = v.get('verdict', {})
        if vd.get('verdict') == 'near-copy-of' and isinstance(vd.get('of_file'), int):
            out.add(vd['of_file'])
        out |= rev['near'].get(i, set())
    return out - ids


def relatives(ctx, ids):
    """Looser kin, reported but NOT counted as isotopes: Quantum Twin links and Vedic cluster Jaccard >= 0.5
    (>= 2 clusters each). The isotope experiment showed these over-flag (precision 0.31 vs families.json)."""
    ids = set(ids)
    idf = ctx['identity']
    rev = _rev_index(ctx)
    out = set()
    for i in ids:
        v = idf.get(i)
        if not v:
            continue
        tw = (v.get('quantum') or {}).get('twin') or {}
        if isinstance(tw.get('file'), int):
            out.add(tw['file'])
        out |= rev['twin'].get(i, set())
        cl = set(v.get('vedic', {}).get('clusters', []))
        if len(cl) >= VEDIC_MIN_CLUSTERS:
            cand = collections.Counter()
            for c in cl:
                for j in ctx['by_cluster'].get(c, ()):
                    cand[j] += 1
            for j, shared in cand.items():
                if j == i:
                    continue
                other = set(idf[j].get('vedic', {}).get('clusters', []))
                if len(other) >= VEDIC_MIN_CLUSTERS and shared / len(cl | other) >= VEDIC_JACCARD:
                    out.add(j)
    return out - ids


def isotopes(ctx, ids):
    """{'isotopes', 'near_copies', 'verbatim_copies', 'versions', 'near_copy_ids'}."""
    nc = near_copies(ctx, ids)
    verb = sum(int((ctx['identity'].get(i) or {}).get('verdict', {}).get('estate_verbatim_copies') or 0) for i in ids)
    vers = 0
    for i in ids:
        own = (ctx['identity'].get(i) or {}).get('keys', {}).get('git_blob')
        vers += sum(1 for _, p, b in version_family(ctx, i) if p != ctx['files'][i]['path'] and b != own)
    return {'isotopes': len(nc) + verb + vers, 'near_copies': len(nc), 'verbatim_copies': verb, 'versions': vers,
            'near_copy_ids': sorted(nc), 'relatives': len(relatives(ctx, ids) - nc)}


def _median(xs):
    xs = sorted(xs)
    if not xs:
        return None
    m = len(xs) // 2
    return xs[m] if len(xs) % 2 else (xs[m - 1] + xs[m]) / 2


def half_life(ctx, ids):
    gaps = []
    for i in ids:
        fam = version_family(ctx, i)
        ts = sorted({t for t, _, _ in fam})
        gaps.extend((b - a).total_seconds() / 86400 for a, b in zip(ts, ts[1:]))
    m = _median(gaps)
    return None if m is None else round(m, 3)


def stability(ctx, ids, state=None):
    """('settled'|'unsettled', basis)."""
    if state in ('SETTLED', 'UNSETTLED'):
        return state.lower(), 'catalogue state'
    for i in ids:
        gen = (ctx['identity'].get(i) or {}).get('genome', {})
        if gen.get('drift_constants'):
            return 'unsettled', 'drift constants in file %d' % i
        if gen.get('duplication_disagree'):
            return 'unsettled', 'functions disagree with their copies in file %d' % i
        if len(version_family(ctx, i)) >= 2:
            return 'unsettled', 'stamped versions of file %d' % i
    return 'settled', 'no drift, no disagreeing copies, no versions'


def reactivity(ctx, ids):
    ids = set(ids)
    files = ctx['files']
    n = 0
    for a, b, _ in ctx['edges']:
        ia, ib = a in ids, b in ids
        if ia != ib:
            m, o = (a, b) if ia else (b, a)
            if files[m]['repo'] != files[o]['repo']:
                n += 1
    return n


def spectrum(ctx, ids):
    c = collections.Counter(ctx['files'][i]['role'] for i in ids)
    tot = sum(c.values())
    return [round(c[r] / tot, 4) if tot else 0.0 for r in ctx['roles']]


def evidence_key(ctx, i):
    v = ctx['identity'].get(i)
    if v and v.get('keys', {}).get('key'):
        return v['keys']['key']
    f = ctx['files'][i]
    return '%s@%s %s:1-%d' % (f['repo'], ctx['repo_commit'].get(f['repo'], '?'), f['path'], f.get('lines') or 0)


def compute_element(ctx, el):
    ids = el['members']
    d, r = in_reach(ctx, ids)
    iso = isotopes(ctx, ids)
    st, basis = stability(ctx, ids, el.get('state'))
    spec = spectrum(ctx, ids)
    return {
        'symbol': el['symbol'], 'number': el['number'], 'key': el['key'], 'name': el['name'],