GLOBALGRID2050 / EXPLORE CODE

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

Furnace — Electron and 1 more file

A Python module in the periodic folder of Cosmic that reads build graph and elements118. It ranks top (`rank_top`) and runs element (`run_element`).

700 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1111 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. Feed storage · cosmic / tools/explore/periodic/feed.py lines 641–760
  2. Furnace — Electron ingest · cosmic / tools/explore/periodic/furnace/electron/common.py lines 1–580

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 641–760 of 760 (continued from section 1110) · 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
copy_furnace, feed, make_fixture, 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/feed.py:641-760 · 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
def copy_furnace(src: Path | None, out: Path) -> bool:
    dst = out / 'furnace'
    if dst.exists():
        shutil.rmtree(dst)
    if not src or not (src / 'index.html').exists():
        return False
    shutil.copytree(src, dst, ignore=shutil.ignore_patterns('*.py', '__pycache__', '*.pyc', '.*'))
    return True


def feed(site: Path | None, out: Path, periodic: Path, props_path: Path | None, graph: Path | None,
         furnace: Path | None, base: str = '') -> dict:
    meta = load_periodic(periodic)
    if periodic.resolve() == (PAGE / 'fixture-periodic.json').resolve():
        meta['fixture'] = True
    elements = meta['elements']
    if not elements:
        raise SystemExit(f'feed.py: no elements in {periodic}')
    props = load_props(props_path, elements)
    files_by_id = load_graph(graph)
    for e in elements:
        e['files'] = [i for i in e['files'] if not files_by_id or i in files_by_id]
    file_names(elements)
    cols, periods = layout(elements, meta['groups'], meta['periods'])
    out.mkdir(parents=True, exist_ok=True)
    for name in ('periodic.css', 'periodic.js'):
        shutil.copyfile(PAGE / name, out / name)
    has_furnace = copy_furnace(furnace, out)
    (out / 'index.html').write_text(render_index(meta, elements, props, cols, periods, has_furnace))
    keep = {'index.html'}
    order = sorted(elements, key=order_key)
    for i, e in enumerate(order):
        fl = [files_by_id[k] for k in e['files'] if k in files_by_id]
        (out / e['page']).write_text(render_element(meta, e, props, fl, order[i - 1], order[(i + 1) % len(order)]))
        keep.add(e['page'])
    for old in out.glob('*.html'):
        if old.name not in keep:
            old.unlink()
    (out / 'llms-periodic.txt').write_text(render_llms(meta, elements, props, files_by_id, base, has_furnace))
    idx = build_index_json(meta, elements, files_by_id)
    (out / 'element-index.json').write_text(json.dumps(idx, ensure_ascii=False, separators=(',', ':')))
    (out / 'extra.json').write_text(json.dumps({
        'title': 'Periodic table of the code',
        'description': f'{len(elements)} code elements on one table: settled, unsettled and candidate, each with its evidence and files.',
        'entry': 'index.html'}, ensure_ascii=False) + '\n')
    (out / 'cards.json').write_text(json.dumps(build_cards_json(elements, files_by_id), ensure_ascii=False, separators=(',', ':')))
    return {'elements': len(elements), 'pages': len(elements) + 1, 'furnace': has_furnace,
            'fixture': meta['fixture'], 'files_mapped': len(idx['files']), 'props': len(props), 'out': str(out)}


# ----------------------------------------------------------------------------------------- fixture
def make_fixture(table_md: Path, graph: Path, commit: str = '') -> tuple[dict, dict]:
    """Fixture from star-maker/PERIODIC-TABLE.md: real symbols, numbers, states, values; files only by exact basename."""
    g = json.loads(graph.read_text())
    by_base: dict[str, list[int]] = {}
    for f in g['files']:
        by_base.setdefault(f['path'].rsplit('/', 1)[-1], []).append(f['id'])
    lines = table_md.read_text().splitlines()
    fam, elems, props = '', [], {}
    row_re = re.compile(r'^\| (\d+) \| \*\*([^*]+)\*\* \| (.+?) \| (.+?) \| (.*) \|$')
    for i, ln in enumerate(lines, 1):
        m = re.match(r'^## ([\w-]+) \(\d+\)', ln)
        if m:
            fam = m.group(1)
            continue
        m = row_re.match(ln)
        if not m:
            continue
        n, sym, name, state, note = int(m.group(1)), m.group(2), m.group(3), m.group(4), m.group(5)
        values = re.findall(r'`([^`]*)`', state) if 'unsettled' in state else []
        fids = by_base.get(name, []) if name.endswith('.js') else []
        elems.append({'symbol': sym, 'number': n, 'name': name, 'family': fam,
                      'state': 'unsettled' if 'unsettled' in state else 'settled',
                      'values': values, 'note': note.strip(),
                      'evidence': [f'star-maker@{commit[:12]} PERIODIC-TABLE.md:{i}'], 'files': fids})
        props[sym] = {'unsettled_forms': len(values), 'mapped_files': len(fids)}
    return ({'schema': 'explore-periodic-fixture-v1', 'fixture': True,
             'source': 'star-maker/PERIODIC-TABLE.md + exact basename match in build_graph.json', 'elements': elems},
            {'schema': 'explore-periodic-props-fixture-v1',
             'properties': [{'key': 'unsettled_forms', 'label': 'values in the wild', 'unit': ''},
                            {'key': 'mapped_files', 'label': 'mapped files', 'unit': ''}], 'elements': props})


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--site', help='built explore-code directory; output goes to <site>/periodic/')
    ap.add_argument('--out', help='output directory (default <site>/periodic); extras.py staging')
    ap.add_argument('--graph', help='build_graph.json (default <site>/build_graph.json)')
    ap.add_argument('--periodic', help='periodic.json from map.py (default /tmp/vk/periodic/periodic.json, else fixture)')
    ap.add_argument('--props', help='props.json from props.py (default /tmp/vk/periodic/props.json, else fixture)')
    ap.add_argument('--furnace', help='FURNACE gallery directory with index.html (default /tmp/vk/periodic/furnace)')
    ap.add_argument('--base', default='', help='absolute site base for llms-periodic.txt, e.g. https://…/explore-code/')
    ap.add_argument('--write-fixture', nargs=2, metavar=('PERIODIC_TABLE_MD', 'COMMIT'), help='rebuild page/fixture-*.json')
    a = ap.parse_args(argv)
    site = Path(a.site) if a.site else (Path(os.environ['EXPLORE_SITE']) if os.environ.get('EXPLORE_SITE') else None)
    graph = Path(a.graph) if a.graph else (site / 'build_graph.json' if site else None)
    if a.write_fixture:
        p, q = make_fixture(Path(a.write_fixture[0]), graph, a.write_fixture[1])
        (PAGE / 'fixture-periodic.json').write_text(json.dumps(p, indent=1, ensure_ascii=False) + '\n')
        (PAGE / 'fixture-props.json').write_text(json.dumps(q, indent=1, ensure_ascii=False) + '\n')
        print(f'feed.py: fixture written, {len(p["elements"])} elements')
        return 0
    if not site and not a.out:
        ap.error('give --site or --out')
    out = Path(a.out) if a.out else site / 'periodic'
    periodic = Path(a.periodic) if a.periodic else pick(DEFAULT_PERIODIC)
    if a.props:
        props = Path(a.props)
    elif a.periodic:
        props = None
    else:
        props = pick(DEFAULT_PROPS[:1]) if periodic == DEFAULT_PERIODIC[0] else pick(DEFAULT_PROPS[1:])
    furnace = Path(a.furnace) if a.furnace else pick(DEFAULT_FURNACE)
    res = feed(site, out, periodic, props, graph, furnace, a.base or os.environ.get('EXPLORE_BASE', ''))
    print('feed.py: ' + json.dumps(res))
    return 0


if __name__ == '__main__':
    sys.exit(main())

Furnace — Electron

A Python module in the periodic folder of Cosmic that reads build graph and elements118. It ranks top (`rank_top`) and runs element (`run_element`).

ingestcosmic / tools/explore/periodic/furnace/electron/common.py · lines 1–580 of 906 · Not reached from any entry point (candidate for review) · pattern fam_isolation (shared by 2 files)

What it does
It loads build graph and elements118. Defines 47 functions or classes, including layout_from_z, _valence_from_layout, _elements_file, _pick, element_params. Uses libraries __future__, json, math, os, re. Side effects: reads or writes files.
Inputs & outputs
In: JSON file build_graph.json; JSON file elements118.json.
What it achieves
ELECTRON shared helpers: graph arrays, element parameters, the 20 measure families.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/periodic/furnace/electron · Python module
Uses
__future__, json, math, os, re, numpy
Used by
none found
Produces
layout_from_z, element_params, graph_arrays, edge_set, py, scatter_max, raw, degrees, rank_top, q_cut, bfs, trim_to_cycles
Defines here
layout_from_z, _valence_from_layout, _elements_file, _pick, element_params, get, _count_params, _graph_path, _host_graph, intern, graph_arrays, _to_dev, edge_set, py, scatter_max, raw, degrees, rank_top, q_cut, bfs, trim_to_cycles, on_cycle_within, weak_components, gini, picture, _hist, fam_fanout, fam_reach, fam_impact, fam_components
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/furnace/electron/common.py:1-580 · blob bf6124cb0a7418ec8d907c489a48806fb16c8510 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""ELECTRON shared helpers: graph arrays, element parameters, the 20 measure families.

Primary computation for the furnace (see GRID.md). Every e<Z>.py calls
run_element(Z, ctx, xp). All array work goes through `xp` (numpy now, CuPy
later); Python loops only run over parameters (hops, chunks), never over files.
Deterministic, no network, no randomness: ties are broken by file id.

Edge direction in build_graph.json: edges[i] = [a, b, kind, flags] means file a
depends on / loads / runs / links file b (b.dependents contains a).
"""
from __future__ import annotations

import json
import math
import os
import re

import numpy as _np  # host-side preparation only; measures use xp

GRAPH_PATH = "/tmp/site8/explore-code/build_graph.json"
HERE = os.path.dirname(os.path.abspath(__file__))
ELEMENTS_JSON = os.path.join(os.path.dirname(HERE), "elements118.json")

# ---------------------------------------------------------------- edge blocks
# block letter -> edge kinds (build_graph edge_kinds ids)
BLOCK_EDGES = {
    "s": ("script-src", "stylesheet", "iframe", "modulepreload", "import-map"),   # page loads
    "p": ("import", "python-relative", "sys-path", "require", "dynamic-import",
          "url-import-meta"),                                                     # code imports
    "d": ("workflow-run", "script-call", "worker"),                               # run / orchestration
    "f": ("link", "estate-url", "fetch", "comment-url"),                          # references
}
BLOCK_TITLE = {"s": "page-load edges", "p": "code-import edges",
               "d": "run/orchestration edges", "f": "reference edges"}
STAGE_ORDER = {"ingest": 0, "transform": 1, "output": 2}  # 'unknown' -> -1

PALETTE = {"bg": "#0b0e14", "line": "#2f343d", "text": "#a6adbb", "hi": "#00ffff",
           "accent": "#66ccff", "white": "#ffffff"}

# --------------------------------------------------------------- element data
_PERIOD_START = [1, 3, 11, 19, 37, 55, 87, 119]


def layout_from_z(z: int) -> dict:
    """Standard 18-column layout (IUPAC form: Sc/Y/Lu/Lr in group 3; La-Yb, Ac-No f-block)."""
    p = max(i for i in range(7) if _PERIOD_START[i] <= z) + 1
    start = _PERIOD_START[p - 1]
    i = z - start
    if p == 1:
        return {"period": 1, "group": 1 if z == 1 else 18, "block": "s"}
    if p in (2, 3):
        if i < 2:
            return {"period": p, "group": i + 1, "block": "s"}
        return {"period": p, "group": i + 11, "block": "p"}
    if p in (4, 5):
        g = i + 1
        return {"period": p, "group": g, "block": "s" if g <= 2 else ("d" if g <= 12 else "p")}
    # periods 6, 7
    if i < 2:
        return {"period": p, "group": i + 1, "block": "s"}
    if i < 16:
        return {"period": p, "group": None, "block": "f"}
    g = i - 13
    return {"period": p, "group": g, "block": "d" if g <= 12 else "p"}


def _valence_from_layout(lay: dict) -> int:
    b, g = lay["block"], lay["group"]
    if b == "s":
        return 2 if g == 18 else g
    if b == "p":
        return g - 10
    if b == "d":
        return g
    return 3


_ELEM_CACHE: dict | None = None


def _elements_file() -> dict:
    global _ELEM_CACHE
    if _ELEM_CACHE is None:
        _ELEM_CACHE = {}
        if os.path.exists(ELEMENTS_JSON):
            try:
                data = json.load(open(ELEMENTS_JSON))
                rows = data.get("elements", data) if isinstance(data, dict) else data
                for r in rows:
                    zz = r.get("Z", r.get("atomic_number", r.get("number")))
                    if zz is not None:
                        _ELEM_CACHE[int(zz)] = r
            except Exception:  # unreadable table: fall back to layout
                _ELEM_CACHE = {}
    return _ELEM_CACHE


def _pick(d: dict, *names):
    for n in names:
        if isinstance(d, dict) and d.get(n) is not None:
            return d[n]
    return None


def element_params(z: int, ctx: dict | None) -> dict:
    """Merge ctx element props > furnace/elements118.json > layout derived from Z."""
    lay = layout_from_z(z)
    src = {}
    if isinstance(ctx, dict):
        src = ctx.get("element") or ctx.get("props") or {}
    row = _elements_file().get(z, {})
    def get(*names):
        v = _pick(src, *names)
        return v if v is not None else _pick(row, *names)
    period = int(get("period") or lay["period"])
    block = str(get("block") or lay["block"]).lower()[:1]
    group = get("group")
    group = int(group) if group not in (None, "", "f") else lay["group"]
    en = get("electronegativity", "en", "electronegativity_pauling")
    try:
        en = float(en) if en is not None else None
    except (TypeError, ValueError):
        en = None
    val = get("valence_electrons", "valence")
    try:
        val = int(val) if val is not None else _valence_from_layout(lay)
    except (TypeError, ValueError):
        val = _valence_from_layout(lay)
    sym = get("symbol") or ""
    name = get("name") or ""
    if block == "f":
        family = "L" if period == 6 else "A"
        fidx = z - (56 if period == 6 else 88)          # La/Ac = 1
    else:
        family = str(group)
        fidx = 0
    return {
        "Z": z, "symbol": sym, "name": name, "period": period, "group": group,
        "block": block, "electronegativity": en, "valence": val, "family": family,
        "f_index": fidx,
        # experiment parameters
        "d": period,                                   # depth / scale / row selector
        "v": max(1, min(int(val), 8)),                 # max bonds drawn = top files named
        "q": round(en / 4.0, 6) if en is not None else 0.5,  # quantile reported
        "k": z,                                        # k / seed
        "edge_block": block,                           # which edge kinds (BLOCK_EDGES)
    }


# ----------------------------------------------------------------- graph load
_HOST: dict | None = None
_DEV: dict = {}


def _count_params(sig: str) -> int:
    a, b = sig.find("("), sig.rfind(")")
    if a < 0 or b <= a:
        return 0
    inner = sig[a + 1:b].strip()
    if not inner:
        return 0
    depth, n = 0, 1
    for ch in inner:
        if ch in "([{<":
            depth += 1
        elif ch in ")]}>":
            depth -= 1
        elif ch == "," and depth == 0:
            n += 1
    return n


def _graph_path(ctx) -> str:
    """build_graph.json path: from ctx["inputs"] (FURNACE v1) if named there, else default."""
    inputs = ctx.get("inputs") if isinstance(ctx, dict) else None
    if isinstance(inputs, dict):
        for p in sorted(inputs):
            if str(p).endswith("build_graph.json") and os.path.exists(p):
                return str(p)
    return GRAPH_PATH


def _host_graph(graph: dict | None = None, path: str = GRAPH_PATH) -> dict:
    global _HOST
    if graph is None and _HOST is not None:
        return _HOST
    g = graph if graph is not None else json.load(open(path))
    files = g["files"]
    n = len(files)
    commits = {r["repo"]: r["commit"] for r in g.get("repos", [])}

    def intern(values):
        table, out = {}, []
        for v in values:
            out.append(table.setdefault(v, len(table)))
        return _np.asarray(out, dtype=_np.int64), list(table)

    repo_id, repos = intern(f["repo"] for f in files)
    lang_id, langs = intern(f["lang"] for f in files)
    role_names = [r["id"] for r in g.get("roles", [])]
    role_id = _np.asarray([role_names.index(f["role"]) if f["role"] in role_names else -1
                           for f in files], dtype=_np.int64)
    dom_names = [d["id"] for d in g.get("domain_stages", [])]
    dom_id = _np.asarray([dom_names.index(f["domain_stage"]) if f["domain_stage"] in dom_names
                          else -1 for f in files], dtype=_np.int64)
    status_names = list(g.get("canonical_statuses", []))
    status_id = _np.asarray([status_names.index(f["canonical_status"])
                             if f["canonical_status"] in status_names else -1 for f in files],
                            dtype=_np.int64)
    stage_rank = _np.asarray([STAGE_ORDER.get(f["stage"], -1) for f in files], dtype=_np.int64)
    lines = _np.asarray([int(f.get("lines") or 0) for f in files], dtype=_np.int64)
    pure = _np.asarray([bool(f.get("pure")) for f in files])
    reachable = _np.asarray([bool(f.get("reachable")) for f in files])
    dup = _np.asarray([f.get("duplicate_of") is not None for f in files])
    n_def = _np.asarray([len(f.get("defines") or []) for f in files], dtype=_np.int64)
    maxpar = _np.asarray([max([_count_params(s) for s in (f.get("signatures") or [])] or [-1])
                          for f in files], dtype=_np.int64)
    fdepth = _np.asarray([len(f["folder_hierarchy"]) - 1 for f in files], dtype=_np.int64)
    # folder prefix ids: H[i, l] = id of folder_hierarchy[:l+1], -1 padded
    L = int(fdepth.max()) + 1
    H = -_np.ones((n, L), dtype=_np.int64)
    pref: dict = {}
    for i, f in enumerate(files):
        fh = tuple(f["folder_hierarchy"])
        for l in range(len(fh)):
            H[i, l] = pref.setdefault(fh[:l + 1], len(pref))
    # name words (no digits), file x word pairs
    wtable: dict = {}
    wf, ww = [], []
    for i, f in enumerate(files):
        for w in sorted(set(f.get("name_words") or [])):
            if w and not re.search(r"\d", w):
                wf.append(i)
                ww.append(wtable.setdefault(w, len(wtable)))
    words = list(wtable)
    # edges by kind
    kind_names = [k["id"] for k in g.get("edge_kinds", [])]
    E = g["edges"]
    e_src = _np.asarray([e[0] for e in E], dtype=_np.int64)
    e_dst = _np.asarray([e[1] for e in E], dtype=_np.int64)
    e_kind = _np.asarray([kind_names.index(e[2]) if e[2] in kind_names else -1 for e in E],
                         dtype=_np.int64)
    e_dupflag = _np.asarray(["duplicate" in (e[3] or "") for e in E])
    evidence = []
    for f in files:
        evidence.append("%s@%s %s:1-%d" % (f["repo"], commits.get(f["repo"], "?"), f["path"],
                                          max(1, int(f.get("lines") or 1))))
    _HOST = dict(
        n=n, repo_id=repo_id, repos=repos, lang_id=lang_id, langs=langs, role_id=role_id,
        roles=role_names, dom_id=dom_id, doms=dom_names, status_id=status_id,
        statuses=status_names, stage_rank=stage_rank, lines=lines, pure=pure,
        reachable=reachable, dup=dup, n_def=n_def, maxpar=maxpar, fdepth=fdepth, H=H,
        w_file=_np.asarray(wf, dtype=_np.int64), w_word=_np.asarray(ww, dtype=_np.int64),
        words=words, kind_names=kind_names, e_src=e_src, e_dst=e_dst, e_kind=e_kind,
        e_dupflag=e_dupflag, evidence=evidence,
        paths=[f["repo"] + "/" + f["path"] for f in files],
        dup_of=[f.get("duplicate_of") for f in files],
    )
    return _HOST


def graph_arrays(ctx, xp) -> dict:
    """Host graph -> arrays on xp (cached per backend). ctx may carry 'graph' (raw dict)."""
    raw = ctx.get("graph") if isinstance(ctx, dict) else None
    if isinstance(raw, dict) and "files" in raw and "edges" in raw:
        key = (xp.__name__, id(raw))
        if key not in _DEV:
            host = _host_graph(raw)
            _DEV[key] = _to_dev(host, xp)
        return _DEV[key]
    key = (xp.__name__, "default")
    if key not in _DEV:
        _DEV[key] = _to_dev(_host_graph(None, _graph_path(ctx)), xp)
    return _DEV[key]


def _to_dev(host: dict, xp) -> dict:
    out = {}
    for k, v in host.items():
        out[k] = xp.asarray(v) if isinstance(v, _np.ndarray) else v
    out["_edgesets"] = {}
    return out


def edge_set(G: dict, block: str, xp):
    """Unique (src, dst) pairs of the block's edge kinds, self loops dropped."""
    if block in G["_edgesets"]:
        return G["_edgesets"][block]
    ids = [G["kind_names"].index(k) for k in BLOCK_EDGES[block] if k in G["kind_names"]]
    m = xp.zeros(G["e_kind"].shape, dtype=bool)
    for i in ids:
        m |= G["e_kind"] == i
    m &= G["e_src"] != G["e_dst"]
    n = G["n"]
    key = xp.unique(G["e_src"][m] * n + G["e_dst"][m])
    src, dst = key // n, key % n
    dupflag_key = G["e_src"][m & G["e_dupflag"]] * n + G["e_dst"][m & G["e_dupflag"]]
    G["_edgesets"][block] = (src, dst, dupflag_key)
    return G["_edgesets"][block]


# -------------------------------------------------------------- small helpers
def py(x):
    """xp scalar -> python number (rounded floats)."""
    if hasattr(x, "item"):
        x = x.item()
    if isinstance(x, float):
        if math.isnan(x):
            return None
        return round(x, 6)
    return x


def scatter_max(idx, val, n, xp):
    """out[i] = max(val[idx == i]) (0 where absent), deterministic on any backend."""
    out = xp.zeros(n, dtype=val.dtype)
    order = xp.lexsort(xp.stack([-val, idx]))
    ii, vv = idx[order], val[order]
    first = xp.ones(ii.shape, dtype=bool)
    first[1:] = ii[1:] != ii[:-1]
    out[ii[first]] = vv[first]
    return out


def raw(x):
    """xp scalar -> python float/int, NOT rounded (experiment values)."""
    if hasattr(x, "item"):
        x = x.item()
    return float(x) if isinstance(x, float) else x


def degrees(src, dst, n, xp):
    return xp.bincount(src, minlength=n), xp.bincount(dst, minlength=n)


def rank_top(score, mask, v, xp):
    """Indices of the top-v files by score desc, file id asc, within mask."""
    idx = xp.nonzero(mask)[0]
    if idx.size == 0:
        return []
    s = score[idx].astype(xp.float64)
    order = xp.lexsort(xp.stack([idx.astype(xp.float64), -s]))
    return [int(i) for i in idx[order[:v]].tolist()]


def q_cut(values, q, xp):
    """Lower empirical quantile: sorted(values)[floor(q*(m-1))]."""
    if values.size == 0:
        return None
    s = xp.sort(values.astype(xp.float64))
    return py(s[int(math.floor(q * (int(s.size) - 1)))])


def bfs(src, dst, n, seeds_mask, hops, xp):
    """Frontier BFS following src->dst; returns (reached mask excl. seeds, new per hop)."""
    reached = seeds_mask.copy()
    frontier = seeds_mask.copy()
    per_hop = []
    for _ in range(hops):
        nxt = xp.zeros(n, dtype=bool)
        nxt[dst[frontier[src]]] = True
        nxt &= ~reached
        per_hop.append(int(nxt.sum()))
        reached |= nxt
        frontier = nxt
    return reached & ~seeds_mask, per_hop


def trim_to_cycles(src, dst, n, xp):
    """Repeatedly drop nodes with zero in- or out-degree; survivors may lie on cycles."""
    alive = xp.ones(n, dtype=bool)
    while True:
        m = alive[src] & alive[dst]
        o = xp.bincount(src[m], minlength=n)
        i = xp.bincount(dst[m], minlength=n)
        new = alive & (o > 0) & (i > 0)
        if int(new.sum()) == int(alive.sum()):
            return new
        alive = new


def on_cycle_within(src, dst, n, cand, L, xp, chunk=512):
    """Bool mask: candidate file returns to itself in <= L steps (batched BFS)."""
    res = xp.zeros(n, dtype=bool)
    cidx = xp.nonzero(cand)[0]
    for s in range(0, int(cidx.size), chunk):
        c = cidx[s:s + chunk]
        B = int(c.size)
        ar = xp.arange(B)
        R = xp.zeros((B, n), dtype=bool)
        Fr = xp.zeros((B, n), dtype=bool)
        Fr[ar, c] = True
        for _ in range(L):
            b, e = xp.nonzero(Fr[:, src])
            N = xp.zeros((B, n), dtype=bool)
            N[b, dst[e]] = True
            N &= ~R
            R |= N
            Fr = N
        res[c[R[ar, c]]] = True
    return res


def weak_components(src, dst, n, xp):
    """Min-label propagation on the undirected graph; returns label per file."""
    lab = xp.arange(n)
    a = xp.concatenate([src, dst])
    b = xp.concatenate([dst, src])
    while True:
        cand = xp.full(n, n, dtype=lab.dtype)
        # scatter-min via sort: for each target b keep min lab[a]
        vals = lab[a]
        order = xp.lexsort(xp.stack([vals, b]))
        bs, vs = b[order], vals[order]
        first = xp.ones(bs.shape, dtype=bool)
        first[1:] = bs[1:] != bs[:-1]
        cand[bs[first]] = vs[first]
        new = xp.minimum(lab, cand)
        new = new[new]  # pointer jumping
        if bool((new == lab).all()):
            return lab
        lab = new


def gini(x, xp):
    x = xp.sort(x.astype(xp.float64))
    m = int(x.size)
    if m == 0 or float(x.sum()) == 0.0:
        return 0.0
    i = xp.arange(1, m + 1, dtype=xp.float64)
    return raw(2.0 * (i * x).sum() / (m * x.sum()) - (m + 1.0) / m)


# ------------------------------------------------------------------- picture
def picture(bars, hi, named, src, dst, k, xp, labels=None):
    """FURNACE v1 primitives in a 100x100 box (y down), palette colour names.

    Top: bars of the measured distribution (log height, highlighted bars cyan).
    Bottom: molecule of the named files (first = cyan) with the block's edges among
    them, at most v bonds; start angle seeded by Z (golden angle).
    """
    prim = []
    bars = [float(b) for b in bars][:16]
    if bars:
        top = max(max(bars), 1.0)
        w = 92.0 / len(bars)
        for i, b in enumerate(bars):
            h = 0.0 if b <= 0 else 3.0 + 39.0 * math.log1p(b) / math.log1p(top)
            if h > 0:
                prim.append({"t": "rect", "x": round(4 + i * w, 3), "y": round(46 - h, 3),
                             "w": round(max(w - 1, 0.5), 3), "h": round(h, 3),
                             "c": "cyan" if i in hi else "blue"})
        prim.append({"t": "line", "x1": 4, "y1": 46.5, "x2": 96, "y2": 46.5, "c": "line", "w": 0.5})
    if labels:
        prim.append({"t": "text", "x": 4, "y": 53, "s": str(labels)[:40], "c": "grey", "h": 4})
    m = len(named)
    pos = {}
    for j, fid in enumerate(named):
        ang = (k * 2.399963 + j * 2 * math.pi / max(m, 1)) % (2 * math.pi)
        r = 0 if m == 1 else 18
        pos[fid] = (round(50 + r * math.cos(ang), 3), round(76 + r * math.sin(ang), 3))
    if m > 1:
        nn = xp.asarray(named)
        sel = xp.nonzero(xp.isin(src, nn) & xp.isin(dst, nn))[0][:m]  # at most v bonds
        for e in sel.tolist():
            a, b = int(src[e]), int(dst[e])
            prim.append({"t": "line", "x1": pos[a][0], "y1": pos[a][1], "x2": pos[b][0],
                         "y2": pos[b][1], "c": "grey", "w": 0.6})
    for j, fid in enumerate(named):
        prim.append({"t": "circle", "x": pos[fid][0], "y": pos[fid][1],
                     "r": 4 if j == 0 else 2.5, "c": "cyan" if j == 0 else "white"})
    return prim


# ------------------------------------------------------------------ families
def _hist(deg, xp, top=9):
    """Counts of files with degree 1..top-1 and >= top."""
    c = xp.bincount(xp.minimum(deg, top), minlength=top + 1)
    return [int(x) for x in c[1:top + 1].tolist()]


def fam_fanout(G, P, xp, rev=False):
    src, dst, _ = edge_set(G, P["edge_block"], xp)
    n, d = G["n"], P["d"]
    out, inn = degrees(src, dst, n, xp)
    deg = inn if rev else out
    val = int((deg >= d).sum())
    named = rank_top(deg, deg > 0, P["v"], xp)
    word = "in" if rev else "out"
    return dict(
        measure="files with %s-degree >= %d over %s" % (word, d, BLOCK_TITLE[P["edge_block"]]),
        value=val, score=deg[deg > 0],
        detail={"max_%s_degree" % word: py(deg.max()), "files_with_edges": int((deg > 0).sum())},
        named=named, bars=_hist(deg, xp), hi=list(range(d - 1, 9)),
        labels="%s-degree 1..9+" % word)


def fam_reach(G, P, xp):
    src, dst, _ = edge_set(G, P["edge_block"], xp)
    n, d = G["n"], P["d"]
    out, _i = degrees(src, dst, n, xp)
    k = min(P["k"], int((out > 0).sum()))
    seeds = rank_top(out, out > 0, k, xp)
    smask = xp.zeros(n, dtype=bool)
    if seeds:
        smask[xp.asarray(seeds)] = True
    reached, per_hop = bfs(src, dst, n, smask, d, xp)
    return dict(
        measure="files reached within %d hops from the top k=%d files by out-degree (%s)"
                % (d, k, BLOCK_TITLE[P["edge_block"]]),
        value=int(reached.sum()), score=out[out > 0],
        detail={"k_seeds": k, "per_hop": per_hop}, named=seeds[:P["v"]], bars=per_hop,
        hi=[len(per_hop) - 1], labels="new files per hop 1..%d" % d)


def fam_impact(G, P, xp):
    src, dst, _ = edge_set(G, P["edge_block"], xp)
    n, d = G["n"], P["d"]
    _o, inn = degrees(src, dst, n, xp)
    r = max(0, d - 4)                      # hub rank: period 4 -> top hub, 5 -> 2nd, ...
    ranked = rank_top(inn, inn > 0, r + 1, xp)
    hub = ranked[r:r + 1]
    hmask = xp.zeros(n, dtype=bool)
    if hub:
        hmask[hub[0]] = True
    reached, per_hop = bfs(dst, src, n, hmask, d, xp)  # reverse direction
    named = hub + rank_top(inn, reached, P["v"] - 1, xp) if P["v"] > 1 else hub
    return dict(
        measure="files depending on the rank-%d in-degree hub within %d hops (%s)"
                % (r + 1, d, BLOCK_TITLE[P["edge_block"]]),
        value=int(reached.sum()), score=inn[inn > 0],
        detail={"hub": G["paths"][hub[0]] if hub else None, "hub_rank": r + 1,
                "hub_in_degree": py(inn[hub[0]]) if hub else 0, "per_hop": per_hop},
        named=named, bars=per_hop, hi=[0], labels="dependents per hop 1..%d" % d)


def fam_components(G, P, xp):
    src, dst, _ = edge_set(G, P["edge_block"], xp)
    n, d = G["n"], P["d"]
    lab = weak_components(src, dst, n, xp)
    sizes = xp.bincount(lab, minlength=n)
    sizes = sizes[sizes > 0]
    ss = xp.sort(sizes)[::-1]
    val = int((sizes >= d + 1).sum())
    big = int(xp.argmax(xp.bincount(lab, minlength=n)))
    out, inn = degrees(src, dst, n, xp)
    named = rank_top(out + inn, lab == big, P["v"], xp)
    return dict(
        measure="weak components of size >= %d (%s)" % (d + 1, BLOCK_TITLE[P["edge_block"]]),
        value=val, score=sizes[sizes > 1],
        detail={"largest": py(ss[0]), "components_size_ge2": int((sizes >= 2).sum())},
        named=named, bars=[int(x) for x in ss[:12].tolist()], hi=[0],
        labels="largest 12 component sizes")


def fam_cycles(G, P, xp):
    src, dst, _ = edge_set(G, P["edge_block"], xp)
    n, d = G["n"], P["d"]
    L = max(2, d - 2)                      # period 4 -> 2-cycles ... period 7 -> length <= 5
    cand = trim_to_cycles(src, dst, n, xp)
    oc = on_cycle_within(src, dst, n, cand, L, xp)
    key = src * n + dst
    recip = int(xp.isin(dst * n + src, key).sum()) // 2
    out, inn = degrees(src, dst, n, xp)
    named = rank_top(out + inn, oc, P["v"], xp)
    per_len = []
    for l in range(2, L + 1):
        per_len.append(int(on_cycle_within(src, dst, n, oc, l, xp).sum()) if int(oc.sum()) else 0)
    return dict(
        measure="files on a directed cycle of length <= %d (%s)" % (L, BLOCK_TITLE[P["edge_block"]]),
        value=int(oc.sum()), score=(out + inn)[oc],
        detail={"reciprocal_pairs": recip, "cycle_core": int(cand.sum())},
        named=named, bars=per_len, hi=[len(per_len) - 1], labels="on cycle len<=2..%d" % L)


def fam_crossrepo(G, P, xp):
    """Boundary crossing: endpoints differ within the first (d-2) folder_hierarchy levels.

    Level 1 is the repository, so period 3 (if used) = repository crossing; period 4 =
    repository or top folder, ... period 7 = any of the first 5 levels.