GLOBALGRID2050 / EXPLORE CODE

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

Visualise

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

614 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1173 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. Visualise storage · cosmic / tools/explore/visualise.py lines 373–986

Visualise

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

storagecosmic / tools/explore/visualise.py · lines 373–986 of 986 (continued from section 1172) · Entry point · pattern render_page (shared by 2 files)

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


# ---------------------------------------------------------------- layouts
def layout_pipeline(files, order_key):
    """Columns by stage; inside each column repos stacked (largest first), files on a dot grid."""
    xy = [None] * len(files)
    cols, groups = [], []
    H = 0
    for si, st in enumerate(STAGES):
        x0 = P_MARGIN + si * (P_COLW + P_GAP)
        members = [i for i, f in enumerate(files) if f['stage'] == st]
        by_repo = {}
        for i in members:
            by_repo.setdefault(files[i]['repo'], []).append(i)
        y = P_MARGIN + 60
        for repo in sorted(by_repo, key=lambda r: (-len(by_repo[r]), r)):
            ids = sorted(by_repo[repo], key=order_key)
            rows = (len(ids) + P_COLS - 1) // P_COLS
            gy = y
            y += P_HEAD
            for k, i in enumerate(ids):
                xy[i] = (x0 + (k % P_COLS) * P_DOT + P_DOT // 2, y + (k // P_COLS) * P_DOT + P_DOT // 2)
            h = P_HEAD + rows * P_DOT
            groups.append([si, x0, gy, P_COLW, h, repo, len(ids)])
            y += rows * P_DOT + P_GROUP_GAP
        cols.append([x0, x0 + P_COLW, STAGE_TITLES[si], len(members)])
        H = max(H, y)
    W = P_MARGIN * 2 + 4 * P_COLW + 3 * P_GAP
    return xy, {'W': W, 'H': H + P_MARGIN, 'cols': cols, 'groups': groups}


def layout_map(files, order_key):
    """Repos packed as circles (area ~ lines), top-level folders packed inside, files on a sunflower."""
    golden = math.pi * (3 - math.sqrt(5))
    by_repo = {}
    for i, f in enumerate(files):
        top = f['path'].split('/')[0] if '/' in f['path'] else '/'
        by_repo.setdefault(f['repo'], {}).setdefault(top, []).append(i)
    repo_circles = []  # [x, y, r, repo, folders]
    for repo in sorted(by_repo):
        folders = []
        for top in sorted(by_repo[repo]):
            ids = sorted(by_repo[repo][top], key=order_key)
            n = len(ids)
            lines = sum(max(1, files[i]['lines']) for i in ids)
            r = max(M_K * math.sqrt(lines), M_DOT * math.sqrt(n) * 0.62 + M_DOT)
            folders.append([0.0, 0.0, r + M_PAD, top, ids, r])
        folders.sort(key=lambda c: (-c[2], c[3]))
        R = pack_siblings(folders) + M_PAD * 3
        repo_circles.append([0.0, 0.0, R, repo, folders])
    repo_circles.sort(key=lambda c: (-c[2], c[3]))
    Rall = pack_siblings([c for c in repo_circles]) + 40
    xy = [None] * len(files)
    repos_out, dirs_out = [], []
    for rc in sorted(repo_circles, key=lambda c: c[3]):
        rx, ry = rc[0] + Rall, rc[1] + Rall
        repos_out.append([round(rx), round(ry), round(rc[2]), rc[3]])
        for fc in rc[4]:
            fx, fy, ids, r = rx + fc[0], ry + fc[1], fc[4], fc[5]
            dirs_out.append([round(fx), round(fy), round(r), fc[3]])
            n = len(ids)
            for k, i in enumerate(ids):
                rho = (r - M_DOT * 0.5) * math.sqrt((k + 0.5) / n)
                th = k * golden
                xy[i] = (round(fx + rho * math.cos(th), 1), round(fy + rho * math.sin(th), 1))
    return xy, {'W': round(2 * Rall), 'H': round(2 * Rall), 'repos': repos_out, 'dirs': dirs_out}


# ---------------------------------------------------------------- compile
def compile_visual(g, scale=1.0, ov_manifest=None):
    """ov_manifest: {overlay name: bytes of its ov-<name>.json}, the only overlay data in graph.json.
    scale < 1 shortens the text fields (achieves, why, title, defines) to keep graph.json under budget."""
    files = [dict(f) for f in g['files']]
    tmax = {k: max(40, int(n * scale)) for k, n in TEXT_MAX.items()}
    dmax = max(3, int(DEFINES_MAX * scale))
    n = len(files)
    role_list = g.get('roles') or [{'id': a, 'title': b, 'colour': c} for a, b, c in ROLES]
    roles = [[r['id'], r.get('title', r['id']), r.get('colour') or dict((a, c) for a, _, c in ROLES).get(r['id'], '#4c5a65')]
             for r in role_list]
    role_ix = {r[0]: i for i, r in enumerate(roles)}
    if 'other' not in role_ix:
        role_ix['other'] = len(roles)
        roles.append(['other', 'Other', '#4c5a65'])
    topics = [[t['id'], t.get('title', t['id']), t.get('sections', 0)] for t in g.get('topics', [])]
    known = {t[0] for t in topics}
    for t in sorted({f.get('topic', '') for f in files} - known):
        topics.append([t, TOPIC_TITLES.get(t, t or 'none'), 0])
    for i, t in enumerate(topics):
        t.append(TOPIC_COLOURS[i % len(TOPIC_COLOURS)])
    topic_ix = {t[0]: i for i, t in enumerate(topics)}
    for f in files:
        if f.get('stage') not in STAGES:
            f['stage'] = 'unknown'
        if f.get('role') not in role_ix:
            f['role'] = 'other'

    def order_key(i):
        f = files[i]
        return (role_ix[f['role']], topic_ix.get(f.get('topic', ''), 0), f['path'])

    pxy, pipe = layout_pipeline(files, order_key)
    mxy, emap = layout_map(files, order_key)
    repo_names = sorted({f['repo'] for f in files})
    repo_ix = {r: i for i, r in enumerate(repo_names)}
    repo_lines = {}
    repo_files = {}
    for f in files:
        repo_lines[f['repo']] = repo_lines.get(f['repo'], 0) + int(f.get('lines') or 0)
        repo_files[f['repo']] = repo_files.get(f['repo'], 0) + 1
    repos = [[r, slug(r), repo_lines[r], repo_files[r]] for r in repo_names]
    for grp in pipe['groups']:
        grp[5] = repo_ix[grp[5]]
    for rc in emap['repos']:
        rc[3] = repo_ix[rc[3]]
    dirs, dir_ix = [], {}
    pat_count = {}
    for f in files:
        p = f.get('pattern') or ''
        if p:
            pat_count[p] = pat_count.get(p, 0) + 1
    pats = sorted((k for k, c in pat_count.items() if c >= 2), key=lambda k: (-pat_count[k], k))
    pat_ix = {k: i for i, k in enumerate(pats)}
    width = 4
    for s in g.get('sections', []):
        m = re.match(r's/(\d+)\.html', s.get('url', ''))
        if m:
            width = len(m.group(1))
            break
    col = {k: [] for k in ('r', 'd', 'b', 't', 'o', 's', 'l', 'sec', 'blk', 'ti', 'a', 'w', 'df', 'p', 'en', 're',
                           'px', 'py', 'mx', 'my')}
    tri = {True: 1, False: 0, None: 2}
    for i, f in enumerate(files):
        d, b = posixpath.split(f['path'])
        if d not in dir_ix:
            dir_ix[d] = len(dirs)
            dirs.append(d)
        title = clip(f.get('title') or humanise(f['path']), tmax['title'])
        col['r'].append(repo_ix[f['repo']])
        col['d'].append(dir_ix[d])
        col['b'].append(b)
        col['t'].append(topic_ix.get(f.get('topic', ''), 0))
        col['o'].append(role_ix[f['role']])
        col['s'].append(STAGES.index(f['stage']))
        col['l'].append(int(f.get('lines') or 0))
        col['sec'].append(int(f.get('section') or 0))
        col['blk'].append(int(f.get('block') or 0))
        col['ti'].append('' if title == humanise(f['path']) else title)
        col['a'].append(clip(f.get('achieves'), tmax['achieves']))
        col['w'].append(clip(f.get('why'), tmax['why']))
        col['df'].append(' '.join(str(x) for x in (f.get('defines') or [])[:dmax]))
        col['p'].append(pat_ix.get(f.get('pattern') or '', -1))
        col['en'].append(tri.get(f.get('entry'), 2))
        col['re'].append(tri.get(f.get('reachable'), 2))
        col['px'].append(pxy[i][0])
        col['py'].append(pxy[i][1])
        mx, my = mxy[i]
        col['mx'].append(int(mx) if mx == int(mx) else mx)
        col['my'].append(int(my) if my == int(my) else my)
    edges = set()
    for i, f in enumerate(files):
        for j in f.get('imports') or []:
            if isinstance(j, int) and 0 <= j < n and j != i:
                edges.add((i, j))
        for j in f.get('dependents') or []:
            if isinstance(j, int) and 0 <= j < n and j != i:
                edges.add((j, i))
    flat = []
    for a, b in sorted(edges):
        flat += [a, b]
    return {
        'schema': 'explore-visual-v1', 'gen': GENERATOR_VERSION, 'ov': ov_manifest or {},
        'cut': g.get('cut', ''), 'base': g.get('base', ''),
        'adapter': g.get('adapter', ''), 'sw': width,
        'roles': roles, 'topics': topics,
        'stages': [[STAGES[i], STAGE_TITLES[i], STAGE_COLOURS[i]] for i in range(4)],
        'repos': repos, 'dirs': dirs,
        'pats': [[k, pattern_colour(k), pat_count[k]] for k in pats], 'grey': UNIQUE_GREY,
        'n': col, 'e': flat, 'pipe': pipe, 'map': emap,
    }


# ---------------------------------------------------------------- optional overlays (lazy files)
# Each overlay becomes visual/ov-<name>.json: a small id -> value map (arrays indexed by graph.json file
# id, -1 = no value) plus its own legend. graph.json carries only a manifest {name: bytes}; the page
# fetches an overlay the first time its control is used. No overlay copies graph data or code.
CLARITY_COLOURS = {'core': '#00ff88', 'copy': '#ffae00', 'via': '#66ccff', 'unreached': '#4c5a65'}
PERIOD_COLOURS = ['#00ffff', '#66ccff', '#00ff88', '#ffff00', '#ffae00', '#ff6666', '#ffd24a', '#a6adbb']
LAW_COLOURS = TOPIC_COLOURS


def warn(msg):
    print('WARNING: visual overlay: %s (skipped)' % msg, file=sys.stderr)


def _load_json(p):
    with open(p, encoding='utf-8') as fh:
        return json.load(fh)


def key_index(g):
    return {(f['repo'], f['path']): i for i, f in enumerate(g['files'])}


def aligner(g, cut, n, keys=None):
    """A function overlay-id -> graph-id (or None), or None when the overlay cannot be lined up.

    keys: list of 'repo@commit:path' per overlay id (lab keys.json): matched by repo/path, any cut.
    Without keys the overlay must come from the same cut and have the same file count."""
    if keys:
        kx = key_index(g)
        m = []
        for k in keys:
            repo, _, rest = str(k).partition('@')
            m.append(kx.get((repo, rest.partition(':')[2])))
        return lambda i: m[i] if isinstance(i, int) and 0 <= i < len(m) else None
    N = len(g['files'])
    if cut and g.get('cut') and cut != g.get('cut'):
        return None
    if n is not None and n != N:
        return None
    return lambda i: i if isinstance(i, int) and 0 <= i < N else None


def _remap_col(col, al, N, default=-1):
    out = [default] * N
    for i, v in enumerate(col):
        j = al(i)
        if j is not None:
            out[j] = v
    return out


def read_lab(d, g):
    """Lab directory -> {'community': ov, 'drift': ov, 'wafer': ov} for the parts that load and line up."""
    out, N = {}, len(g['files'])
    keys = None
    try:
        keys = _load_json(os.path.join(d, 'keys.json')).get('k')
    except (OSError, ValueError) as e:
        warn('lab keys.json not readable (%s); matching lab overlays by id' % e)
    try:
        c = _load_json(os.path.join(d, 'communities.json'))
        al = aligner(g, c.get('cut'), c.get('n'), keys)
        if al is None:
            warn('communities.json is from another cut')
        else:
            col = _remap_col(c['cols']['c'], al, N)
            hdr = c['legend']['c']
            present = {}
            for v in col:
                if v >= 0:
                    present[v] = present.get(v, 0) + 1
            rows = []
            for r in c['legend']['rows']:
                r = dict(zip(hdr, r))
                if r['id'] in present:
                    hub = al(r.get('hub_file'))
                    rows.append([r['id'], clip(r.get('label') or 'community %d' % r['id'], 60),
                                 pattern_colour('community:%d' % r['id']), present[r['id']], -1 if hub is None else hub])
            rows.sort(key=lambda r: (-r[3], r[0]))
            for k, r in enumerate(rows[:len(TOPIC_COLOURS)]):  # the largest get the distinct site palette
                r[2] = TOPIC_COLOURS[k]
            ix = {r[0]: k for k, r in enumerate(rows)}
            out['community'] = {'kind': 'community', 'rules': c.get('rules', ''), 'cut': c.get('cut', ''),
                                'cats': [[r[1], r[2], r[4]] for r in rows],
                                'v': [ix.get(v, -1) for v in col]}
    except (OSError, ValueError, KeyError, TypeError) as e:
        warn('communities.json: %s' % e)
    try:
        dr = _load_json(os.path.join(d, 'drift.json'))
        al = aligner(g, dr.get('cut'), dr.get('n'), keys)
        if al is None:
            warn('drift.json is from another cut')
        else:
            fam = _remap_col(dr['cols']['fam'], al, N)
            e, flat = dr.get('edges') or [], []
            for k in range(0, len(e) - 2, 3):
                a, b = al(e[k]), al(e[k + 1])
                if a is not None and b is not None and a != b:
                    flat += [a, b, int(e[k + 2])]
            safe = sorted(j for j in (al(i) for i in dr.get('safe_review') or []) if j is not None)
            out['drift'] = {'kind': 'drift', 'rules': dr.get('rules', ''), 'cut': dr.get('cut', ''),
                            'fam': fam, 'e': flat, 'safe': safe}
    except (OSError, ValueError, KeyError, TypeError) as e:
        warn('drift.json: %s' % e)
    try:
        w = _load_json(os.path.join(d, 'wafer.json'))
        hdr = w['legend']['dies']
        nums = {}
        for r in w['legend']['rows']:
            r = dict(zip(hdr, r))
            nums[r['repo']] = int(r['repo_number'])
        out['wafer'] = {'kind': 'wafer', 'rules': w.get('rules', ''), 'cut': w.get('cut', ''), 'numbers': nums}
    except (OSError, ValueError, KeyError, TypeError) as e:
        warn('wafer.json: %s' % e)
    return out


def wafer_numbers(g, lab_numbers):
    """Permanent repo numbers: build_graph repos[].number wins, then the lab's; unseen repos are appended
    after the highest number in name order (Modular Star: assigned once, never renumbered)."""
    nums = dict(lab_numbers or {})
    for r in g.get('repos') or []:
        if isinstance(r.get('number'), int):
            nums[r['repo']] = r['number']
    if not nums:
        return None
    nxt = max(nums.values()) + 1
    for repo in sorted({f['repo'] for f in g['files']} - set(nums)):
        nums[repo] = nxt
        nxt += 1
    return {k: nums[k] for k in sorted({f['repo'] for f in g['files']})}


def read_clarity(p, g):
    c = _load_json(p)
    al = aligner(g, c.get('cut'), len(c.get('file_category') or []))
    if al is None:
        warn('%s is from another cut or file count' % p)
        return None
    cats = list(c.get('categories') or sorted(set(c['file_category'])))
    ix = {k: i for i, k in enumerate(cats)}
    titles = c.get('titles') or {}
    return {'kind': 'clarity', 'rules': c.get('schema', ''), 'cut': c.get('cut', ''),
            'cats': [[titles.get(k, k), CLARITY_COLOURS.get(k, TOPIC_COLOURS[i % len(TOPIC_COLOURS)])]
                     for i, k in enumerate(cats)],
            'v': _remap_col([ix.get(x, -1) for x in c['file_category']], al, len(g['files']))}


def read_periodic(p, g):
    d = _load_json(p)
    files = d.get('files') or {}
    al = aligner(g, d.get('cut'), d.get('counts', {}).get('files'))
    if al is None:
        warn('%s is from another cut or file count' % p)
        return None
    by_key = {e['key']: e for e in d.get('elements') or []}
    periods = {pp['n']: pp.get('title', str(pp['n'])) for pp in (d.get('axes') or {}).get('periods') or []}
    used, col = [], [-1] * len(g['files'])
    uix = {}
    for sid in sorted(files, key=lambda s: int(s)):
        j = al(int(sid))
        ek = (files[sid] or {}).get('element')
        if j is None or ek not in by_key:
            continue
        if ek not in uix:
            uix[ek] = len(used)
            used.append(ek)
        col[j] = uix[ek]
    els = []
    for ek in used:
        e = by_key[ek]
        an = e.get('analogue') or {}
        els.append([e.get('symbol') or '', e.get('number'), clip(e.get('title') or e.get('name') or ek, 60),
                    int(e.get('period') or 0), e.get('status') or ('numbered' if e.get('number') else 'candidate'),
                    an.get('symbol') or '', an.get('name') or ''])
    pers = sorted({e[3] for e in els})
    return {'kind': 'periodic', 'rules': d.get('schema', ''), 'cut': d.get('cut', ''),
            'cats': [[('%d · %s' % (n, periods.get(n, 'period %d' % n))), PERIOD_COLOURS[(n - 1) % len(PERIOD_COLOURS)], n]
                     for n in pers],
            'els': els, 'v': col}


def read_categorical(d, g, kind='laws'):
    """Generic per-file classes. Accepted shapes (first that fits):
      {"file_category"|"file_law": [class per file id], "titles"?: {class: title}, "cut"?}
      {"files": {"<id>": "class" | {"law"|"class"|"category": "class"}}, "titles"?, "cut"?}
      {"cols": {"<name>": [class per id]}, "cut"?, "n"?}   (lab overlay; first column)"""
    col = d.get('file_category') or d.get('file_law')
    if col is None and isinstance(d.get('files'), dict):
        n = d.get('n') or (max(int(k) for k in d['files']) + 1 if d['files'] else 0)
        col = [None] * n
        for k, v in d['files'].items():
            if isinstance(v, dict):
                v = v.get('law') or v.get('class') or v.get('category')
            col[int(k)] = v
    if col is None and isinstance(d.get('cols'), dict) and d['cols']:
        col = d['cols'][sorted(d['cols'])[0]]
    if not isinstance(col, list):
        return None
    al = aligner(g, d.get('cut'), d.get('n', len(col)) if 'files' not in d else None)
    if al is None:
        return None
    vals = sorted({str(x) for x in col if x is not None and x != -1 and x != ''})
    ix = {k: i for i, k in enumerate(vals)}
    titles = d.get('titles') or {}
    return {'kind': kind, 'rules': d.get('rules') or d.get('schema', ''), 'cut': d.get('cut', ''),
            'cats': [[str(titles.get(k, k)), LAW_COLOURS[i % len(LAW_COLOURS)]] for i, k in enumerate(vals)],
            'v': _remap_col([ix.get(str(x), -1) if x is not None else -1 for x in col], al, len(g['files']))}


def read_laws(p, g):
    paths = sorted(glob.glob(os.path.join(p, '*.json'))) if os.path.isdir(p) else [p]
    for q in paths:
        try:
            ov = read_categorical(_load_json(q), g)
        except (OSError, ValueError, KeyError, TypeError) as e:
            warn('%s: %s' % (q, e))
            continue
        if ov and ov['cats']:
            ov['source'] = os.path.basename(q)
            return ov
    warn('no laws overlay with per-file classes for this cut in %s' % p)
    return None


def read_faraday(p, g):
    """Faraday pulse (laws FA, optional): the measured rate at which a user changed when the file it uses changed,
    from laws.json (explore laws, tools/explore/laws). Only the numbers travel (a few hundred bytes); the users come
    from graph.json's own edges in the browser. Used only when the law HOLDS and its counts are present."""
    d = _load_json(p)
    fa = ((d.get('laws') or {}).get('FA') or {}) if isinstance(d, dict) else {}
    n = fa.get('numbers') or {}
    k, c = n.get('used_changed_user_changed'), n.get('used_changed_user_same')
    if fa.get('verdict') != 'HOLDS' or not isinstance(k, int) or not isinstance(c, int) or k + c <= 0:
        warn('%s: no Faraday (FA) law that holds, with counts' % p)
        return None
    return {'kind': 'faraday', 'k': k, 'n': k + c, 'p': round(k / float(k + c), 4),
            'lift': n.get('lift'), 'pairs': n.get('replicated_pairs'), 'law': fa.get('law', ''),
            'cut': d.get('graph_cut', ''), 'source': os.path.basename(p) + ' FA'}


def load_overlays(g, lab=None, clarity=None, periodic=None, laws=None, faraday=None):
    ovs = {}
    if lab:
        if os.path.isdir(lab):
            ovs.update(read_lab(lab, g))
        else:
            warn('lab directory %s not found' % lab)
        if 'wafer' in ovs:
            nums = wafer_numbers(g, ovs['wafer']['numbers'])
            if nums:
                ovs['wafer']['numbers'] = nums
            else:
                del ovs['wafer']
    for name, p, fn in (('clarity', clarity, read_clarity), ('periodic', periodic, read_periodic),
                        ('laws', laws, read_laws), ('faraday', faraday, read_faraday)):
        if not p:
            continue
        if not os.path.exists(p):
            warn('%s input %s not found' % (name, p))
            continue
        try:
            ov = fn(p, g)
        except (OSError, ValueError, KeyError, TypeError) as e:
            warn('%s: %s' % (p, e))
            ov = None
        if ov:
            ovs[name] = ov
    return ovs


# ---------------------------------------------------------------- page
def read_asset(name):
    with open(os.path.join(ASSETS, name), encoding='utf-8') as fh:
        return fh.read()


OV_MODE_TITLES = {'community': 'community', 'clarity': 'clarity group', 'periodic': 'periodic element', 'laws': 'laws'}


def human_bytes(n):
    return '%.1f MB' % (n / 1048576.0) if n >= 1048576 else '%d KB' % max(1, round(n / 1024.0))


def render_page(v, gbytes=0):
    E = lambda s: html.escape(str(s), quote=True)
    top_repos = sorted(v['repos'], key=lambda r: (-r[2], r[0]))[:30]
    repo_list = ''.join('<li><a href="../repos/%s.html">%s</a> (%d lines, %d files)</li>' % (E(r[1]), E(r[0]), r[2], r[3])
                        for r in top_repos)
    topic_list = ''.join('<li><a href="../topics/%s.html">%s</a></li>' % (E(t[0]), E(t[1])) for t in v['topics'] if t[0])
    legend = ''.join('<li data-k="%d"><i style="background:%s"></i>%s</li>' % (i, E(r[2]), E(r[1]))
                     for i, r in enumerate(v['roles']))
    ov = v.get('ov') or {}
    # Overlay controls exist in the page only when their file was written (missing data -> no button).
    ov_options = ''.join('<option value="%s">%s</option>' % (k, E(OV_MODE_TITLES[k])) for k in
                         ('community', 'clarity', 'periodic', 'laws') if k in ov)
    ov_controls = ''
    if 'drift' in ov:
        ov_controls = ('<label class="more" title="Near-copy edges, copy to canonical (d)"><input type="checkbox" id="tdrift"> near copies</label>'
                       '<label class="more" title="Only files not reached from an entry point that have a reachable near copy">'
                       '<input type="checkbox" id="tsafe"> safe review</label>')
    if 'faraday' in ov:
        ov_controls += ('<label class="more" title="Faraday pulse: tap a file and the files that use it light up (p)">'
                        '<input type="checkbox" id="tfaraday"> Faraday pulse</label>')
    wafer_tab = ('<button role="tab" data-view="wafer" title="Wafer: positions from each file\'s permanent key (4)"><span class="k">4 </span>Wafer</button>'
                 if 'wafer' in ov else '')
    page = read_asset('template.html')
    for k, val in (('{{CSS}}', read_asset('app.css')), ('{{JS}}', read_asset('app.js')),
                   ('{{REPO_LIST}}', repo_list), ('{{TOPIC_LIST}}', topic_list), ('{{LEGEND}}', legend),
                   ('{{OV_OPTIONS}}', ov_options), ('{{OV_CONTROLS}}', ov_controls), ('{{WAFER_TAB}}', wafer_tab),
                   ('{{GBYTES}}', '%d' % gbytes), ('{{GSIZE}}', human_bytes(gbytes)), ('{{GEN}}', E(v.get('gen', ''))),
                   ('{{NFILES}}', '%d' % len(v['n']['r'])), ('{{NREPOS}}', '%d' % len(v['repos'])),
                   ('{{NEDGES}}', '%d' % (len(v['e']) // 2)), ('{{CUT}}', E(v['cut']))):
        page = page.replace(k, val)
    return page


README = """# Explore Code visualiser (generator {gen})

`index.html` draws the GlobalGrid2050 code estate ({nfiles} files, {nrepos} repositories, {nedges} resolved
imports) on one canvas, from `graph.json`, which `tools/explore/visualise.py` computes from `../build_graph.json`
(cut {cut}{adapter}). Every coordinate is computed in Python, deterministically; the browser only draws.

Views (keys 1, 2, 3, 4). On phones the page opens on the Estate map, with the legend and the filters folded.

- **Pipeline**: columns Ingest | Transform | Engineering output | Unknown (the build's stage rule), repositories
  stacked inside each column, files as dots. Edges of the hovered or selected file are drawn; "all edges"
  draws them bundled repository to repository.
- **Estate map**: repositories as circles sized by lines, top-level folders inside, files as dots.
- **Flow**: a matrix of import counts between categories of the current colour mode, plus stage to stage.
- **Wafer** (when the lab's permanent repo numbers are given): one die per repository on a hex spiral by its
  permanent number; inside the die each file sits where its own key `repo/path` puts it (first 32 bits of
  sha256, r = sqrt(u), golden-angle theta). The browser computes these positions; nothing per file is stored,
  so an unchanged file never moves when the estate changes.

Colour modes (key c): **role** (default; the palette in build_graph.json `roles`, from the website and Pipeline
News scheme), topic, stage, and **pattern**: files sharing a pattern key get the same stable colour, unique files
are grey, so repeated logic shows as repeated colour across repositories. Legend entries filter.

Optional overlays, each a small file loaded only when its control is first used: community, clarity group,
periodic element and laws colour modes; near-copy (drift) edges and a "safe review" filter (unreached files
that have a reachable near copy: candidates for review, never a deletion list). In this build: {overlays}.

Reachability (key r): entry points are drawn as bright rings and files not reached from any entry point are
hollow and counted as "candidates for review". This is a static reading, never a deletion list.

Search/command bar (key /): a file name, path, repository or defined name; or `repo:NAME`, `topic:ID`,
`role:ID`, `pipeline`, `map`, `flow`, `colour pattern`. Enter, a repository or a topic zooms to the matches.
The URL hash keeps the view, selection, colour mode and filters, so links can be shared, and each selection or
view change is a history step, so Back walks your trail. Click a file to list what it uses and what uses it,
and open its section page. The plain list of topics and repositories stays in the page under the drawing for
screen readers and for no-script browsers.
"""


BUDGET = 1900 * 1024  # bytes of graph.json; text is shortened step by step (deterministically) to fit


OV_NAMES = ('community', 'drift', 'wafer', 'clarity', 'periodic', 'laws', 'faraday')


def write_outputs(g, out, overlays=None):
    overlays = overlays or {}
    os.makedirs(out, exist_ok=True)
    manifest = {}
    for stale in glob.glob(os.path.join(out, 'ov-*.json')):  # same inputs -> same file set
        os.remove(stale)
    for name in OV_NAMES:
        if name not in overlays:
            continue
        data = json.dumps(overlays[name], separators=(',', ':'), ensure_ascii=False, sort_keys=True)
        with open(os.path.join(out, 'ov-%s.json' % name), 'w', encoding='utf-8', newline='\n') as fh:
            fh.write(data)
        manifest[name] = len(data.encode('utf-8'))
    for scale in (1.0, 0.8, 0.6, 0.45, 0.3, 0.0):
        v = compile_visual(g, scale, manifest)
        data = json.dumps(v, separators=(',', ':'), ensure_ascii=False)
        if len(data.encode('utf-8')) <= BUDGET:
            break
    size = len(data.encode('utf-8'))
    with open(os.path.join(out, 'graph.json'), 'w', encoding='utf-8', newline='\n') as fh:
        fh.write(data)
    with open(os.path.join(out, 'index.html'), 'w', encoding='utf-8', newline='\n') as fh:
        fh.write(render_page(v, size))
    with open(os.path.join(out, 'README.md'), 'w', encoding='utf-8', newline='\n') as fh:
        fh.write(README.format(nfiles=len(v['n']['r']), nrepos=len(v['repos']), nedges=len(v['e']) // 2,
                               cut=v['cut'] or 'unknown', gen=GENERATOR_VERSION,
                               adapter='; synthesised from the Parquet tables' if v['adapter'] == 'parquet' else '',
                               overlays=', '.join('ov-%s.json (%d bytes)' % (k, b) for k, b in manifest.items()) or 'none in this build'))
    return v, size


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    src = ap.add_mutually_exclusive_group(required=True)
    src.add_argument('--graph', help='build_graph.json (contract explore-build-graph-v1)')
    src.add_argument('--from-parquet', metavar='DIR', help='explore-code/data directory (adapter)')
    ap.add_argument('--out', required=True, help='output directory, e.g. explore-code/visual')
    ap.add_argument('--dump-graph', help='with --from-parquet: also write the synthesised graph here')
    ap.add_argument('--lab', metavar='DIR', help='optional: lab output dir (communities, drift, wafer, keys.json)')
    ap.add_argument('--clarity', metavar='FILE', help='optional: translator clarity.json')
    ap.add_argument('--periodic', metavar='FILE', help='optional: periodic.json (explore-periodic-v1)')
    ap.add_argument('--laws', metavar='PATH', help='optional: laws overlay file or directory')
    ap.add_argument('--faraday', metavar='FILE', help='optional: laws.json (law FA) for the Faraday pulse')
    ap.add_argument('--version', action='version', version='visualise.py ' + GENERATOR_VERSION)
    a = ap.parse_args(argv)
    if a.graph:
        with open(a.graph, encoding='utf-8') as fh:
            g = json.load(fh)
        if not str(g.get('schema', '')).startswith('explore-build-graph-v1'):
            print('WARNING: unexpected schema %r' % g.get('schema'), file=sys.stderr)
    else:
        g = graph_from_parquet(a.from_parquet)
        if a.dump_graph:
            with open(a.dump_graph, 'w', encoding='utf-8') as fh:
                json.dump(g, fh, separators=(',', ':'), ensure_ascii=False)
    faraday = a.faraday
    if not faraday and a.laws and os.path.isfile(a.laws):  # extras.py passes laws/laws.json as --laws: use its FA law
        try:
            faraday = a.laws if 'FA' in (_load_json(a.laws).get('laws') or {}) else None
        except (OSError, ValueError, AttributeError):
            faraday = None
    ovs = load_overlays(g, a.lab, a.clarity, a.periodic, a.laws, faraday)
    v, size = write_outputs(g, a.out, ovs)
    print('visual %s: %d files, %d edges, %d repos, graph.json %.0f KB, overlays: %s -> %s'
          % (GENERATOR_VERSION, len(v['n']['r']), len(v['e']) // 2, len(v['repos']), size / 1024,
             ' '.join('%s %.0f KB' % (k, b / 1024) for k, b in v['ov'].items()) or 'none', a.out))


if __name__ == '__main__':
    main()