GLOBALGRID2050 / EXPLORE CODE

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

Exp

A Python command-line tool in the experiments folder of Cosmic that draws families and metrics, using Louvain. It writes page (`write_page`) and matches acc (`match_acc`).

700 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1109 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. Exp render · cosmic / tools/explore/periodic/experiments/exp.py lines 1–700

Exp

A Python command-line tool in the experiments folder of Cosmic that draws families and metrics, using Louvain. It writes page (`write_page`) and matches acc (`match_acc`).

rendercosmic / tools/explore/periodic/experiments/exp.py · lines 1–700 of 760 · Entry point · pattern modularity (shared by 2 files)

What it does
It draws families and metrics. Defines 29 functions or classes, including rnd, quantile, spearman, ranks, table. Uses libraries collections, hashlib, html, json, math. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file families.json; JSON file metrics.json; command-line arguments. Out: JSON file; canvas drawing.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Five code visualisation experiments driven by element properties. It accepts `--out`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/periodic/experiments · Python CLI
Uses
Props (sys.path import), collections, hashlib, html, json, math, os, random, sys
Used by
none found
Produces
rnd, quantile, spearman, table, write_page, modularity, element_bonds, louvain, exp_reactions, chain_drift, exp_decay, exp_isotopes
Defines here
rnd, quantile, spearman, ranks, table, write_page, modularity, element_bonds, louvain, exp_reactions, _lines, chain_drift, exp_decay, exp_isotopes, crosses, real_layout, add, mapper_axes_test, eta, exp_periodicity, ratio, acf, exp_barcode, spec, js_div, kl, match_acc
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/experiments/exp.py:1-700 · blob 51047570db3c32e17c20e77100306ee6808a9282 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
#!/usr/bin/env python3
"""tools/explore/periodic/experiments/exp.py - five code visualisation experiments driven by element properties.

Each experiment writes one self-contained offline canvas page into --out (default /tmp/vk/periodic/experiments/)
and computes a metric with fixed thresholds that says whether the picture shows something TRUE (an independent
check agrees) and USEFUL (it separates things a reader cares about). Verdicts come from verdict rules below, not
from judgement. Also writes metrics.json, index.html and (with --md) EXPERIMENTS.md.

  python3 experiments/exp.py [--out DIR] [--md PATH]
"""
import collections
import hashlib
import html
import json
import math
import os
import random
import sys

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

SEED = 20261205
ETA_FLOOR = 0.10  # a column must explain >= 10% of a property's variance to count as a periodic law
FAMILIES = '/tmp/vk/clean/families.json'
# Categorical palette (dataviz reference, dark steps; validated on #0b0e14: all checks pass). 8 slots + Other grey.
SERIES = ['#338ced', '#e76624', '#00a888', '#d28e05', '#e24d8b', '#0aac23', '#9887ef', '#eb6263']
OTHER = '#5c6370'
ROLE_GROUPS = [('domain', ['geodesy', 'electrical', 'energy-data']), ('ingest', ['ingest']), ('transform', ['transform']),
               ('render', ['render']), ('interaction', ['interaction']), ('storage', ['storage']), ('test', ['test']),
               ('automation', ['automation']), ('other', ['docs-config', 'other'])]


def rnd(x, k=4):
    return None if x is None else round(float(x), k)


def quantile(xs, q):
    xs = sorted(xs)
    if not xs:
        return None
    k = (len(xs) - 1) * q
    lo, hi = int(math.floor(k)), int(math.ceil(k))
    return xs[lo] + (xs[hi] - xs[lo]) * (k - lo)


def spearman(a, b):
    def ranks(v):
        o = sorted(range(len(v)), key=lambda i: v[i])
        r = [0.0] * len(v)
        i = 0
        while i < len(o):
            j = i
            while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]:
                j += 1
            for k in range(i, j + 1):
                r[o[k]] = (i + j) / 2
            i = j + 1
        return r
    ra, rb = ranks(a), ranks(b)
    n = len(a)
    ma, mb = sum(ra) / n, sum(rb) / n
    cov = sum((x - ma) * (y - mb) for x, y in zip(ra, rb))
    va = math.sqrt(sum((x - ma) ** 2 for x in ra))
    vb = math.sqrt(sum((y - mb) ** 2 for y in rb))
    return cov / (va * vb) if va and vb else 0.0


# ------------------------------------------------------------------ page shell
SHELL = r'''<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="data:,">
<title>%(title)s - periodic experiment</title>
<style>
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--text:#fff;--muted:#a6adbb;--accent:#66ccff;--hi:#00ffff}
*{box-sizing:border-box}html,body{margin:0;background:var(--bg);color:var(--text);font:15px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
main{max-width:1100px;margin:0 auto;padding:12px}
h1{font-size:1.2rem;margin:.2rem 0}a{color:var(--accent)}
p{color:var(--muted);margin:.4rem 0}
.verdict{display:inline-block;border:1px solid var(--line);border-radius:6px;padding:2px 8px;margin:4px 0;background:var(--panel);color:var(--text)}
.verdict b{color:var(--hi)}
.wrap{position:relative;background:var(--panel);border:1px solid var(--line);border-radius:8px;margin:10px 0;touch-action:pan-y}
canvas{display:block;width:100%%}
#tip{position:absolute;pointer-events:none;background:#000;border:1px solid var(--line);border-radius:6px;padding:6px 8px;font-size:13px;max-width:260px;display:none;z-index:2;color:var(--text)}
.legend{display:flex;flex-wrap:wrap;gap:6px 12px;font-size:13px;color:var(--muted);margin:6px 0}
.legend i{display:inline-block;width:12px;height:12px;border-radius:3px;margin-right:4px;vertical-align:-2px}
.ctl{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
button{background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:6px;padding:8px 12px;font:inherit;min-height:40px}
button[aria-pressed=true]{border-color:var(--hi);color:var(--hi)}
details{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px;margin:10px 0}
summary{cursor:pointer;color:var(--accent)}
table{border-collapse:collapse;font-size:12px;width:100%%}td,th{border-bottom:1px solid var(--line);padding:3px 4px;text-align:left;color:var(--muted)}
.tw{overflow-x:auto;max-height:340px;overflow-y:auto}
code{color:var(--hi);font-size:12px}
</style></head><body><main>
<p><a href="index.html">All experiments</a> &middot; QUANTA-19 periodic PHYSICIST</p>
<h1>%(title)s</h1>
<p>%(question)s</p>
<div class="verdict">Verdict: <b>%(verdict)s</b> &middot; %(basis)s</div>
%(controls)s
<div class="legend" id="legend"></div>
<div class="wrap" id="wrap"><canvas id="cv" role="img" aria-label="%(title)s"></canvas><div id="tip"></div></div>
<p>%(read)s</p>
<details><summary>Table view</summary><div class="tw">%(table)s</div></details>
<details><summary>How it was measured</summary><p>%(method)s</p><p>Graph cut <code>%(cut)s</code>. Source: <code>tools/explore/periodic/experiments/exp.py</code>, properties from <code>props.py</code> (rules %(rules)s).</p></details>
</main>
<script>
const DATA=%(data)s;
const SER=%(series)s, OTHER="%(other)s";
const cv=document.getElementById('cv'),ctx=cv.getContext('2d'),tip=document.getElementById('tip'),wrap=document.getElementById('wrap');
let W=0,H=0,HITS=[];
function legend(items){document.getElementById('legend').innerHTML=items.map(([c,t])=>'<span><i style="background:'+c+'"></i>'+t+'</span>').join('')}
function size(h){const r=window.devicePixelRatio||1;W=wrap.clientWidth;H=h(W);cv.width=Math.round(W*r);cv.height=Math.round(H*r);cv.style.height=H+'px';ctx.setTransform(r,0,0,r,0,0);ctx.clearRect(0,0,W,H)}
function esc(s){return String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]))}
function hit(x,y){let best=null,bd=1e9;for(const h of HITS){let d;if(h.w!==undefined){d=(x>=h.x&&x<=h.x+h.w&&y>=h.y&&y<=h.y+h.h)?0:1e9}else{d=Math.hypot(x-h.x,y-h.y);if(d>Math.max(h.r,10))d=1e9}if(d<bd){bd=d;best=h}}return best}
function show(e){const b=cv.getBoundingClientRect(),x=e.clientX-b.left,y=e.clientY-b.top,h=hit(x,y);if(!h){tip.style.display='none';return}tip.innerHTML=h.t;tip.style.display='block';const tw=tip.offsetWidth;tip.style.left=Math.max(0,Math.min(W-tw,x+12))+'px';tip.style.top=(y+14)+'px'}
cv.addEventListener('pointermove',show);cv.addEventListener('pointerdown',show);cv.addEventListener('pointerleave',()=>{tip.style.display='none'});
%(js)s
let rt;window.addEventListener('resize',()=>{clearTimeout(rt);rt=setTimeout(draw,120)});draw();
</script></body></html>
'''


def table(head, rows):
    h = '<table><thead><tr>%s</tr></thead><tbody>' % ''.join('<th>%s</th>' % html.escape(str(x)) for x in head)
    for r in rows:
        h += '<tr>%s</tr>' % ''.join('<td>%s</td>' % html.escape('' if x is None else str(x)) for x in r)
    return h + '</tbody></table>'


def write_page(out, name, title, question, res, read, method, data, js, table_html, ctx, controls=''):
    page = SHELL % {
        'title': html.escape(title), 'question': html.escape(question), 'verdict': html.escape(res['verdict']),
        'basis': html.escape(res['basis']), 'controls': controls, 'read': html.escape(read), 'method': html.escape(method),
        'table': table_html, 'cut': html.escape(str(ctx['graph_cut'])), 'rules': props.RULES,
        'data': json.dumps(data, separators=(',', ':'), sort_keys=True).replace('</', '<\\/'),
        'series': json.dumps(SERIES), 'other': OTHER, 'js': js}
    path = os.path.join(out, name)
    with open(path, 'w', encoding='utf-8') as fh:
        fh.write(page)
    return path


# ------------------------------------------------------------------ 1 reactions / molecules
def modularity(adj, part, m2):
    """adj: {u:{v:w}}, part: {u:c}, m2 = 2*total weight."""
    if not m2:
        return 0.0
    deg = {u: sum(nb.values()) for u, nb in adj.items()}
    inside = collections.Counter()
    dsum = collections.Counter()
    for u, nb in adj.items():
        dsum[part[u]] += deg[u]
        for v, w in nb.items():
            if part[u] == part[v]:
                inside[part[u]] += w
    return sum(inside[c] / m2 - (dsum[c] / m2) ** 2 for c in dsum)


def element_bonds(ctx, members_by_sym):
    f2e = collections.defaultdict(set)
    for s, ids in members_by_sym.items():
        for i in ids:
            f2e[i].add(s)
    w = collections.Counter()
    for a, b, _ in ctx['edges']:
        for ea in f2e.get(a, ()):
            for eb in f2e.get(b, ()):
                if ea != eb:
                    w[tuple(sorted((ea, eb)))] += 1
    return w


def louvain(bonds, nodes, seed):
    import networkx as nx
    G = nx.Graph()
    G.add_nodes_from(sorted(nodes))
    for (a, b), x in sorted(bonds.items()):
        G.add_edge(a, b, weight=x)
    comms = nx.community.louvain_communities(G, weight='weight', seed=seed, resolution=1.0)
    comms = sorted((sorted(c) for c in comms), key=lambda c: (-len(c), c[0]))
    part = {s: k for k, c in enumerate(comms) for s in c}
    adj = {u: {v: d['weight'] for v, d in G[u].items()} for u in G}
    return comms, part, adj, 2 * sum(bonds.values()), G


def exp_reactions(ctx, P, out):
    import networkx as nx
    els = [e for e in P['elements'].values() if e['members']]
    mem = {e['symbol']: e['file_ids'] for e in els}
    bonds = element_bonds(ctx, mem)
    bonded = {s for k in bonds for s in k}
    comms, part, adj, m2, G = louvain(bonds, bonded, SEED)
    q = modularity(adj, part, m2)
    grp = lambda s: P['elements'][s].get('group') or P['elements'][s]['dominant_role'] or '?'
    cat_part = {s: grp(s) for s in bonded}
    q_cat = modularity(adj, cat_part, m2)
    # null: same element sizes, member files drawn at random from the member pool (seeded), Louvain again
    pool = sorted({i for ids in mem.values() for i in ids})
    rng = random.Random(SEED)
    nullq = []
    for t in range(20):
        sh = {s: rng.sample(pool, len(ids)) for s, ids in sorted(mem.items())}
        b2 = element_bonds(ctx, sh)
        n2 = {s for k in b2 for s in k}
        if not b2:
            continue
        c2, p2, a2, mm2, _ = louvain(b2, n2, SEED + t)
        nullq.append(modularity(a2, p2, mm2))
    null95 = quantile(nullq, 0.95)
    big = [c for c in comms if len(c) >= 3]
    cross = sum(1 for c in big if len({grp(s) for s in c}) > 1)
    if q >= null95 + 0.05 and len(big) >= 3:
        verdict = 'reveals'
    elif q > null95:
        verdict = 'marginal'
    else:
        verdict = 'no'
    res = {'verdict': verdict, 'basis': 'molecule modularity Q %.3f vs shuffled-membership null p95 %.3f (table-column partition %.3f); %d molecules of 3+ elements, %d mix table columns'
           % (q, null95, q_cat, len(big), cross),
           'Q': rnd(q), 'Q_null_p95': rnd(null95), 'Q_null_mean': rnd(sum(nullq) / len(nullq)), 'Q_column': rnd(q_cat),
           'bonded_elements': len(bonded), 'bonds': len(bonds), 'molecules_3plus': len(big), 'cross_category_molecules': cross}
    pos = nx.spring_layout(G, weight='weight', seed=SEED, iterations=150, k=1.6 / math.sqrt(max(1, len(G))))
    molecules = []
    for k, c in enumerate(comms[:12]):
        catc = collections.Counter(P['elements'][s].get('group') or P['elements'][s]['dominant_role'] for s in c)
        top = sorted(c, key=lambda s: -P['elements'][s]['mass'])[:4]
        molecules.append({'k': k, 'size': len(c), 'category': catc.most_common(1)[0][0], 'top': top,
                          'mass': sum(P['elements'][s]['mass'] for s in c)})
    res['molecules'] = molecules[:8]
    nodes = []
    for s in sorted(bonded):
        e = P['elements'][s]
        x, y = pos[s]
        nodes.append({'s': s, 'n': e['name'], 'x': rnd(x, 3), 'y': rnd(y, 3), 'm': part[s], 'mass': e['mass'],
                      'chi': e['electronegativity_pauling'], 'val': e['valence'], 'rx': e['reactivity'], 'cat': grp(s)})
    links = [[a, b, x] for (a, b), x in sorted(bonds.items())]
    js = r'''
function draw(){size(w=>Math.min(Math.max(w*0.95,360),720));const pad=20;
let xs=DATA.nodes.map(n=>n.x),ys=DATA.nodes.map(n=>n.y);const x0=Math.min(...xs),x1=Math.max(...xs),y0=Math.min(...ys),y1=Math.max(...ys);
const sx=v=>pad+(v-x0)/(x1-x0||1)*(W-2*pad),sy=v=>pad+(v-y0)/(y1-y0||1)*(H-2*pad);const P={};DATA.nodes.forEach(n=>P[n.s]=n);
const col=m=>m<7?SER[m]:OTHER;ctx.lineCap='round';
for(const [a,b,w] of DATA.links){const A=P[a],B=P[b];ctx.strokeStyle=A.m===B.m?col(A.m):'#2f343d';ctx.globalAlpha=A.m===B.m?0.55:0.35;ctx.lineWidth=Math.min(4,0.6+Math.log2(1+w)*0.5);ctx.beginPath();ctx.moveTo(sx(A.x),sy(A.y));ctx.lineTo(sx(B.x),sy(B.y));ctx.stroke()}
ctx.globalAlpha=1;HITS=[];
for(const n of DATA.nodes){const r=2.5+Math.sqrt(n.mass)/18;const x=sx(n.x),y=sy(n.y);ctx.fillStyle=col(n.m);ctx.strokeStyle='#0b0e14';ctx.lineWidth=2;ctx.beginPath();ctx.arc(x,y,Math.min(r,16),0,7);ctx.fill();ctx.stroke();
HITS.push({x,y,r:Math.min(r,16)+4,t:'<b>'+esc(n.s)+'</b> '+esc(n.n)+'<br>molecule '+(n.m+1)+' &middot; '+esc(n.cat)+'<br>mass '+n.mass+' lines &middot; valence '+n.val+'<br>electronegativity '+n.chi+' &middot; reactivity '+n.rx})}
ctx.fillStyle='#fff';ctx.font='11px system-ui';for(const n of DATA.nodes){if(n.mass>4000)ctx.fillText(n.s,sx(n.x)+6,sy(n.y)-6)}}
legend(DATA.molecules.slice(0,7).map((m,i)=>[SER[i],'molecule '+(i+1)+': '+m.top.join(' ')+' ('+m.size+')']).concat([[OTHER,'smaller molecules']]));
'''
    rows = [[m['k'] + 1, m['size'], m['category'], ' '.join(m['top']), m['mass']] for m in molecules]
    write_page(out, 'reactions.html', 'Reactions: elements bond into molecules',
               'Do code elements that reference each other form molecules (tight groups) that a reader would not get from the table\'s columns (roles)?',
               res, 'Each dot is an element (size = mass in lines). A line is a bond: resolved references between member files of two elements; thicker = more references. Colour = molecule (Louvain community).',
               'Bond weight = resolved edges (comment-url excluded) between member files of two different elements. Molecules = Louvain (networkx, resolution 1, seed %d). Null = 20 runs with each element keeping its size but drawing members at random from the pooled member files. Verdict reveals if Q >= null p95 + 0.05 and >= 3 molecules of 3+ elements; marginal if Q > null p95.' % SEED,
               {'nodes': nodes, 'links': links, 'molecules': molecules}, js,
               table(['molecule', 'elements', 'main column', 'heaviest elements', 'mass'], rows), ctx)
    return res


# ------------------------------------------------------------------ 2 decay chains
SRC = '/home/claude/src'


def _lines(repo, path):
    try:
        with open(os.path.join(SRC, repo, path), encoding='utf-8', errors='replace') as fh:
            return {l.strip() for l in fh if l.strip()}
    except OSError:
        return None


def chain_drift(ctx, chains):
    seen = set()
    rhos = []
    for c in chains:
        f = ctx['files'][c['i']]
        fam = props.version_family(ctx, c['i'])
        key = (f['repo'], props.masked(f['path']))
        if key in seen or not 3 <= len(fam) <= 60:
            continue
        seen.add(key)
        newest = fam[-1]
        ref = _lines(f['repo'], newest[1])
        if not ref:
            continue
        ts, sims = [], []
        for t, p, _ in fam[:-1]:
            ls = _lines(f['repo'], p)
            if ls is None:
                continue
            ts.append(t.timestamp())
            sims.append(len(ls & ref) / (len(ls | ref) or 1))
        if len(sims) < 2 or len(set(sims)) < 2 or len(set(ts)) < 2:
            continue
        rhos.append(spearman(ts, sims))
    return {'testable': len(rhos), 'ordered_share': (sum(1 for r in rhos if r > 0) / len(rhos)) if rhos else 0,
            'mean_rho': (sum(rhos) / len(rhos)) if rhos else 0}


def exp_decay(ctx, P, out):
    chains = []
    kept_newest = 0
    total = 0
    for e in P['elements'].values():
        for i in e['file_ids']:
            fam = props.version_family(ctx, i)
            ts = sorted({t for t, _, _ in fam})
            if len(ts) < 2:
                continue
            total += 1
            own = props.stamp_time(ctx['files'][i]['path'])
            if own == ts[-1]:
                kept_newest += 1
            chains.append({'s': e['symbol'], 'i': i, 'path': ctx['files'][i]['path'], 'repo': ctx['files'][i]['repo'],
                           'ts': ts, 'own': own})
    per_el = collections.defaultdict(list)
    for c in chains:
        per_el[c['s']].append(c)
    drift = chain_drift(ctx, chains)
    true_share = drift['ordered_share']
    hl = {s: P['elements'][s]['half_life_days'] for s in per_el if P['elements'][s]['half_life_days'] is not None}
    vals = sorted(v for v in hl.values() if v > 0)
    p10, p90 = quantile(vals, 0.1), quantile(vals, 0.9)
    spread = (p90 / p10) if p10 else None
    kept_share = kept_newest / total if total else 0
    # stability link: are unsettled elements faster-decaying? (median half-life by stability)
    by_st = collections.defaultdict(list)
    for s, v in hl.items():
        by_st[P['elements'][s]['stability']].append(v)
    if true_share >= 0.7 and len(per_el) >= 10 and spread and spread >= 10:
        verdict = 'reveals'
    elif true_share >= 0.7 and len(per_el) >= 10:
        verdict = 'marginal'
    else:
        verdict = 'no'
    res = {'verdict': verdict,
           'basis': '%d member files in %d elements have stamped version chains; in %.0f%% of %d testable chains older stamps are less like the newest version (truth check, content read from disk); element half-life p10 %.3f d, p90 %.3f d (spread %.0fx)'
           % (total, len(per_el), 100 * true_share, drift['testable'], p10 or 0, p90 or 0, spread or 0),
           'chains': total, 'elements_with_chains': len(per_el), 'kept_is_newest_share': rnd(kept_share),
           'drift_testable_chains': drift['testable'], 'drift_ordered_share': rnd(true_share),
           'drift_mean_spearman': rnd(drift['mean_rho']),
           'half_life_p10_days': rnd(p10), 'half_life_p50_days': rnd(quantile(vals, 0.5)), 'half_life_p90_days': rnd(p90),
           'spread_p90_over_p10': rnd(spread, 1),
           'median_half_life_by_stability': {k: rnd(quantile(v, 0.5)) for k, v in sorted(by_st.items())}}
    # page: top 24 elements by chain versions; one row per element = its longest chain
    rows = []
    for s, cs in sorted(per_el.items(), key=lambda kv: (-max(len(c['ts']) for c in kv[1]), kv[0]))[:24]:
        c = max(cs, key=lambda c: (len(c['ts']), -c['i']))
        newest = c['ts'][-1]
        ages = [rnd((newest - t).total_seconds() / 3600, 3) for t in c['ts']]
        rows.append({'s': s, 'n': P['elements'][s]['name'], 'path': c['repo'] + '/' + c['path'], 'ages': ages,
                     'hl': P['elements'][s]['half_life_days'], 'st': P['elements'][s]['stability'], 'chains': len(cs),
                     'kept': c['own'] == newest})
    js = r'''
function draw(){const rh=26,top=28;size(w=>top+DATA.rows.length*rh+30);const L=Math.min(120,W*0.28),R=W-12;
const maxh=Math.log10(1+Math.max(...DATA.rows.flatMap(r=>r.ages)));const X=a=>R-(Math.log10(1+a)/maxh)*(R-L);
ctx.font='11px system-ui';ctx.fillStyle='#a6adbb';ctx.strokeStyle='#2f343d';ctx.lineWidth=1;
const ticks=[[0,'kept'],[1,'1 h'],[24,'1 d'],[168,'1 wk'],[720,'1 mo'],[4320,'6 mo']];
for(const [a,t] of ticks){if(Math.log10(1+a)>maxh)continue;const x=X(a);ctx.beginPath();ctx.moveTo(x,top-6);ctx.lineTo(x,H-24);ctx.stroke();ctx.fillText(t,Math.min(x-8,W-34),H-8)}
ctx.fillText('older  <-  age before the kept version (log)',L,14);HITS=[];
DATA.rows.forEach((r,k)=>{const y=top+k*rh+rh/2;ctx.fillStyle='#fff';ctx.fillText(r.s,4,y+4);ctx.fillStyle='#a6adbb';ctx.fillText(r.st[0].toUpperCase(),36,y+4);
ctx.strokeStyle='#66ccff';ctx.globalAlpha=.5;ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(X(r.ages[0]),y);ctx.lineTo(X(0),y);ctx.stroke();ctx.globalAlpha=1;
r.ages.forEach((a,j)=>{const x=X(a),last=j===r.ages.length-1;ctx.fillStyle=last?'#00ffff':SER[0];ctx.strokeStyle='#0b0e14';ctx.lineWidth=2;ctx.beginPath();ctx.arc(x,y,last?5:4,0,7);ctx.fill();ctx.stroke()});
HITS.push({x:L,y:y-rh/2,w:R-L,h:rh,t:'<b>'+esc(r.s)+'</b> '+esc(r.n)+'<br>'+esc(r.path)+'<br>'+r.ages.length+' versions in this chain, '+r.chains+' chains in element<br>half-life '+r.hl+' days &middot; '+esc(r.st)})})}
legend([[SER[0],'older stamped version'],['#00ffff','version the graph keeps'],['#a6adbb','S/U = settled/unsettled']]);
'''
    trows = [[r['s'], r['n'], len(r['ages']), r['hl'], r['st'], r['path']] for r in rows]
    write_page(out, 'decay.html', 'Decay chains: how fast versions get superseded',
               'When a file is saved again under a new timestamp, the old one decays. How fast does each element decay, and is that measurement trustworthy?',
               res, 'Each row is one element\'s longest version chain. Dots are stamped versions placed by age before the kept version (log scale); the cyan dot is the one the graph keeps. Rows bunched at the right decay in minutes.',
               'Version family = estate paths (estate-blobs.tsv) equal to a member path once 20YYMMDD[hhmm] stamps are masked (build.py rule). Half-life = median gap between consecutive stamps. Truth check (independent of the stamps\' meaning): read every version from the local clone and compute line-set Jaccard to the newest; in a real decay chain similarity rises with stamp time (Spearman > 0).   … [line shortened here: 619 characters; full line on GitHub]
               {'rows': rows}, js, table(['element', 'name', 'versions', 'half-life days', 'stability', 'chain'], trows), ctx)
    return res


# ------------------------------------------------------------------ 3 isotope cloud
def exp_isotopes(ctx, P, out):
    # truth check A: identity verbatim count vs raw blob count in estate-blobs.tsv (different source, same quantity)
    blob_count = collections.Counter()
    with open(props.DEFAULTS['blobs'], encoding='utf-8') as fh:
        for line in fh:
            b = line.split('\t', 1)[0]
            blob_count[b] += 1
    agree = n = 0
    xs, ys = [], []
    for i, v in sorted(ctx['identity'].items()):
        b = v.get('keys', {}).get('git_blob')
        if not b:
            continue
        a = int(v.get('verdict', {}).get('estate_verbatim_copies') or 0)
        raw = max(0, blob_count.get(b, 1) - 1)
        n += 1
        agree += (a == raw)
        xs.append(a)
        ys.append(raw)
    exact = agree / n if n else 0
    rho = spearman(xs, ys)
    # truth check B: near-copy isotopes vs families.json (line-Jaccard >= 0.9 groups, a different detector)
    partner = collections.defaultdict(set)
    if os.path.exists(FAMILIES):
        for p in props._read_json(FAMILIES)['proposals']:
            if isinstance(p.get('target_file_id'), int):
                partner[p['file_id']].add(p['target_file_id'])
                partner[p['target_file_id']].add(p['file_id'])

    def crosses(ids):
        ids = set(ids)
        return any(partner.get(i, set()) - ids for i in ids)
    els = [e for e in P['elements'].values() if e['members']]
    tp = fp = fn = 0
    for e in els:
        pred = e['near_copies'] > 0
        act = crosses(e['file_ids'])
        tp += pred and act
        fp += pred and not act
        fn += act and not pred
    prec = tp / (tp + fp) if tp + fp else 0
    rec = tp / (tp + fn) if tp + fn else 0
    f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0
    stp = sfp = sfn = 0
    for e in els:
        pred = e['near_copies'] > 0 or e['relatives'] > 0
        act = crosses(e['file_ids'])
        stp += pred and act
        sfp += pred and not act
        sfn += act and not pred
    sprec = stp / (stp + sfp) if stp + sfp else 0
    srec = stp / (stp + sfn) if stp + sfn else 0
    sf1 = 2 * sprec * srec / (sprec + srec) if sprec + srec else 0
    tot_iso = sum(e['isotopes'] for e in els)
    with_iso = sum(1 for e in els if e['isotopes'])
    if exact >= 0.9 and f1 >= 0.6:
        verdict = 'reveals'
    elif exact >= 0.9 or f1 >= 0.6:
        verdict = 'marginal'
    else:
        verdict = 'no'
    res = {'verdict': verdict,
           'basis': 'verbatim copies agree with raw estate blob counts for %.1f%% of files (Spearman %.3f); near-copy isotopes vs families.json: precision %.2f, recall %.2f, F1 %.2f (adding Twin/Vedic relatives drops F1 to %.2f); %d of %d elements carry isotopes'
           % (100 * exact, rho, prec, rec, f1, sf1, with_iso, len(els)),
           'verbatim_exact_agreement': rnd(exact), 'verbatim_spearman': rnd(rho), 'families_precision': rnd(prec),
           'families_recall': rnd(rec), 'families_f1': rnd(f1),
           'with_relatives_precision': rnd(sprec), 'with_relatives_recall': rnd(srec), 'with_relatives_f1': rnd(sf1), 'elements_with_isotopes': with_iso,
           'elements': len(els), 'total_isotopes': tot_iso}
    cells = []
    for e in els:
        cells.append({'s': e['symbol'], 'n': e['name'], 'mem': e['members'], 'nc': e['near_copies'], 'vb': e['verbatim_copies'],
                      'vs': e['versions'], 'iso': e['isotopes'], 'mass': e['mass'], 'st': e['stability']})
    js = r'''
function draw(){const cols=W<500?6:W<900?10:14;const n=DATA.cells.length;const cw=0;size(w=>{const c=w/cols;return Math.ceil(n/cols)*c+8});const c=W/cols;HITS=[];
ctx.font='10px system-ui';const GA=2.399963;
DATA.cells.forEach((e,k)=>{const cx=(k%cols)*c+c/2,cy=Math.floor(k/cols)*c+c/2;
const dots=Math.min(70,Math.round(5*Math.log2(1+e.iso)));const tot=e.nc+e.vb+e.vs||1;const R=c*0.44;
for(let j=0;j<dots;j++){const f=j/dots;const col=f<e.nc/tot?SER[0]:f<(e.nc+e.vb)/tot?SER[1]:SER[2];const rr=R*Math.sqrt((j+0.5)/dots);const a=j*GA;
ctx.fillStyle=col;ctx.globalAlpha=.85;ctx.beginPath();ctx.arc(cx+rr*Math.cos(a),cy+rr*Math.sin(a),1.8,0,7);ctx.fill()}
ctx.globalAlpha=1;ctx.fillStyle=e.st==='unsettled'?'#eb6263':'#fff';ctx.strokeStyle='#0b0e14';ctx.lineWidth=2;const nr=Math.min(c*0.16,2+Math.sqrt(e.mem));
ctx.beginPath();ctx.arc(cx,cy,nr,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#a6adbb';ctx.fillText(e.s,cx-c/2+3,cy-c/2+11);
HITS.push({x:cx,y:cy,r:c/2,t:'<b>'+esc(e.s)+'</b> '+esc(e.n)+'<br>'+e.mem+' member files, '+e.mass+' lines ('+esc(e.st)+')<br>isotopes '+e.iso+': '+e.nc+' near copies, '+e.vb+' verbatim copies, '+e.vs+' versions'})})}
legend([[SER[0],'near copy in the graph'],[SER[1],'verbatim copy in the estate'],[SER[2],'older stamped version'],['#fff','nucleus (settled)'],['#eb6263','nucleus (unsettled)']]);
'''
    top = sorted(cells, key=lambda c: -c['iso'])
    write_page(out, 'isotopes.html', 'Isotope cloud: how much each element is duplicated',
               'Each element is surrounded by a cloud of its copies. Where is the duplication, and do two independent counts agree?',
               res, 'One cell per element in atomic-number order. Nucleus size = member files (red = unsettled). Cloud dots grow with log2(1 + isotopes), coloured by kind of copy. A dense cloud is an element that has been copied or re-saved many times.',
               'Isotopes per props.py. Truth check A: identity-files.json verdict.estate_verbatim_copies against a raw count of the same git blob in estate-blobs.tsv. Truth check B: elements with near-copy isotopes against elements with a families.json pair (line-Jaccard >= 0.9, a different detector) that crosses the element boundary. Reveals needs A >= 90% exact and B F1 >= 0.6; one of the two =   … [line shortened here: 411 characters; full line on GitHub]
               {'cells': cells}, js,
               table(['element', 'name', 'isotopes', 'near copies', 'verbatim', 'versions', 'members'],
                     [[c['s'], c['n'], c['iso'], c['nc'], c['vb'], c['vs'], c['mem']] for c in top]), ctx)
    return res


# ------------------------------------------------------------------ 4 periodicity
def real_layout():
    """[(Z, period, group or None, display_row, display_col)] for Z = 1..118 (standard IUPAC 18-column table)."""
    out = []
    z = 1
    def add(p, g, row=None, col=None):
        nonlocal z
        out.append((z, p, g, row if row else p, col if col else g))
        z += 1
    add(1, 1); add(1, 18)
    for p in (2, 3):
        add(p, 1); add(p, 2)
        for g in range(13, 19):
            add(p, g)
    for p in (4, 5):
        for g in range(1, 19):
            add(p, g)
    for p, frow in ((6, 9), (7, 10)):
        add(p, 1); add(p, 2)
        for k in range(15):
            add(p, None, frow, 3 + k)
        for g in range(4, 19):
            add(p, g)
    return out


def mapper_axes_test(P, keys, rng):
    """Does the same column (group) mean the same property level in every period? eta^2 of group after removing
    period means, against 200 shuffles of group labels within each period."""
    els = [e for e in P['elements'].values() if e['members'] and e.get('period') is not None and e.get('group')]
    out = {}
    if len(els) < 30:
        return {k: None for k, _ in keys}
    by_p = collections.defaultdict(list)
    for j, e in enumerate(els):
        by_p[e['period']].append(j)
    for k, _ in keys:
        v = [math.log1p(e[k]) for e in els]
        pm = {p: sum(v[j] for j in js) / len(js) for p, js in by_p.items()}
        r = [v[j] - pm[e['period']] for j, e in enumerate(els)]
        sst = sum(x * x for x in r) or 1

        def eta(groups):
            by = collections.defaultdict(list)
            for g, x in zip(groups, r):
                by[g].append(x)
            m = sum(r) / len(r)
            return sum(len(xs) * (sum(xs) / len(xs) - m) ** 2 for xs in by.values()) / sst

        g0 = [e['group'] for e in els]
        e0 = eta(g0)
        null = []
        for t in range(200):
            g = g0[:]
            for p, js in sorted(by_p.items()):
                lab = [g0[j] for j in js]
                rng.shuffle(lab)
                for j, x in zip(js, lab):
                    g[j] = x
            null.append(eta(g))
        n95 = quantile(null, 0.95)
        out[k] = {'eta2_within': rnd(e0), 'null_p95': rnd(n95), 'repeats': e0 > n95 and e0 >= ETA_FLOOR, 'elements': len(els)}
    return out


def exp_periodicity(ctx, P, out):
    els = [e for e in sorted(P['elements'].values(), key=lambda e: (e['number'] or 0, e['symbol'])) if e['members'] and e['number'] is not None][:118]
    keys = [('mass', 'mass'), ('valence', 'valence'), ('electronegativity', 'electronegativity'),
            ('isotopes', 'isotopes'), ('reactivity', 'reactivity')]
    lay = real_layout()[:len(els)]
    rng = random.Random(SEED)
    per = {}
    passes = 0
    for k, _ in keys:
        v = [math.log1p(e[k]) for e in els]
        groups = [l[2] if l[2] is not None else 'f' for l in lay]

        def ratio(vals):
            # between-group variance share (eta^2) over the real-table groups
            m = sum(vals) / len(vals)
            sst = sum((x - m) ** 2 for x in vals) or 1
            by = collections.defaultdict(list)
            for g, x in zip(groups, vals):
                by[g].append(x)
            ssb = sum(len(xs) * (sum(xs) / len(xs) - m) ** 2 for xs in by.values())
            return ssb / sst

        def acf(vals, lag):
            m = sum(vals) / len(vals)
            d = sum((x - m) ** 2 for x in vals) or 1
            return sum((vals[i] - m) * (vals[i + lag] - m) for i in range(len(vals) - lag)) / d

        eta = ratio(v)
        lags = list(range(2, 41))
        ac = [acf(v, L) for L in lags]
        best = max(range(len(lags)), key=lambda j: ac[j])
        null_eta, null_ac = [], []
        for t in range(200):
            w = v[:]
            rng.shuffle(w)
            null_eta.append(ratio(w))
            null_ac.append(max(acf(w, L) for L in lags))
        e95, a95 = quantile(null_eta, 0.95), quantile(null_ac, 0.95)
        ok = eta > e95 and eta >= ETA_FLOOR and ac[best] > a95
        passes += ok
        per[k] = {'eta2_groups': rnd(eta), 'eta2_null_p95': rnd(e95), 'best_lag': lags[best], 'acf_best': rnd(ac[best]),
                  'acf_null_p95_of_max': rnd(a95), 'acf_lag18': rnd(ac[lags.index(18)]), 'repeats': ok,
                  'acf': [rnd(x, 3) for x in ac]}
    mapper = mapper_axes_test(P, keys, rng)
    mpass = sum(1 for v in mapper.values() if v and v['repeats'])
    if passes >= 3 or mpass >= 3:
        verdict = 'reveals'
    elif passes >= 1 or mpass >= 1:
        verdict = 'marginal'
    else:
        verdict = 'no'
    res = {'verdict': verdict,
           'basis': 'real-table layout: %d of %d properties repeat beyond a shuffle null (lag-18 autocorrelation %s); MAPPER table (column = role group, row = abstraction period): column explains %s within periods, %d of %d beat the within-period shuffle'
           % (passes, len(keys), ', '.join('%s %.2f' % (k, per[k]['acf_lag18']) for k, _ in keys),
              ', '.join('%s %.2f' % (k, mapper[k]['eta2_within']) for k, _ in keys if mapper.get(k)), mpass, len(keys)),
           'elements_placed': len(els), 'properties': per, 'repeating_properties': passes,
           'mapper_axes': mapper, 'mapper_repeating_properties': mpass}
    cells = []
    for e, l in zip(els, lay):
        cells.append({'s': e['symbol'], 'n': e['name'], 'z': l[0], 'r': l[3], 'c': l[4],
                      'v': {k: e[k] for k, _ in keys}})
    controls = '<div class="ctl" id="ctl">%s</div>' % ''.join(
        '<button type="button" data-k="%s" aria-pressed="%s">%s</button>' % (k, 'true' if j == 0 else 'false', lab) for j, (k, lab) in enumerate(keys))
    js = r'''
let K='mass';document.querySelectorAll('#ctl button').forEach(b=>b.addEventListener('click',()=>{K=b.dataset.k;document.querySelectorAll('#ctl button').forEach(x=>x.setAttribute('aria-pressed',x===b));draw()}));
function draw(){const c=W?W/18:20;size(w=>{const cc=w/18;return cc*10.6+150});const cs=W/18;HITS=[];
const vals=DATA.cells.map(e=>Math.log1p(e.v[K]));const mn=Math.min(...vals),mx=Math.max(...vals);
const shade=t=>{const l=18+t*62;return 'hsl(190,100%,'+l+'%)'};ctx.font=Math.max(8,Math.min(12,cs*0.32))+'px system-ui';
DATA.cells.forEach((e,k)=>{const x=(e.c-1)*cs,y=(e.r-1)*cs+(e.r>=9?cs*0.5:0);const t=(vals[k]-mn)/(mx-mn||1);ctx.fillStyle=shade(t);ctx.fillRect(x+1,y+1,cs-2,cs-2);
ctx.fillStyle=t>0.55?'#000':'#fff';ctx.fillText(e.s,x+3,y+cs*0.6);HITS.push({x,y,w:cs,h:cs,t:'<b>'+esc(e.s)+'</b> '+esc(e.n)+'<br>slot Z='+e.z+'<br>'+K+' '+e.v[K]})});
const P=DATA.props[K];const gy=cs*10.6+20,gh=110,L=34,R=W-10;ctx.strokeStyle='#2f343d';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(L,gy+gh/2);ctx.lineTo(R,gy+gh/2);ctx.stroke();
const X=j=>L+j/(P.acf.length-1)*(R-L),Y=v=>gy+gh/2-v*gh/2;ctx.fillStyle='#2f343d';ctx.globalAlpha=.6;ctx.fillRect(L,Y(P.acf_null_p95_of_max),R-L,Y(-P.acf_null_p95_of_max)-Y(P.acf_null_p95_of_max));ctx.globalAlpha=1;
ctx.strokeStyle='#66ccff';ctx.lineWidth=2;ctx.beginPath();P.acf.forEach((v,j)=>{j?ctx.lineTo(X(j),Y(v)):ctx.moveTo(X(j),Y(v))});ctx.stroke();
P.acf.forEach((v,j)=>HITS.push({x:X(j),y:Y(v),r:6,t:'lag '+(j+2)+': autocorrelation '+v}));
ctx.fillStyle='#a6adbb';ctx.fillText('autocorrelation by lag 2..40 (band = shuffle null p95); lag 18 = real table width',L,gy-4);ctx.fillText('+1',4,Y(1)+4);ctx.fillText('-1',4,Y(-1)+4)}
legend([['hsl(190,100%,18%)','low (log scale)'],['hsl(190,100%,80%)','high'],['#2f343d','shuffle null band']]);
'''
    trows = [[k, per[k]['eta2_groups'], per[k]['eta2_null_p95'], per[k]['best_lag'], per[k]['acf_best'], per[k]['acf_null_p95_of_max'], per[k]['repeats'],
              (mapper.get(k) or {}).get('eta2_within'), (mapper.get(k) or {}).get('null_p95'), (mapper.get(k) or {}).get('repeats')] for k, _ in keys]
    write_page(out, 'periodicity.html', 'Periodicity check: do the properties repeat?',
               'If the first 118 code elements (by permanent number) are laid on the real 18-column table, do elements in the same column share properties the way real elements do?',
               res, 'Cells use the real table shape; colour = the chosen property (log). The line below is autocorrelation of the property along atomic number; a real periodic law would show a peak above the grey band.',
               'Test 1: numbered elements with member files, ordered by permanent number, first 118 placed into the IUPAC layout (f-block rows separate). For log1p(property): eta^2 of the 18 columns + f-block, and max autocorrelation over lags 2-40; both compared with 200 seeded shuffles (p95); a property repeats only if both beat the null. Test 2: the MAPPER\'s own table (periodic.json group = co  … [line shortened here: 748 characters; full line on GitHub]
               {'cells': cells, 'props': per}, js,
               table(['property', 'eta2 real columns', 'null p95', 'best lag', 'acf at best', 'null p95 (max)', 'repeats (real layout)', 'eta2 MAPPER column within period', 'null p95', 'repeats (MAPPER)'], trows), ctx, controls)
    return res


# ------------------------------------------------------------------ 5 spectrum barcode per repo
def exp_barcode(ctx, P, out):
    role_group = {r: k for k, (_, rs) in enumerate(ROLE_GROUPS) for r in rs}
    G = len(ROLE_GROUPS)
    by_repo = collections.defaultdict(list)
    for f in ctx['files']:
        by_repo[f['repo']].append(f)
    repos = sorted((r for r in by_repo if len(by_repo[r]) >= 10), key=lambda r: (-len(by_repo[r]), r))

    def spec(fs):
        c = [0] * G
        for f in fs:
            c[role_group.get(f['role'], G - 1)] += 1
        t = sum(c) or 1
        return [x / t for x in c]

    def js_div(p, q):
        m = [(a + b) / 2 for a, b in zip(p, q)]
        def kl(a, b):
            return sum(x * math.log2(x / y) for x, y in zip(a, b) if x > 0)
        return (kl(p, m) + kl(q, m)) / 2

    def match_acc(assign):
        A, B = {}, {}
        for r in repos:
            fs = assign[r]
            A[r] = spec([f for f in fs if f['id'] % 2 == 0])
            B[r] = spec([f for f in fs if f['id'] % 2 == 1])
        hits = 0
        for r in repos:
            best = min(repos, key=lambda s: (js_div(B[r], A[s]), s))
            hits += best == r
        return hits / len(repos)

    acc = match_acc(by_repo)
    rng = random.Random(SEED)
    allf = [f for r in repos for f in by_repo[r]]
    null = []
    for t in range(50):
        sh = allf[:]
        rng.shuffle(sh)
        assign, k = {}, 0
        for r in repos:
            assign[r] = sh[k:k + len(by_repo[r])]
            k += len(by_repo[r])
        null.append(match_acc(assign))
    n95 = quantile(null, 0.95)
    chance = 1 / len(repos)
    # element spectra (props.spectrum) are the same formula on member files: report how many elements are single-role
    els = [e for e in P['elements'].values() if e['members']]
    pure = sum(1 for e in els if max(e['spectrum']) >= 0.999)
    if acc >= 3 * chance and acc > n95:
        verdict = 'reveals'
    elif acc > n95:
        verdict = 'marginal'
    else:
        verdict = 'no'
    res = {'verdict': verdict,
           'basis': 'a repo\'s even-id half finds its odd-id half by barcode alone %.0f%% of the time (chance %.1f%%, shuffled-files null p95 %.0f%%) over %d repos'
           % (100 * acc, 100 * chance, 100 * n95, len(repos)),
           'self_match_accuracy': rnd(acc), 'chance': rnd(chance), 'null_p95': rnd(n95), 'repos': len(repos),
           'single_role_elements': pure, 'elements': len(els)}
    rows = []
    for r in repos:
        fs = by_repo[r]
        c = [0] * G
        for f in fs:
            c[role_group.get(f['role'], G - 1)] += 1
        rows.append({'r': r, 'n': len(fs), 'c': c})
    js = r'''
function draw(){const rh=W<500?22:20,top=6;size(w=>top+DATA.rows.length*rh+6);const L=Math.min(150,W*0.36),R=W-8;HITS=[];ctx.font='11px system-ui';
DATA.rows.forEach((r,k)=>{const y=top+k*rh;ctx.fillStyle='#a6adbb';let lab=r.r.length>22?r.r.slice(0,21)+'…':r.r;ctx.fillText(lab+' '+r.n,2,y+rh*0.68);
let x=L;const tot=r.c.reduce((a,b)=>a+b,0);r.c.forEach((v,j)=>{if(!v)return;const w=v/tot*(R-L);ctx.fillStyle=j<8?SER[j]:OTHER;ctx.fillRect(x,y+2,Math.max(1,w-2),rh-4);
HITS.push({x,y,w,h:rh,t:'<b>'+esc(r.r)+'</b><br>'+esc(DATA.groups[j])+': '+v+' of '+tot+' files ('+Math.round(100*v/tot)+'%)'});x+=w})})}