GLOBALGRID2050 / EXPLORE CODE

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

Feed and 1 more file

A Python command-line tool in the periodic folder of Cosmic that reads fixture periodic, fixture props, element and cards. It loads periodic (`load_periodic`), loads props (`load_props`) and loads graph (`load_graph`).

700 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1110 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 701–760
  2. Feed storage · cosmic / tools/explore/periodic/feed.py lines 1–640

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 701–760 of 760 (continued from section 1109) · 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
run, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/experiments/exp.py:701-760 · blob 51047570db3c32e17c20e77100306ee6808a9282 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
legend(DATA.groups.map((g,j)=>[j<8?SER[j]:OTHER,g]));
'''
    groups = [g for g, _ in ROLE_GROUPS]
    write_page(out, 'barcode.html', 'Spectrum barcode per repository',
               'Like an emission spectrum, each repository has a mix of file roles. Is that barcode a stable fingerprint that tells repositories apart?',
               res, 'One bar per repository (10+ files), split by share of files in each role group. Test-heavy, render-heavy and automation-heavy repositories stand out at a glance.',
               'Roles from build_graph.json folded into 9 groups (domain = geodesy+electrical+energy-data; other = docs-config+other) so the palette stays at 8 hues + grey. Self-match test: split each repo\'s files by id parity; for each odd half, the nearest even half by Jensen-Shannon divergence must be its own repo. Null = files shuffled across repos (50 seeded runs). Reveals needs accuracy >=   … [line shortened here: 435 characters; full line on GitHub]
               {'rows': rows, 'groups': groups}, js,
               table(['repository', 'files'] + groups, [[r['r'], r['n']] + r['c'] for r in rows]), ctx)
    return res


INDEX = '''<!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>Periodic experiments</title><style>
body{margin:0;background:#000;color:#fff;font:15px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:900px;margin:0 auto;padding:12px}
a{color:#66ccff}li{background:#0b0e14;border:1px solid #2f343d;border-radius:8px;padding:10px;margin:8px 0;list-style:none}ul{padding:0}
b{color:#00ffff}p{color:#a6adbb}</style></head><body><main><h1>Periodic table of the code estate: experiments</h1>
<p>Each page is a picture driven by measured element properties (props.py) plus a metric that says whether the picture is true and useful. Verdicts use fixed thresholds.</p><ul>%s</ul></main></body></html>'''


EXPERIMENTS = [('reactions', 'reactions.html', 'Reactions: molecules', exp_reactions),
               ('decay', 'decay.html', 'Decay chains', exp_decay),
               ('isotopes', 'isotopes.html', 'Isotope cloud', exp_isotopes),
               ('periodicity', 'periodicity.html', 'Periodicity check', exp_periodicity),
               ('barcode', 'barcode.html', 'Spectrum barcode per repo', exp_barcode)]


def run(out, ctx=None, P=None):
    os.makedirs(out, exist_ok=True)
    ctx = ctx or props.dev_ctx()
    P = P or props.compute_all(ctx)
    results = {}
    items = []
    for key, page, title, fn in EXPERIMENTS:
        r = fn(ctx, P, out)
        results[key] = r
        items.append('<li><a href="%s">%s</a><br><b>%s</b> &middot; %s</li>' % (page, html.escape(title), html.escape(r['verdict']), html.escape(r['basis'])))
    with open(os.path.join(out, 'index.html'), 'w', encoding='utf-8') as fh:
        fh.write(INDEX % ''.join(items))
    m = {'schema': 'explore-periodic-experiments-v1', 'rules': props.RULES, 'seed': SEED, 'graph_cut': ctx['graph_cut'],
         'props_digest': props.digest(P['elements']), 'experiments': results}
    m['digest'] = props.digest(results)
    with open(os.path.join(out, 'metrics.json'), 'w', encoding='utf-8') as fh:
        json.dump(m, fh, indent=1, sort_keys=True)
    return m, P


def main(argv):
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument('--out', default='/tmp/vk/periodic/experiments')
    a = ap.parse_args(argv)
    m, P = run(a.out)
    for k, r in m['experiments'].items():
        print('%-12s %-9s %s' % (k, r['verdict'], r['basis']))
    print('digest', m['digest'][:16])


if __name__ == '__main__':
    main(sys.argv[1:])

Feed

A Python command-line tool in the periodic folder of Cosmic that reads fixture periodic, fixture props, element and cards. It loads periodic (`load_periodic`), loads props (`load_props`) and loads graph (`load_graph`).

storagecosmic / tools/explore/periodic/feed.py · lines 1–640 of 760 · Entry point · pattern fixture_note (shared by 2 files)

What it does
It loads fixture periodic, fixture props, element and cards. Defines 35 functions or classes, including _chem_table, ln_of, esc, first, pick. Uses libraries __future__, argparse, html, json, math. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file periodic.json; JSON file fixture-periodic.json; JSON file props.json; JSON file fixture-props.json; JSON file element-index.json; JSON file cards.json; JSON file build_graph.json; form fields (user input). Out: JSON file element-index.json; JSON file extra.json; JSON file cards.json; JSON file fixture-periodic.json; JSON file fixture-props.json.
Downstream impact
Used directly by 2 files: Extras (cosmic); Test Feed (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Post-build step: feed the periodic table of the code estate into Explore Code. It accepts `--site`, `--out` and `--graph`.
Why it matters
Run by Extras. Checked by Test Feed.
Application
cosmic · tools/explore/periodic · Python CLI
Uses
__future__, argparse, html, json, math, os, re, shutil
Used by
run by Extras (script call), imported by Test Feed (import)
Produces
ln_of, esc, first, pick, norm_analogy, norm_value, as_list, norm_evidence, norm_files, load_periodic, load_props, load_graph
Defines here
_chem_table, ln_of, esc, first, pick, norm_analogy, norm_value, as_list, norm_evidence, norm_files, load_periodic, load_props, load_graph, file_names, order_key, layout, shape, header, state_label, num_label, file_link, group_of, element_card_html, fixture_note, tile, render_index, footer, render_element, render_llms, build_index_json
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/feed.py:1-640 · blob 3f9fdcaeaf2c184b7d34577f2c8c609a00102ccb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Post-build step: feed the periodic table of the code estate into Explore Code.

    python tools/explore/periodic/feed.py --site <out>/explore-code \
        [--periodic periodic.json] [--props props.json] [--furnace <dir>] [--graph G] [--out DIR]

Writes <site>/periodic/ (or --out DIR, for extras.py staging):
  index.html            interactive table (phone first, scrolls in its own frame), colour switch, element cards,
                        "estate elements" / "chemical analogy" view switch, <noscript> list
  <Sym>.html            one page per element (CANDIDATE elements: candidate-<Sym>.html)
  llms-periodic.txt     plain-text shard for agents
  element-index.json    explore-periodic-index-v1: file id -> element symbols, for badges and the Periodic mode
  cards.json            card details (values, evidence, files), fetched by index.html when a card opens
  periodic.css/.js      page assets (from page/); extra.json: hub card text for extras.py
  furnace/              byte copy of the FURNACE gallery when one exists (index.html required)

Inputs are read, never changed. Nothing is invented: every value shown comes from periodic.json, props.json or
build_graph.json. With no periodic.json the bundled fixture (page/fixture-periodic.json, built from
star-maker/PERIODIC-TABLE.md) is used and every page says so. No network, no CDN.
"""
from __future__ import annotations

import argparse
import html
import json
import math
import os
import re
import shutil
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
PAGE = HERE / 'page'
SCHEMA_INDEX = 'explore-periodic-index-v1'
DEFAULT_PERIODIC = [Path('/tmp/vk/periodic/periodic.json'), PAGE / 'fixture-periodic.json']
DEFAULT_PROPS = [Path('/tmp/vk/periodic/props.json'), PAGE / 'fixture-props.json']
DEFAULT_FURNACE = [Path('/tmp/vk/periodic/furnace')]

# Categorical colours already used by the site (explore.css role badges), in a fixed order.
PALETTE = ['#00ffff', '#ffae00', '#00ff88', '#ff6666', '#66ccff', '#ffd24a', '#86e1d1', '#aef7d1', '#ffff00']
FAMILY_ORDER = ['physics', 'vocabulary', 'engine', 'cartridge', 'data-layer', 'contract']
CANDIDATE_COLOR = '#a6adbb'

# The 118 chemical elements (IUPAC symbols and English names), in atomic-number order.
CHEM_TEXT = (
    'H Hydrogen,He Helium,Li Lithium,Be Beryllium,B Boron,C Carbon,N Nitrogen,O Oxygen,F Fluorine,Ne Neon,'
    'Na Sodium,Mg Magnesium,Al Aluminium,Si Silicon,P Phosphorus,S Sulfur,Cl Chlorine,Ar Argon,K Potassium,'
    'Ca Calcium,Sc Scandium,Ti Titanium,V Vanadium,Cr Chromium,Mn Manganese,Fe Iron,Co Cobalt,Ni Nickel,'
    'Cu Copper,Zn Zinc,Ga Gallium,Ge Germanium,As Arsenic,Se Selenium,Br Bromine,Kr Krypton,Rb Rubidium,'
    'Sr Strontium,Y Yttrium,Zr Zirconium,Nb Niobium,Mo Molybdenum,Tc Technetium,Ru Ruthenium,Rh Rhodium,'
    'Pd Palladium,Ag Silver,Cd Cadmium,In Indium,Sn Tin,Sb Antimony,Te Tellurium,I Iodine,Xe Xenon,'
    'Cs Caesium,Ba Barium,La Lanthanum,Ce Cerium,Pr Praseodymium,Nd Neodymium,Pm Promethium,Sm Samarium,'
    'Eu Europium,Gd Gadolinium,Tb Terbium,Dy Dysprosium,Ho Holmium,Er Erbium,Tm Thulium,Yb Ytterbium,'
    'Lu Lutetium,Hf Hafnium,Ta Tantalum,W Tungsten,Re Rhenium,Os Osmium,Ir Iridium,Pt Platinum,Au Gold,'
    'Hg Mercury,Tl Thallium,Pb Lead,Bi Bismuth,Po Polonium,At Astatine,Rn Radon,Fr Francium,Ra Radium,'
    'Ac Actinium,Th Thorium,Pa Protactinium,U Uranium,Np Neptunium,Pu Plutonium,Am Americium,Cm Curium,'
    'Bk Berkelium,Cf Californium,Es Einsteinium,Fm Fermium,Md Mendelevium,No Nobelium,Lr Lawrencium,'
    'Rf Rutherfordium,Db Dubnium,Sg Seaborgium,Bh Bohrium,Hs Hassium,Mt Meitnerium,Ds Darmstadtium,'
    'Rg Roentgenium,Cn Copernicium,Nh Nihonium,Fl Flerovium,Mc Moscovium,Lv Livermorium,Ts Tennessine,Og Oganesson'
)


def _chem_table() -> list[dict]:
    out = []
    for z, item in enumerate(CHEM_TEXT.split(','), start=1):
        sym, name = item.split(' ', 1)
        if z <= 2:
            period, group = 1, (1 if z == 1 else 18)
        else:
            # period starts: 3, 11, 19, 37, 55, 87
            starts = [(3, 2, 8), (11, 3, 8), (19, 4, 18), (37, 5, 18), (55, 6, 32), (87, 7, 32)]
            for s, p, ln in starts:
                if s <= z < s + ln:
                    period, i = p, z - s
                    break
            if ln_of(period) == 8:
                group = i + 1 if i < 2 else i + 11
            elif ln_of(period) == 18:
                group = i + 1
            else:
                group = i + 1 if i < 2 else (None if i < 17 else i - 13)
        row, col = period, group
        if group is None:  # lanthanides / actinides: the two f rows under the table
            row, col = (9 if period == 6 else 10), z - (57 if period == 6 else 89) + 3
        out.append({'z': z, 'sym': sym, 'name': name, 'period': period, 'group': group, 'row': row, 'col': col})
    return out


def ln_of(period: int) -> int:
    return {1: 2, 2: 8, 3: 8, 4: 18, 5: 18, 6: 32, 7: 32}[period]


CHEM = _chem_table()
CHEM_BY_SYM = {c['sym'].lower(): c for c in CHEM}
CHEM_BY_NAME = {c['name'].lower(): c for c in CHEM}
CHEM_BY_NAME.update({'aluminum': CHEM_BY_SYM['al'], 'cesium': CHEM_BY_SYM['cs'], 'sulphur': CHEM_BY_SYM['s']})


def esc(s) -> str:
    return html.escape('' if s is None else str(s), quote=True)


def first(d: dict, *keys, default=None):
    for k in keys:
        if isinstance(d, dict) and d.get(k) not in (None, '', []):
            return d[k]
    return default


def pick(paths) -> Path | None:
    for p in paths:
        if p and Path(p).exists():
            return Path(p)
    return None


# ----------------------------------------------------------------------------------------- normalising
def norm_analogy(raw) -> dict | None:
    if raw in (None, '', {}):
        return None
    why = ''
    if isinstance(raw, dict):
        why = first(raw, 'why', 'reason', 'note', 'because', default='')
        key = first(raw, 'symbol', 'sym', 'name', 'element', default=None)
        z = first(raw, 'Z', 'z', 'number', 'atomic_number', default=None)
        c = None
        if isinstance(z, int) and 1 <= z <= 118:
            c = CHEM[z - 1]
        elif key:
            c = CHEM_BY_SYM.get(str(key).lower()) or CHEM_BY_NAME.get(str(key).lower())
    else:
        text, c = str(raw), None
        for w in re.findall(r'[A-Za-z]+', text):
            c = CHEM_BY_NAME.get(w.lower()) or (CHEM_BY_SYM.get(w.lower()) if w[0].isupper() and len(w) <= 2 else None)
            if c:
                break
        why = text if c and re.sub(r'^like\s+', '', text.strip().lower()) not in (c['name'].lower(), c['sym'].lower()) else ''
    if not c:
        return {'z': None, 'sym': '?', 'name': str(raw)[:60], 'why': why}
    return {'z': c['z'], 'sym': c['sym'], 'name': c['name'], 'why': str(why)}


def norm_value(v) -> dict:
    if isinstance(v, dict):
        return {'value': str(first(v, 'value', 'v', 'text', default='')),
                'evidence': [str(e) for e in as_list(first(v, 'evidence', 'evidence_keys', 'where', default=[]))],
                'count': first(v, 'count', 'n', 'sites', default=None) or (v['files'] if isinstance(v.get('files'), int) else None)}
    return {'value': str(v), 'evidence': [], 'count': None}


def as_list(x) -> list:
    if x is None:
        return []
    return x if isinstance(x, list) else [x]


def norm_evidence(x) -> list[str]:
    out = []
    for e in as_list(x):
        if isinstance(e, dict):
            key = first(e, 'key', 'evidence', default=None)
            if not key:
                repo, commit, path = e.get('repo', ''), e.get('commit', ''), e.get('path', '')
                lines = first(e, 'lines', 'line', default='')
                key = f"{repo}@{commit[:12] if commit else ''} {path}{':' + str(lines) if lines else ''}".strip()
            out.append(str(key))
        elif e not in (None, ''):
            out.append(str(e))
    return out


def norm_files(x) -> list[int]:
    out = []
    for f in as_list(x):
        fid = first(f, 'id', 'file', 'file_id', default=None) if isinstance(f, dict) else f
        try:
            out.append(int(fid))
        except (TypeError, ValueError):
            continue
    return sorted(set(out))


MAPPER_PROPS = [  # numeric fields periodic.json carries per element (shown with an "map:" key, never mixed with props.json)
    ('file_count', 'files (mapper)', 'files'), ('lines', 'lines (mapper)', 'lines'), ('family_count', 'function families', 'count'),
    ('valence', 'bonded elements (mapper valence)', 'elements'), ('dependents', 'dependents (mapper)', 'files'),
    ('reachable_share', 'reachable share', 'share'), ('timestamp_share', 'timestamped share', 'share'),
    ('importance', 'importance (mapper)', ''), ('tiny_helpers', 'tiny helpers', 'functions')]


def load_periodic(path: Path) -> dict:
    raw = json.loads(path.read_text())
    meta = raw if isinstance(raw, dict) else {}
    elems = raw if isinstance(raw, list) else first(raw, 'elements', 'table', default=[])
    if isinstance(elems, dict):
        elems = [dict(v, symbol=v.get('symbol', k)) for k, v in elems.items()]
    rules = {r.get('id'): r.get('text', '') for r in meta.get('analogue_rules', []) if isinstance(r, dict)}
    axes = meta.get('axes') or {}
    groups = [{'id': str(g.get('id')), 'title': str(g.get('title') or g.get('id')), 'colour': g.get('colour') or g.get('color')}
              for g in axes.get('groups', []) if isinstance(g, dict)]
    periods = [{'n': int(q.get('n')), 'title': str(q.get('title') or q.get('id'))} for q in axes.get('periods', [])
               if isinstance(q, dict) and str(q.get('n', '')).isdigit()]
    out = []
    for e in elems:
        status = str(e.get('status', '')).lower()
        state = str(first(e, 'state', default='') or '').lower()
        cand = bool(e.get('candidate')) or status == 'candidate' or 'candidate' in state
        sym = str(first(e, 'symbol', 'proposed_symbol', 'sym', default='') or '').strip()
        if not sym:
            continue
        n = e.get('number', first(e, 'atomic_number', 'z', default=None))
        n = None if cand or not str(n if n is not None else '').isdigit() else int(n)
        if cand:
            state = 'candidate'
        elif 'unsettled' in state:
            state = 'unsettled'
        elif 'settled' in state:
            state = 'settled'
        else:
            state = 'numbered'  # numbered element with no settled/unsettled verdict in the input
        values = [norm_value(v) for v in as_list(first(e, 'competing_values', 'values', 'unsettled_values', default=[]))]
        an = norm_analogy(first(e, 'analogue', 'analogy', 'chemical', 'chemical_analogy', 'like', default=None))
        if an and isinstance(e.get('analogue'), dict) and e['analogue'].get('rule'):
            rid = e['analogue']['rule']
            an['rule'] = rid
            an['why'] = an['why'] if an['why'] and an['why'] != rid else rules.get(rid, rid)
        family = str(first(e, 'star_family', 'family', 'category', default='') or '')
        props = {}
        for k, label, unit in MAPPER_PROPS:
            if isinstance(e.get(k), (int, float)) and not isinstance(e.get(k), bool) and 'group' in e:
                props['map:' + k] = e[k]
        props.update({k: v for k, v in (first(e, 'properties', 'props', default={}) or {}).items()})
        if family:
            props['map:family'] = family
        out.append({
            'sym': sym, 'key': str(e.get('key') or sym), 'n': n, 'candidate': cand,
            'name': str(first(e, 'name', 'title', default=sym)), 'title': str(e.get('title') or ''),
            'state': state,
            'group': str(first(e, 'group', default='') or family or 'other'), 'family': family or 'other',
            'period': first(e, 'period', 'row', default=None),
            'note': str(first(e, 'note', 'summary', 'description', default='')),
            'values': values,
            'evidence': norm_evidence(first(e, 'evidence', default=[])),
            'keys': [str(k) for k in as_list(first(e, 'evidence_keys', 'keys', default=[]))],
            'files': norm_files(first(e, 'files', 'file_ids', 'members', default=[])),
            'analogy': an, 'props': props,
        })
    if not groups:  # fixture / older shapes: groups = families, one period
        fams = [f for f in FAMILY_ORDER if any(x['group'] == f for x in out)]
        fams += sorted({x['group'] for x in out} - set(fams))
        groups = [{'id': f, 'title': f, 'colour': None} for f in fams]
    for i, g in enumerate(groups):
        g['colour'] = g['colour'] or PALETTE[i % len(PALETTE)]
    known = {g['id'] for g in groups}
    for x in out:
        if x['group'] not in known:
            groups.append({'id': x['group'], 'title': x['group'], 'colour': PALETTE[len(groups) % len(PALETTE)]})
            known.add(x['group'])
        if not isinstance(x['period'], int):
            x['period'] = 1
    if not periods:
        periods = [{'n': n, 'title': f'period {n}'} for n in sorted({x['period'] for x in out})]
    return {'schema': meta.get('schema', ''), 'fixture': bool(meta.get('fixture')),
            'cut': meta.get('cut', meta.get('generated', '')), 'elements': out, 'groups': groups, 'periods': periods}


def load_props(path: Path | None, elements: list[dict]) -> list[dict]:
    """Merge props.json into elements[i]['props']; return the property list [{key,label,unit,kind}] (scalars only)."""
    labels: dict[str, dict] = {'map:' + k: {'key': 'map:' + k, 'label': lab, 'unit': unit} for k, lab, unit in MAPPER_PROPS}
    labels['map:family'] = {'key': 'map:family', 'label': 'star-maker family', 'unit': ''}
    listed = None
    if path and path.exists():
        raw = json.loads(path.read_text())
        if isinstance(raw, dict) and raw.get('properties'):
            listed = []
            for q in as_list(raw['properties']):
                key = q.get('key') if isinstance(q, dict) else q
                if key:
                    listed.append(key)
                    labels[key] = {'key': key, 'label': str((q.get('label') if isinstance(q, dict) else '') or key),
                                   'unit': str((q.get('unit') if isinstance(q, dict) else '') or '')}
        per = first(raw, 'elements', 'values', default={}) if isinstance(raw, dict) else raw
        if isinstance(per, list):
            per = {str(first(x, 'symbol', 'sym', 'key', default='')): x for x in per}
        index = {}
        for e in elements:
            for k in (e['sym'], e['key'], e['sym'].lstrip('*')):
                index.setdefault(k, e)
        for sym, props in (per or {}).items():
            e = index.get(sym) or (index.get(props.get('key')) if isinstance(props, dict) else None)
            if not e or not isinstance(props, dict):
                continue
            props = first(props, 'properties', 'props', default=props)
            for k, v in props.items():
                if listed is not None and k not in listed:
                    continue
                v = v.get('value') if isinstance(v, dict) and 'value' in v else v
                if isinstance(v, (str, int, float)) and not isinstance(v, bool):
                    e['props'][k] = v
    keys = []
    for k in (listed or []):
        keys.append(k)
    for e in elements:
        for k in e['props']:
            if k not in keys:
                keys.append(k)
    out = []
    for k in keys:
        vals = [e['props'].get(k) for e in elements if e['props'].get(k) is not None]
        if not vals:
            continue
        kind = 'number' if all(isinstance(v, (int, float)) for v in vals) else 'category'
        lab = labels.get(k, {'key': k, 'label': k.replace('_', ' '), 'unit': ''})
        out.append(dict(lab, kind=kind))
    return out


def load_graph(path: Path | None) -> dict[int, dict]:
    if not path or not path.exists():
        return {}
    g = json.loads(path.read_text())
    commits = {r['repo']: r.get('commit', '') for r in g.get('repos', [])}
    return {f['id']: {'id': f['id'], 'repo': f['repo'], 'path': f['path'], 'section': f.get('section'),
                      'block': f.get('block'), 'title': f.get('title', ''), 'lines': f.get('lines', 0),
                      'commit': commits.get(f['repo'], '')} for f in g.get('files', [])}


# ----------------------------------------------------------------------------------------- layout
TILE, GAP = 48, 4


def file_names(elements: list[dict]) -> None:
    seen = set()
    for e in elements:
        base = ('candidate-' if e['candidate'] else '') + re.sub(r'[^A-Za-z0-9_-]', '_', e['sym'].lstrip('*'))
        name, i = base, 2
        while name.lower() in seen or name.lower() in ('index', 'periodic'):  # case-insensitive file systems
            name, i = f'{base}-{i}', i + 1
        seen.add(name.lower())
        e['page'] = name + '.html'


def order_key(e: dict):
    return (e['candidate'], e['n'] if e['n'] is not None else 10 ** 6, e['sym'].lower())


def layout(elements: list[dict], groups: list[dict], periods: list[dict]) -> list[dict]:
    """Columns = groups, rows = periods; each (group, period) cell holds its tiles in a wrap. Returns column specs."""
    used_g = [g for g in groups if any(e['group'] == g['id'] for e in elements)]
    used_p = [q for q in periods if any(e['period'] == q['n'] for e in elements)]
    count = {(g['id'], q['n']): 0 for g in used_g for q in used_p}
    for e in elements:
        count[(e['group'], e['period'])] += 1

    def shape(height: int):
        widths = [max(1, min(24, max(max(math.ceil(c / height), min(4, math.ceil(c ** 0.5))) for c in (count[(g['id'], q['n'])] for q in used_p))))
                  for g in used_g]
        rows = sum(max(math.ceil(count[(g['id'], q['n'])] / w) for g, w in zip(used_g, widths)) for q in used_p)
        return widths, sum(widths), rows

    # pick the per-cell height that makes the whole table closest to square (fewest tiles of panning both ways)
    best = min(range(1, 80), key=lambda hh: (max(shape(hh)[1], shape(hh)[2]), hh))
    cols = [dict(g, tiles=w) for g, w in zip(used_g, shape(best)[0])]
    for e in elements:
        e['gc'] = next(i for i, g in enumerate(used_g) if g['id'] == e['group']) + 2
        e['gr'] = next(i for i, q in enumerate(used_p) if q['n'] == e['period']) + 2
    return cols, used_p


# ----------------------------------------------------------------------------------------- rendering
HEAD = ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
        '<meta name="viewport" content="width=device-width,initial-scale=1"><title>{title}</title>'
        '<meta name="description" content="{desc}"><link rel="stylesheet" href="../explore.css">'
        '<link rel="stylesheet" href="periodic.css"></head><body class="pt">')


def header(crumbs: list[tuple[str, str]], h1: str, lead: str) -> str:
    c = ' / '.join(f'<a class="pt-tap" href="{esc(h)}">{esc(t)}</a>' if h else esc(t) for t, h in crumbs)
    return (f'<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE / PERIODIC</p><p class="crumbs">{c}</p>'
            f'<h1>{h1}</h1><p class="pt-lead">{lead}</p></header>')


STATE_TEXT = {'settled': 'settled', 'numbered': 'numbered (no settled/unsettled verdict in the input)'}


def state_label(e: dict) -> str:
    if e['candidate']:
        return 'CANDIDATE (proposal, no number)'
    if e['state'] == 'unsettled':
        return f"unsettled: {len(e['values'])} values in the wild"
    return STATE_TEXT.get(e['state'], e['state'])


def num_label(e: dict) -> str:
    return 'CANDIDATE' if e['candidate'] or e['n'] is None else str(e['n'])


def file_link(f: dict, up: str) -> str:
    if f.get('section'):
        return f"{up}s/{int(f['section']):04d}.html#f{f.get('block') or 1}"
    return ''


def group_of(meta: dict, e: dict) -> dict:
    return next((g for g in meta['groups'] if g['id'] == e['group']), {'id': e['group'], 'title': e['group'], 'colour': CANDIDATE_COLOR})


def element_card_html(meta: dict, e: dict, files: list[dict], props: list[dict]) -> str:
    g = group_of(meta, e)
    per = next((q['title'] for q in meta['periods'] if q['n'] == e['period']), str(e['period']))
    parts = [f'<dl class="v"><dt>number</dt><dd>{esc(num_label(e))}</dd><dt>state</dt><dd>{esc(state_label(e))}</dd>'
             f'<dt>group</dt><dd>{esc(g["title"])}</dd><dt>period</dt><dd>{esc(per)}</dd>']
    if e['family'] and e['family'] != 'other':
        parts.append(f'<dt>family</dt><dd>{esc(e["family"])}</dd>')
    if e['title'] and e['title'] != e['name']:
        parts.append(f'<dt>title</dt><dd>{esc(e["title"])}</dd>')
    if e['analogy']:
        a = e['analogy']
        parts.append(f'<dt>chemical analogy</dt><dd>like {esc(a["name"])} ({esc(a["sym"])}'
                     f'{", Z=" + str(a["z"]) if a["z"] else ""}){": " + esc(a["why"]) if a["why"] else ""}'
                     ' <span class="k">(a lens only; it never replaces the number or symbol)</span></dd>')
    if e['note']:
        parts.append(f'<dt>note</dt><dd>{esc(e["note"])}</dd>')
    parts.append('</dl>')
    if e['values']:
        parts.append('<h2>Unsettled values, side by side</h2><div class="pt-vals">')
        for i, v in enumerate(e['values'], 1):
            ev = ''.join(f'<li><code>{esc(k)}</code></li>' for k in v['evidence'])
            parts.append(f'<div class="pt-val"><p class="k">form {i}{" · " + str(v["count"]) + " files" if v["count"] else ""}</p>'
                         f'<p class="pt-v"><code>{esc(v["value"])}</code></p>{"<ul class=pt-ev>" + ev + "</ul>" if ev else ""}</div>')
        parts.append('</div>')
    shown = [q for q in props if e['props'].get(q['key']) is not None]
    if shown:
        parts.append('<h2>Properties</h2><table><tbody>')
        for q in shown:
            parts.append(f'<tr><th scope="row">{esc(q["label"])}</th><td>{esc(e["props"][q["key"]])}'
                         f'{" " + esc(q["unit"]) if q["unit"] else ""}</td></tr>')
        parts.append('</tbody></table>')
    parts.append('<h2>Evidence keys</h2>')
    keys = e['evidence'] + e['keys']
    parts.append('<ul class="pt-ev">' + ''.join(f'<li><code>{esc(k)}</code></li>' for k in keys) + '</ul>'
                 if keys else '<p class="k">No evidence key given for this element in the input.</p>')
    parts.append(f'<h2>Files ({len(files)})</h2>')
    if files:
        parts.append('<ul class="pt-files">')
        for f in files:
            href = file_link(f, '../')
            label = f'{esc(f["repo"])}/{esc(f["path"])}'
            parts.append(f'<li><a class="pt-file" href="{esc(href)}">{label}<span class="k">{esc(f["title"])}'
                         f' · {f["lines"]} lines</span></a></li>' if href else f'<li>{label}</li>')
        parts.append('</ul>')
    else:
        parts.append('<p class="k">No Explore Code file is mapped to this element yet.</p>')
    return ''.join(parts)


def fixture_note(meta: dict) -> str:
    if meta['fixture']:
        return ('<p class="pt-fix k">Fixture data: built from star-maker/PERIODIC-TABLE.md and exact file-name matches '
                'in build_graph.json, until the mapper\'s periodic.json is available.</p>')
    return ''


def tile(e: dict) -> str:
    cls = 'pt-el' + (' pt-cand' if e['candidate'] else '') + (' pt-un' if e['state'] == 'unsettled' else '')
    extra = ', candidate' if e['candidate'] else (', unsettled' if e['state'] == 'unsettled' else '')
    return (f'<a class="{cls}" href="{esc(e["page"])}" data-sym="{esc(e["sym"])}" aria-label="{esc(e["sym"])} {esc(e["name"][:60])}{extra}">'
            f'<span class="pt-n">{esc("?" if e["candidate"] else (e["n"] if e["n"] is not None else ""))}</span>'
            f'<b>{esc(e["sym"])}</b></a>')


def render_index(meta, elements, props, cols, periods, furnace: bool) -> str:
    title = 'Periodic table of the code estate — GlobalGrid2050 Explore Code'
    cnt = lambda st: sum(1 for e in elements if e['state'] == st)
    lead = (f'{len(elements)} elements: {sum(1 for e in elements if not e["candidate"])} numbered '
            f'({cnt("settled")} settled, {cnt("unsettled")} unsettled) and {cnt("candidate")} candidate proposals. '
            'Columns are groups, rows are periods. Tap an element for its card.')
    out = [HEAD.format(title=esc(title), desc=esc(lead)),
           header([('Explore Code', '../index.html'), ('Periodic table', '')], 'Periodic table of the code estate', esc(lead)),
           '<main>', fixture_note(meta)]
    has_analogy = any(e['analogy'] and e['analogy']['z'] for e in elements)
    out.append('<div class="pt-bar">'
               '<div class="pt-seg" role="group" aria-label="View">'
               '<button type="button" class="pt-btn" data-view="estate" aria-pressed="true">Estate elements</button>'
               f'<button type="button" class="pt-btn" data-view="chem" aria-pressed="false"{"" if has_analogy else " disabled title=\"No chemical analogy in the input yet\""}>Chemical analogy</button></div>'
               '<label class="pt-lab">Colour by <select id="pt-color" class="pt-sel"><option value="group">Group</option>'
               '<option value="state">State</option>'
               + ''.join(f'<option value="p:{esc(q["key"])}">{esc(q["label"])}</option>' for q in props)
               + '</select></label>'
               + ('<a class="pt-btn pt-link" href="furnace/index.html">Furnace: 118 experiments</a>' if furnace else '')
               + '</div>')
    out.append('<div id="pt-legend" class="pt-legend" aria-live="polite"></div>'
               '<p class="k pt-hint">The table scrolls inside its own frame: drag sideways and down. Period 4 holds most elements.</p>')
    tmpl = 'var(--ph) ' + ' '.join(f'{c["tiles"] * (TILE + GAP) - GAP + 8}px' for c in cols)
    out.append('<div class="pt-frame" id="pt-frame" tabindex="0" role="region" aria-label="Periodic table (scrolls inside this frame)">'
               f'<div class="pt-grid" id="pt-estate" style="grid-template-columns:{tmpl}">'
               '<span class="pt-corner"></span>')
    for i, c in enumerate(cols):
        n = sum(1 for e in elements if e['group'] == c['id'])
        out.append(f'<p class="pt-head" style="grid-column:{i + 2};--c:{c["colour"]}" title="{esc(c["title"])}">'
                   f'{esc(c["title"])} <span class="k">{n}</span></p>')
    for j, q in enumerate(periods):
        out.append(f'<p class="pt-per" style="grid-row:{j + 2}"><b>{q["n"]}</b> {esc(q["title"])}</p>')
    colour = {c['id']: c['colour'] for c in cols}
    for i, c in enumerate(cols):
        for j, q in enumerate(periods):
            items = sorted([e for e in elements if e['group'] == c['id'] and e['period'] == q['n']], key=order_key)
            if items:
                out.append(f'<div class="pt-cellg" style="grid-column:{i + 2};grid-row:{j + 2};--c:{colour[c["id"]]}">'
                           + ''.join(tile(e) for e in items) + '</div>')
    out.append('</div><div class="pt-grid pt-chem" id="pt-chem" hidden></div></div>')
    out.append('<p class="k">Legend: a dot marks an unsettled element; a dashed edge and "?" mark a CANDIDATE proposal (no number).</p>')
    out.append('<div id="pt-card" class="pt-card" role="dialog" aria-modal="true" aria-labelledby="pt-card-h" hidden>'
               '<div class="pt-card-in"><button type="button" class="pt-btn pt-x" id="pt-x" aria-label="Close card">Close</button>'
               '<div id="pt-card-body"></div></div></div>')
    out.append('<noscript><h2>All elements</h2><p class="k">Every tile above is a link to its element page. '
               'The same list, by number (CANDIDATE proposals last):</p><ol class="pt-list">')
    for e in sorted(elements, key=order_key):
        out.append(f'<li><a href="{esc(e["page"])}">{esc(e["sym"])} {esc(e["name"][:60])}</a> {esc(num_label(e))}'
                   f'{" unsettled" if e["state"] == "unsettled" else ""}</li>')
    out.append('</ol></noscript>')
    links = [('llms-periodic.txt', 'llms-periodic.txt'), ('element-index.json', 'element-index.json')]
    if furnace:
        links.insert(0, ('furnace/index.html', 'Furnace gallery: 118 electron/positron experiments'))
    out.append('<h2>More</h2><p>' + ' '.join(f'<a class="pt-tap" href="{h}">{esc(t)}</a>' for h, t in links) + '</p>')
    out.append('</main>')
    rules = {}
    light = []
    for e in elements:
        an = None
        if e['analogy']:
            a = e['analogy']
            rid = a.get('rule') or a['why']
            if rid:
                rules.setdefault(rid, a['why'])
            an = [a['z'], a['sym'], a['name'], rid or '']
        light.append([e['sym'], e['n'], 1 if e['candidate'] else 0, e['name'], e['state'], e['group'], e['period'],
                      an, e['page'], len(e['files'])])
    pv = {q['key']: [e['props'].get(q['key']) for e in elements] for q in props}
    data = {'cols': ['sym', 'n', 'cand', 'name', 'state', 'group', 'period', 'analogy', 'page', 'nfiles'],
            'elements': light, 'props': props, 'pv': pv, 'groups': meta['groups'], 'periods': meta['periods'],
            'rules': rules, 'candidateColor': CANDIDATE_COLOR, 'stateText': STATE_TEXT,
            'chem': [[c['z'], c['sym'], c['name'], c['row'], c['col']] for c in CHEM]}
    js = json.dumps(data, ensure_ascii=False, separators=(',', ':')).replace('</', '<\\/')
    out.append(f'<script id="pt-data" type="application/json">{js}</script><script src="periodic.js" defer></script>')
    out.append(footer(meta))
    return ''.join(out)


def footer(meta: dict) -> str:
    src = 'fixture' if meta['fixture'] else (meta['schema'] or 'periodic.json')
    return (f'<footer><p class="k">Source: {esc(src)}{" · cut " + esc(meta["cut"]) if meta["cut"] else ""}. '
            'Numbers and symbols are the estate\'s own; CANDIDATE elements are proposals and have no number.</p></footer></body></html>')


def render_element(meta, e, props, files, prev_e, next_e) -> str:
    colour = group_of(meta, e)['colour']
    title = f'{e["sym"]} {e["name"]} — periodic table — GlobalGrid2050 Explore Code'
    lead = f'{num_label(e)} · {group_of(meta, e)["title"]} · {state_label(e)} · {len(files)} files'
    return ''.join([
        HEAD.format(title=esc(title), desc=esc(f'{e["name"]}: {lead}')),
        header([('Explore Code', '../index.html'), ('Periodic table', 'index.html'), (e['sym'], '')],
               f'<span class="pt-big{" pt-cand" if e["candidate"] else ""}" style="--c:{colour}">{esc(e["sym"])}</span> {esc(e["name"])}', esc(lead)),
        '<main>', fixture_note(meta), element_card_html(meta, e, files, props),
        f'<nav class="pt-nav" aria-label="Elements"><a class="pt-tap" href="{esc(prev_e["page"])}">Previous: {esc(prev_e["sym"])}</a>'
        f'<a class="pt-tap" href="index.html#{esc(e["sym"])}">Back to the table</a>'
        f'<a class="pt-tap" href="{esc(next_e["page"])}">Next: {esc(next_e["sym"])}</a></nav></main>', footer(meta)])


def render_llms(meta, elements, props, files_by_id, base: str, furnace: bool) -> str:
    L = ['# Periodic table of the code estate (Explore Code)', '',
         f'> {len(elements)} elements. A numbered element keeps the estate\'s own symbol and number; UNSETTLED means it',
         '> exists in more than one form in the code; CANDIDATE is a proposal with no number. Columns are groups (roles),',
         '> rows are periods. The chemical analogy is a lens only.',
         f'> Source: {"fixture (star-maker/PERIODIC-TABLE.md + exact file-name matches)" if meta["fixture"] else (meta["schema"] or "periodic.json")}'
         f'{", cut " + meta["cut"] if meta["cut"] else ""}.',
         '', f'- Table: {base}periodic/index.html', f'- Lookup JSON ({SCHEMA_INDEX}, file id -> symbols): {base}periodic/element-index.json',
         f'- Card data JSON: {base}periodic/cards.json']
    if furnace:
        L.append(f'- Furnace experiments (118 chemical elements, electron/positron): {base}periodic/furnace/index.html')
    L.append('')
    for e in sorted(elements, key=order_key):
        g = group_of(meta, e)
        L.append(f'## {e["sym"]} — {e["name"]}')
        L.append(f'number: {num_label(e)} | group: {g["id"]} | period: {e["period"]} | state: {state_label(e)} | files: {len(e["files"])}')
        if e['analogy']:
            L.append(f'chemical analogy: like {e["analogy"]["name"]} ({e["analogy"]["sym"]})' + (f' — {e["analogy"]["why"]}' if e['analogy']['why'] else ''))
        for i, v in enumerate(e['values'], 1):
            L.append(f'value {i}: {v["value"]}' + (f' ({v["count"]} files)' if v['count'] else '') + (f' [{"; ".join(v["evidence"])}]' if v['evidence'] else ''))
        pr = [f'{q["label"]}={e["props"][q["key"]]}' for q in props if e['props'].get(q['key']) is not None]
        if pr:
            L.append('properties: ' + '; '.join(pr))
        for k in e['evidence'] + e['keys']:
            L.append(f'evidence: {k}')
        sample = [files_by_id[i] for i in e['files'][:5] if i in files_by_id]
        for f in sample:
            L.append(f'file: {f["repo"]}/{f["path"]} -> {base}{file_link(f, "")}')
        if len(e['files']) > len(sample):
            L.append(f'(+{len(e["files"]) - len(sample)} more files on the element page)')
        L.append(f'page: {base}periodic/{e["page"]}')
        L.append('')
    return '\n'.join(L)


def build_index_json(meta, elements, files_by_id) -> dict:
    files, sections = {}, {}
    for e in elements:
        for fid in e['files']:
            files.setdefault(str(fid), []).append(e['sym'])
            f = files_by_id.get(fid)
            if f and f.get('section'):
                lst = sections.setdefault(str(f['section']), [])
                if e['sym'] not in lst:
                    lst.append(e['sym'])
    return {'schema': SCHEMA_INDEX, 'page': 'periodic/index.html',
            'elements': {e['sym']: {'n': e['n'], 'name': e['name'], 'state': e['state'], 'group': e['group'],
                                    'color': group_of(meta, e)['colour'], 'url': 'periodic/' + e['page'],
                                    'analogy': e['analogy']['sym'] if e['analogy'] and e['analogy']['z'] else None}
                         for e in elements},
            'files': files, 'sections': sections}


def build_cards_json(elements, files_by_id) -> dict:
    repos: list[str] = []
    out = {}
    for e in elements:
        fl = []
        for fid in e['files']:
            f = files_by_id.get(fid)
            if not f:
                continue
            if f['repo'] not in repos:
                repos.append(f['repo'])
            fl.append([fid, repos.index(f['repo']), f['path'], f['section'], f['block'], f['lines'], f['title']])
        out[e['sym']] = {'title': e['title'], 'note': e['note'], 'family': e['family'], 'values': e['values'],
                         'evidence': e['evidence'] + e['keys'], 'files': fl}
    return {'schema': 'explore-periodic-cards-v1', 'repos': repos,
            'file_cols': ['id', 'repo', 'path', 'section', 'block', 'lines', 'title'], 'elements': out}