GLOBALGRID2050 / EXPLORE CODE

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

Page and 1 more file

A Python command-line tool in the chess folder of Cosmic that reads board, games and build graph. It finds graph (`find_graph`), loads JSON (`load_json`) and starts squares (`start_squares`).

612 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1086 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. Furnace storage · cosmic / tools/explore/chess/furnace.py lines 1–259
  2. Page storage · cosmic / tools/explore/chess/page.py lines 1–353

Furnace

A Python command-line tool in the chess folder of Cosmic that reads furnace receipt.

storagecosmic / tools/explore/chess/furnace.py · lines 1–259 of 259 · Entry point · pattern features (shared by 5 files)

What it does
It loads furnace receipt. Defines 14 functions or classes, including _cheb, _centre, _shelter, piece_values, Furnace. Uses libraries json, sys, time, numpy, argparse. Side effects: reads or writes files.
Inputs & outputs
In: JSON file furnace-receipt.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Players (cosmic). Reached from 7 other entry points, including CI Chess Gate (cosmic); Extras (cosmic); Ship (cosmic).
What it achieves
It is built from the piece values helper (`piece_values`), the furnace class (`Furnace`) and the encode step (`encode`). Batched, vectorised chess evaluation (numpy now, CuPy/CUDA later). It accepts `--board`, `--games` and `--out`.
Why it matters
Imported by Players.
Application
cosmic · tools/explore/chess · Python CLI
Uses
Rules (import), json, sys, time, numpy, argparse
Used by
imported by Players (import)
Produces
piece_values, Furnace, reference_features, benchmark, positions_from_games
Defines here
_cheb, _centre, _shelter, piece_values, Furnace, __init__, encode, features, score, to_host, reference_features, benchmark, best, positions_from_games
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/chess/furnace.py:1-259 · blob cf682234a8c6c2101f1e58e750241e102a738ab6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Furnace: batched, vectorised chess evaluation (numpy now, CuPy/CUDA later).

The GPU lesson this reuses (gpu-drivers-for-global-grid engine/fused.py, CUDA-FURNACE-PROGRESS):
keep small lookup tables resident, push MANY cases through one pass instead of one call per case,
reduce before transfer, and check the batched channel against an independent per-case reference.
Here a "case" is a chess position, encoded as two (N, 64) int8 arrays:

  codes[n, s]  piece code on square s (a1 = 0 ... h8 = 63): pawn 1 .. king 6, white +, black -, 0 empty
  ids[n, s]    index of the board.json piece standing on s (0..31), or 32 for an empty square

`Furnace.features(codes, ids)` returns an (N, K) float matrix of white-minus-black features (FEATURES
below); a player is a weight vector w (K,), so scoring is one matrix product F @ w, and scoring the
same batch for all ten players at once is F @ W with W (K, 10). Every step is an array op over the
whole batch: gathers from tables, comparisons, sums. No Python loop runs per position.

Backends: `Furnace(board, xp=numpy)` (default). A CUDA backend slots in as `xp=cupy`: tables are
moved to the device once in __init__ (`xp.asarray`), batches are sent once per call, and only the
(N,) or (N, P) scores come back (`to_host`). Nothing else changes; a fused RawKernel can later replace
`features` behind the same signature, validated against `reference_features` exactly as here.

`reference_features` is the independent per-position channel: plain Python loops over 64 squares,
written separately from the vector code. `python furnace.py` compares the two on a batch of positions
(max |difference| must be 0 up to float rounding) and times both, writing a compact JSON receipt.
"""
import json
import sys
import time

import numpy as np

FEATURES = ('material', 'centre', 'advance', 'reach', 'orphan', 'tropism', 'shelter', 'king', 'develop')
K = len(FEATURES)
F_IDX = {f: i for i, f in enumerate(FEATURES)}
TYPE_VALUE = (0.0, 1.0, 3.0, 3.25, 5.0, 9.0, 0.0)      # king's worth is the separate 'king' feature
CENTRE_MULT = (0.0, 0.5, 1.0, 0.6, 0.1, 0.3, -0.5)      # how much each piece type likes the centre
EMPTY_ID = 32


def _cheb(a, b):
    return max(abs((a & 7) - (b & 7)), abs((a >> 3) - (b >> 3)))


def _centre(s):
    f, r = s & 7, s >> 3
    return 3.5 - max(abs(f - 3.5), abs(r - 3.5))          # 3.0 on d4/e4/d5/e5 .. 0.0 on the rim


def _shelter(k, s, side):
    """Is square s one of the (up to) six squares in front of a king on k?"""
    dr = ((s >> 3) - (k >> 3)) * side
    return 1 <= dr <= 2 and abs((s & 7) - (k & 7)) <= 1


def piece_values(pieces):
    """Per-piece values from board.json community facts (indexed like pieces).

    reach value  = type value x (reach + unique + centrality) / 1.5   (well-reached, unique, central = precious)
    orphan value = type value x ((1 - reach) + unique + (1 - centrality)) / 1.5   (the unreached are precious)
    Kings get 0 here: their survival is the 'king' feature.
    """
    names = {'pawn': 1, 'knight': 2, 'bishop': 3, 'rook': 4, 'queen': 5, 'king': 6}
    reach, orphan = [], []
    for p in pieces:
        tv = TYPE_VALUE[names[p['type']]]
        r, u, c = float(p['reach']), float(p['unique']), float(p['centrality'])
        reach.append(tv * (r + u + c) / 1.5)
        orphan.append(tv * ((1 - r) + u + (1 - c)) / 1.5)
    return reach, orphan


class Furnace:
    def __init__(self, pieces, xp=np):
        self.xp = xp
        self.pieces = pieces
        self.index = {p['id']: i for i, p in enumerate(pieces)}
        sign = [1.0 if p['side'] == 'white' else -1.0 for p in pieces]
        reach, orphan = piece_values(pieces)
        # host tables, then one transfer to the backend; they stay resident
        mat = np.array(TYPE_VALUE)
        cen = np.array([[CENTRE_MULT[t] * _centre(s) for s in range(64)] for t in range(7)])
        adv_w = np.array([max(0, (s >> 3) - 1) for s in range(64)], float)
        adv_b = np.array([max(0, 6 - (s >> 3)) for s in range(64)], float)
        idr = np.zeros(EMPTY_ID + 1)
        ido = np.zeros(EMPTY_ID + 1)
        idr[:len(pieces)] = np.array(reach) * sign
        ido[:len(pieces)] = np.array(orphan) * sign
        cheb = np.array([[7 - _cheb(a, b) for b in range(64)] for a in range(64)], float)
        sh_w = np.array([[_shelter(k, s, 1) for s in range(64)] for k in range(64)], float)
        sh_b = np.array([[_shelter(k, s, -1) for s in range(64)] for k in range(64)], float)
        rank = np.array([s >> 3 for s in range(64)])
        # every feature that depends only on (piece code, square) folded into one table, so the batch
        # needs one gather + one sum for all of them (fewer full-size temporaries: the fused.py lesson)
        lin = np.zeros((13, 64, 4))                         # material, centre, advance, develop
        for c in range(-6, 7):
            t, sg = abs(c), (1 if c > 0 else -1)
            if not c:
                continue
            lin[c + 6, :, 0] = sg * mat[t]
            lin[c + 6, :, 1] = sg * cen[t]
            if c == 1:
                lin[c + 6, :, 2] = adv_w
            elif c == -1:
                lin[c + 6, :, 2] = -adv_b
            if c in (2, 3):
                lin[c + 6, :, 3] = rank != 0
            elif c in (-2, -3):
                lin[c + 6, :, 3] = -(rank != 7).astype(float)
        self.t = {k: xp.asarray(v) for k, v in dict(
            lin=np.ascontiguousarray(lin.reshape(13 * 64, 4).T), ids=np.stack([idr, ido]),
            sq=np.arange(64), cheb=cheb, sh_w=sh_w, sh_b=sh_b).items()}
        self.calls = 0
        self.positions = 0

    def encode(self, codes, ids):
        """Lists of 64-lists (or arrays) to backend int arrays."""
        xp = self.xp
        return xp.asarray(np.asarray(codes, dtype=np.int8)), xp.asarray(np.asarray(ids, dtype=np.int8))

    def features(self, codes, ids):
        xp, t = self.xp, self.t
        codes = codes.astype(xp.intp)
        n = codes.shape[0]
        F = xp.empty((n, K))
        flat = (codes + 6) * 64 + t['sq']                                 # (N, 64) index into (code, square)
        lin = t['lin'][:, flat].sum(2)                                     # (4, N): contiguous gathers
        F[:, 0], F[:, 1], F[:, 2], F[:, 8] = lin[0], lin[1], lin[2], lin[3]
        idv = t['ids'][:, ids.astype(xp.intp)].sum(2)                     # (2, N)
        F[:, 3], F[:, 4] = idv[0], idv[1]
        wk_on, bk_on = codes == 6, codes == -6
        wk_alive, bk_alive = wk_on.any(1), bk_on.any(1)
        wk, bk = xp.argmax(wk_on, 1), xp.argmax(bk_on, 1)
        w_off = (codes >= 2) & (codes <= 5)
        b_off = (codes <= -2) & (codes >= -5)
        # tropism: closeness of each side's officers to the enemy king (0 if that king is gone)
        F[:, 5] = (w_off * t['cheb'][bk]).sum(1) * bk_alive - (b_off * t['cheb'][wk]).sum(1) * wk_alive
        F[:, 6] = ((codes == 1) * t['sh_w'][wk]).sum(1) * wk_alive - ((codes == -1) * t['sh_b'][bk]).sum(1) * bk_alive
        F[:, 7] = wk_alive.astype(xp.float64) - bk_alive.astype(xp.float64)
        self.calls += 1
        self.positions += n
        return F

    def score(self, codes, ids, w):
        """White-perspective scores: (N,) for w (K,), (N, P) for W (K, P)."""
        return self.features(codes, ids) @ self.xp.asarray(w)

    def to_host(self, a):
        return a.get() if hasattr(a, 'get') else np.asarray(a)


def reference_features(pieces, code64, id64):
    """Independent per-position channel: Python loops, no numpy. Same definitions as Furnace."""
    reach, orphan = piece_values(pieces)
    sign = [1 if p['side'] == 'white' else -1 for p in pieces]
    f = [0.0] * K
    wk = bk = None
    for s in range(64):
        if code64[s] == 6:
            wk = s
        elif code64[s] == -6:
            bk = s
    for s in range(64):
        c = code64[s]
        if not c:
            continue
        side = 1 if c > 0 else -1
        t = abs(c)
        f[0] += side * TYPE_VALUE[t]
        f[1] += side * CENTRE_MULT[t] * _centre(s)
        if c == 1:
            f[2] += max(0, (s >> 3) - 1)
        elif c == -1:
            f[2] -= max(0, 6 - (s >> 3))
        i = id64[s]
        if i != EMPTY_ID:
            f[3] += sign[i] * reach[i]
            f[4] += sign[i] * orphan[i]
        if 2 <= t <= 5:
            enemy_k = bk if side == 1 else wk
            if enemy_k is not None:
                f[5] += side * (7 - _cheb(s, enemy_k))
            if t <= 3 and (s >> 3) != (0 if side == 1 else 7):
                f[8] += side
        if t == 1:
            own_k = wk if side == 1 else bk
            if own_k is not None and _shelter(own_k, s, side):
                f[6] += side
    f[7] = (wk is not None) - (bk is not None)
    return f


def benchmark(pieces, codes, ids, repeat=5, xp=np, clock=time.process_time):
    """Furnace vs per-position reference on the same positions: agreement and timing receipt.

    Timed in CPU seconds (process_time) by default: shared runners and busy hosts make wall time noisy.
    The furnace time includes encoding the Python lists into arrays (what search pays per call).
    """
    furnace = Furnace(pieces, xp=xp)
    n = len(codes)

    def best(fn):
        ts = []
        for _ in range(repeat):
            t0 = clock()
            out = fn()
            ts.append(clock() - t0)
        return min(ts), out

    t_ref, ref = best(lambda: [reference_features(pieces, codes[i], ids[i]) for i in range(n)])
    t_enc, (c, d) = best(lambda: furnace.encode(codes, ids))
    t_feat, F = best(lambda: furnace.to_host(furnace.features(c, d)))
    t_chunk, _ = best(lambda: [furnace.to_host(furnace.features(*furnace.encode(codes[i:i + 32], ids[i:i + 32])))
                               for i in range(0, n, 32)])
    t_one, _ = best(lambda: [furnace.to_host(furnace.features(*furnace.encode(codes[i:i + 1], ids[i:i + 1])))
                             for i in range(n)])
    t_batch = t_enc + t_feat
    diff = float(np.abs(np.array(ref) - F).max()) if n else 0.0
    r = lambda x: round(x, 6)  # noqa: E731
    return {'positions': n, 'features': list(FEATURES), 'backend': xp.__name__, 'clock': clock.__name__,
            'reference_s': r(t_ref), 'furnace_encode_s': r(t_enc), 'furnace_features_s': r(t_feat),
            'furnace_s': r(t_batch), 'furnace_chunk32_s': r(t_chunk),
            'speedup_full_batch': round(t_ref / t_batch, 1) if t_batch else None,
            'speedup_features_only': round(t_ref / t_feat, 1) if t_feat else None,
            'speedup_chunk32': round(t_ref / t_chunk, 1) if t_chunk else None,
            'furnace_one_call_per_position_s': r(t_one),
            'speedup_batch_vs_one_call_per_position': round(t_one / t_batch, 1) if t_batch else None,
            'max_abs_diff': diff, 'agree': diff < 1e-9,
            'per_position_us': {'reference': round(1e6 * t_ref / max(n, 1), 2),
                                'furnace': round(1e6 * t_batch / max(n, 1), 3)}}


def positions_from_games(games_path, pieces):
    """Replay games.json through rules.py and encode every position reached."""
    sys.path.insert(0, __file__.rsplit('/', 1)[0])
    import rules
    idx = {p['id']: i for i, p in enumerate(pieces)}
    codes, ids = [], []
    for g in json.load(open(games_path))['games']:
        bd = rules.Board(track_ids=True)
        for mv in g['moves']:
            promo = {'queen': 'q', 'rook': 'r', 'bishop': 'b', 'knight': 'n'}.get(mv.get('promotion'), '')
            bd.push_uci(mv['from'] + mv['to'] + promo)
            codes.append([bd.b[s] for s in rules.SQUARES])
            ids.append([idx.get(bd.ids[s], EMPTY_ID) if bd.b[s] else EMPTY_ID for s in rules.SQUARES])
    return codes, ids


if __name__ == '__main__':                                  # pragma: no cover
    import argparse
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--board', required=True)
    ap.add_argument('--games', required=True, help='games.json whose positions to evaluate')
    ap.add_argument('--out', default='/tmp/vk/5/furnace-receipt.json')
    a = ap.parse_args()
    pcs = json.load(open(a.board))['pieces']
    cs, ds = positions_from_games(a.games, pcs)
    rec = benchmark(pcs, cs, ds)
    json.dump(rec, open(a.out, 'w'), indent=1)
    print(json.dumps(rec))

Page

A Python command-line tool in the chess folder of Cosmic that reads board, games and build graph. It finds graph (`find_graph`), loads JSON (`load_json`) and starts squares (`start_squares`).

storagecosmic / tools/explore/chess/page.py · lines 1–353 of 353 · Entry point · pattern first_existing (shared by 2 files)

What it does
It loads board, games and build graph. Defines 14 functions or classes, including first_existing, peek_cut, find_graph, load_json, start_squares. Uses libraries argparse, glob, html, json, os. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file board.json; JSON file games.json; JSON file build_graph.json; JSON file data.json; DuckDB queries; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 4 files: Test No Tmp (cosmic); Test Page (cosmic); CI Chess Gate (cosmic); Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Code chess page builder (reads `CONTRACT.md` `board.json` + `games.json`, writes one self-contained page). It accepts `--board`, `--games` and `--graph`.
Why it matters
Imported by CI Chess Gate. Run by Extras. Checked by 2 tests, including Test No Tmp.
Application
cosmic · tools/explore/chess · Python CLI
Uses
Board (import), argparse, glob, html, json, os, re, sys
Used by
run by Test No Tmp (script call), imported by Test Page (import), imported by CI Chess Gate (sys.path import), run by Extras (script call)
Produces
first_existing, peek_cut, find_graph, load_json, start_squares, fixture_board, fixture_games, build_data, E, noscript_html, fixture_note, read_template
Defines here
first_existing, peek_cut, find_graph, load_json, start_squares, fixture_board, fixture_games, build_data, E, noscript_html, fixture_note, read_template, render, 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/chess/page.py:1-353 · blob b2b5828d30da416b134f950322bb2e996a1f479e · 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
"""Code chess page builder (reads CONTRACT.md board.json + games.json, writes one self-contained page).

    python tools/explore/chess/page.py [--board B] [--games G] [--graph build_graph.json] [--out DIR]

Writes DIR/index.html (HTML, CSS, JS and data all inline; no network) and DIR/data.json (the same data).
The page is meant to sit at explore-code/chess/, so file links are ../s/NNNN.html#fB and topic links
../topics/<id>.html. If board.json or games.json are missing, a small deterministic fixture is used and the
page says so. build_graph.json is optional: it supplies file titles, sections, topics and the role palette;
without it file ids are listed without links.

Framing (owner brief, 5 December 2026): a playful map of how code communities relate, not a judgement.
"""
import argparse
import glob
import html
import json
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
TEMPLATE = os.path.join(HERE, 'template')
BOARD_SCHEMA = 'explore-chess-board-v1'
GAMES_SCHEMA = 'explore-chess-games-v1'
PAGE_SCHEMA = 'explore-chess-page-v1'
# No host paths (CI has none): extras.py sets EXPLORE_GRAPH / EXTRA_OUT; otherwise the current folder.
_OUT = os.environ.get('EXTRA_OUT') or '.'
DEFAULT_BOARD = [os.path.join(_OUT, 'board.json')]
DEFAULT_GAMES = [os.path.join(_OUT, 'games.json')]
DEFAULT_GRAPH = [os.environ.get('EXPLORE_GRAPH', ''), 'build_graph.json',
                 os.path.join(HERE, '..', '..', '..', 'explore-code', 'build_graph.json')]
DEFAULT_GRAPH_GLOBS = []

# Same palette as build.py ROLES (GRAPH-CONTRACT.md "Palette"); used when no build_graph.json is given.
ROLES = [
    ('geodesy', 'Geodesy and coordinates', '#00ffff'), ('electrical', 'Electrical engineering', '#ffae00'),
    ('energy-data', 'Energy data and markets', '#ffff00'), ('ingest', 'Ingest (fetch, load, parse)', '#66ccff'),
    ('transform', 'Transform (pure maths and conversion)', '#00ff88'),
    ('render', 'Render (DOM, canvas, maps, HTML)', '#ff6666'),
    ('interaction', 'Interaction (events, input, navigation)', '#ffd24a'),
    ('storage', 'Storage (browser, DuckDB, files written)', '#86e1d1'), ('test', 'Tests and checks', '#aef7d1'),
    ('automation', 'Automation and CI', '#8d95a3'), ('docs-config', 'Configuration and manifests', '#a6adbb'),
    ('other', 'Other', '#4c5a65'),
]
TYPES = ['king', 'queen', 'rook', 'bishop', 'knight', 'pawn']
GLYPH = {'king': '♚', 'queen': '♛', 'rook': '♜', 'bishop': '♝', 'knight': '♞', 'pawn': '♟'}
MAX_FILES = 200


def first_existing(paths):
    for p in paths:
        if p and os.path.exists(p):
            return p
    return None


def peek_cut(path):
    """The graph's cut, read from the first bytes (build_graph.json is compact and starts with schema, cut)."""
    try:
        with open(path, encoding='utf-8') as fh:
            head = fh.read(400)
    except OSError:
        return None
    m = re.search(r'"cut"\s*:\s*"([^"]*)"', head)
    return m.group(1) if m else None


def find_graph(cut):
    """File ids are stable within one cut only: prefer a graph whose cut equals the board's."""
    cands = [p for p in DEFAULT_GRAPH if os.path.exists(p)]
    for g in DEFAULT_GRAPH_GLOBS:
        cands += sorted(glob.glob(g))
    for p in cands:
        if cut and peek_cut(p) == cut:
            return p
    return cands[0] if cands else None


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


# ---------------------------------------------------------------- fixture (until the real files exist)

FIXTURE_GAMES = [  # short legal games: (white, black, result, [(from, to, promotion)])
    ('w1', 'b1', '1-0', ['e2e4', 'e7e5', 'f1c4', 'b8c6', 'd1h5', 'g8f6', 'h5f7']),
    ('w2', 'b2', '0-1', ['f2f3', 'e7e5', 'g2g4', 'd8h4']),
    ('w3', 'b3', '1/2-1/2', ['e2e4', 'g8f6', 'e4e5', 'd7d5', 'e5d6', 'e7d6', 'g1f3', 'f8e7', 'f1e2', 'e8g8', 'e1g1']),
    ('w4', 'b4', '1/2-1/2', ['a2a4', 'b7b5', 'a4b5', 'a7a6', 'b5a6', 'c8b7', 'a6b7', 'b8c6', 'b7a8q', 'd8a8']),
    ('w5', 'b5', '1-0', ['d2d4', 'd7d5', 'c2c4', 'e7e6', 'b1c3', 'g8f6', 'c1g5', 'f8e7']),
]


def start_squares():
    back = ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook']
    out = []
    for side, r1, r2 in (('white', '1', '2'), ('black', '8', '7')):
        s = side[0]
        for i, f in enumerate('abcdefgh'):
            t = back[i]
            pid = '%s-%s' % (s, 'n' if t == 'knight' else t[0]) + ('' if t in ('king', 'queen') else '-' + f)
            out.append((pid, side, t, f + r1))
            out.append(('%s-p-%s' % (s, f), side, 'pawn', f + r2))
    return out


def fixture_board(graph):
    """Deterministic stand-in: communities = (repo) groups of the graph, largest first."""
    files = (graph or {}).get('files') or []
    groups = {}
    for f in files:
        groups.setdefault(f.get('repo', '?'), []).append(f)
    comms = sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:32]
    while len(comms) < 32:
        comms.append(('community %d' % (len(comms) + 1), []))
    core = {'gridatlas', 'ventus-grid-engine', 'globalgrid2050', 'satnav', 'pipelinenews',
            'solar-electrical-topology-analysis-engine-text-based'}
    white = [c for c in comms if c[0] in core]
    rest = [c for c in comms if c[0] not in core]
    white = (white + rest)[:16]
    black = [c for c in comms if c not in white][:16]
    slots = {'white': [s for s in start_squares() if s[1] == 'white'],
             'black': [s for s in start_squares() if s[1] == 'black']}
    order = {t: i for i, t in enumerate(TYPES)}
    pieces = []
    for side, cs in (('white', white), ('black', black)):
        sl = sorted(slots[side], key=lambda s: (order[s[2]], s[3]))
        for ci, ((name, fl), (pid, _, typ, sq)) in enumerate(zip(cs, sl)):
            roles = {}
            for f in fl:
                roles[f.get('role', 'other')] = roles.get(f.get('role', 'other'), 0) + 1
            role = max(sorted(roles), key=lambda r: roles[r]) if roles else 'other'
            n = len(fl) or 1
            fl2 = sorted(fl, key=lambda f: -len(f.get('dependents') or []))
            pieces.append({
                'id': pid, 'side': side, 'type': typ, 'square': sq, 'community': ci + (0 if side == 'white' else 16),
                'label': name.replace('-', ' '), 'size': len(fl), 'lines': sum(f.get('lines', 0) for f in fl),
                'repos': [name] if fl else [], 'role': role,
                'centrality': round(1 - ci / 16.0, 2),
                'reach': round(sum(1 for f in fl if f.get('reachable')) / n, 2),
                'unique': round(sum(1 for f in fl if f.get('canonical_status') != 'duplicate_candidate') / n, 2),
                'files': [f['id'] for f in fl2[:MAX_FILES]],
                'why': 'Fixture: repository %s, rank %d by size on the %s side.' % (name, ci + 1, side),
            })
    return {'schema': BOARD_SCHEMA, 'cut': (graph or {}).get('cut', ''), 'rules_version': 'fixture',
            'sides': {'white': 'fixture: core repositories first', 'black': 'fixture: the rest'},
            'pieces': pieces, 'fixture': True}


def fixture_games(board):
    by_sq = {p['square']: p for p in board['pieces']}
    names = ['Opening Theorist', 'Steady Builder', 'Gambiteer', 'Fortress', 'Tactician']
    strat = ['plays central pawns first', 'develops minor pieces before anything else',
             'gives material for activity', 'castles early and waits', 'looks for captures and checks']
    players = []
    for side in ('white', 'black'):
        for i in range(5):
            players.append({'id': '%s%d' % (side[0], i + 1), 'side': side,
                            'name': '%s %s' % (side.title(), names[i]), 'strategy': 'Fixture: ' + strat[i]})
    games = []
    for seed, (w, b, res, mv) in enumerate(FIXTURE_GAMES):
        state = {sq: p for sq, p in by_sq.items()}
        moves = []
        for ply, m in enumerate(mv, 1):
            fr, to, promo = m[:2], m[2:4], m[4:] or None
            p = state.pop(fr)
            cap = state.get(to)
            if p['type'] == 'pawn' and fr[0] != to[0] and not cap:  # en passant
                cap = state.pop(to[0] + fr[1], None)
            if p['type'] == 'king' and abs(ord(fr[0]) - ord(to[0])) == 2:
                rf, rt = ('h', 'f') if to[0] == 'g' else ('a', 'd')
                state[rt + fr[1]] = state.pop(rf + fr[1])
            state[to] = p
            note = 'The %s community (%s) moves %s to %s' % (p['label'], p['role'], fr, to)
            if cap:
                note += ' and takes the %s community (%d files, %d%% unique)' % (
                    cap['label'], cap['size'], round(cap['unique'] * 100))
            mo = {'ply': ply, 'piece': p['id'], 'from': fr, 'to': to, 'capture': cap['id'] if cap else None,
                  'check': ply == len(mv) and res != '1/2-1/2', 'note': note + '.'}
            if promo:
                mo['promotion'] = 'queen'
            moves.append(mo)
        games.append({'white': w, 'black': b, 'seed': seed, 'result': res, 'moves': moves})
    table = []
    for p in players:
        row = {'player': p['id'], 'played': 0, 'won': 0, 'drawn': 0, 'lost': 0}
        for g in games:
            if p['id'] not in (g['white'], g['black']):
                continue
            row['played'] += 1
            if g['result'] == '1/2-1/2':
                row['drawn'] += 1
            elif (g['result'] == '1-0') == (p['side'] == 'white'):
                row['won'] += 1
            else:
                row['lost'] += 1
        table.append(row)
    return {'schema': GAMES_SCHEMA, 'players': players, 'games': games, 'table': table, 'fixture': True}


# ---------------------------------------------------------------- data for the page

def build_data(board, games, graph):
    graph = graph or {}
    mismatch = bool(graph) and bool(board.get('cut')) and graph.get('cut') != board.get('cut')
    roles = graph.get('roles')
    if mismatch:  # ids would point at the wrong files: keep the palette and topics, drop file links
        graph = {'roles': roles, 'topics': graph.get('topics')}
    roles = graph.get('roles') or [{'id': k, 'title': t, 'colour': c} for k, t, c in ROLES]
    sections = {s['section']: s for s in graph.get('sections') or []}
    topics = {t['id']: t['title'] for t in graph.get('topics') or []}
    gfiles = graph.get('files') or []
    files = {}
    pieces = []
    for p in board.get('pieces') or []:
        q = dict(p)
        q['files'] = list(p.get('files') or [])[:MAX_FILES]
        tcount = {}
        for fid in q['files']:
            if isinstance(fid, int) and 0 <= fid < len(gfiles):
                f = gfiles[fid]
                sec = sections.get(f.get('section'))
                url = ('../' + sec['url']) if sec and sec.get('url') else (
                    '../s/%04d.html' % f['section'] if f.get('section') else '')
                if url and f.get('block'):
                    url += '#f%d' % f['block']
                files[str(fid)] = {'t': f.get('title') or f.get('path', ''), 'r': f.get('repo', ''),
                                   'p': f.get('path', ''), 'u': url}
                tp = sec.get('topic') if sec else None
                if tp:
                    tcount[tp] = tcount.get(tp, 0) + 1
        q['topics'] = [{'id': t, 'title': topics.get(t, t), 'n': n, 'u': '../topics/%s.html' % t}
                       for t, n in sorted(tcount.items(), key=lambda kv: (-kv[1], kv[0]))]
        pieces.append(q)
    return {
        'schema': PAGE_SCHEMA, 'cut': board.get('cut') or graph.get('cut', ''),
        'board_schema': board.get('schema'), 'games_schema': games.get('schema'),
        'rules_version': board.get('rules_version', ''), 'sides': board.get('sides') or {},
        'fixture': bool(board.get('fixture') or games.get('fixture')), 'graph_mismatch': mismatch,
        'fixture_board': bool(board.get('fixture')), 'fixture_games': bool(games.get('fixture')),
        'roles': roles, 'pieces': pieces, 'reserve': board.get('reserve') or [],
        'files': files, 'players': games.get('players') or [], 'games': games.get('games') or [],
        'table': games.get('table') or [],
    }


def E(s):
    return html.escape(str(s), quote=True)


def noscript_html(data):
    rows = []
    for side in ('white', 'black'):
        ps = [p for p in data['pieces'] if p.get('side') == side]
        ps.sort(key=lambda p: (TYPES.index(p['type']) if p.get('type') in TYPES else 9, p.get('square', '')))
        rows.append('<h3>%s pieces</h3><ul>' % side.title())
        for p in ps:
            links = []
            for fid in p['files'][:5]:
                f = data['files'].get(str(fid))
                if f and f['u']:
                    links.append('<a href="%s">%s</a>' % (E(f['u']), E(f['t'])))
            tl = ['<a href="%s">%s</a>' % (E(t['u']), E(t['title'])) for t in p.get('topics', [])[:3]]
            rows.append('<li>%s %s %s on %s: <b>%s</b> (%s; %s files)%s%s</li>' % (
                GLYPH.get(p.get('type'), '?'), E(side), E(p.get('type', '')), E(p.get('square', '')),
                E(p.get('label', '')), E(p.get('role', '')), E(p.get('size', 0)),
                ('<br>files: ' + ', '.join(links)) if links else '',
                ('<br>topics: ' + ', '.join(tl)) if tl else ''))
        rows.append('</ul>')
    return ('<noscript><section class="ns"><h2>Pieces and their code communities</h2>'
            '<p>The board and the replays need JavaScript. Here is every piece, its community and where to read the code. '
            'Also see the <a href="../index.html">Explore Code topics</a>.</p>%s</section></noscript>' % ''.join(rows))


def fixture_note(data):
    what = [w for w, f in (('board', data['fixture_board']), ('games', data['fixture_games'])) if f]
    if not what:
        return ''
    return ('<p class="fixture">Preview: the real %s %s not been built yet, so this page shows a small stand-in.</p>'
            % (' and '.join(what), 'has' if what == ['board'] else 'have'))


def read_template(name):
    with open(os.path.join(TEMPLATE, name), encoding='utf-8') as fh:
        return fh.read()


def render(data):
    blob = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
    blob = blob.replace('</', '<\\/').replace('<!--', '<\\!--')
    page = read_template('index.html')
    subs = {
        '{{CSS}}': read_template('chess.css'),
        '{{JS}}': read_template('chess.js'),
        '{{DATA}}': blob,
        '{{NOSCRIPT}}': noscript_html(data),
        '{{CUT}}': E(data.get('cut') or 'unknown'),
        '{{FIXTURE}}': fixture_note(data),
    }
    for k, v in subs.items():
        page = page.replace(k, v)
    return page


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--board')
    ap.add_argument('--games')
    ap.add_argument('--graph')
    ap.add_argument('--out', default=_OUT)
    a = ap.parse_args(argv)
    bpath = a.board or first_existing(DEFAULT_BOARD)
    board = load_json(bpath) if bpath and os.path.exists(bpath) else None
    gpath = a.graph or find_graph(board.get('cut') if board else None)
    graph = load_json(gpath) if gpath and os.path.exists(gpath) else None
    if board is None and graph is not None and isinstance(graph.get('edges'), list):
        # Fallback computed from build_graph (communities by label propagation), not the fixture.
        sys.path.insert(0, HERE)
        import board as board_mod  # noqa: E402
        board, bpath = board_mod.build_board(graph, ''), 'computed from build_graph'
        print('page.py: no board.json; computed the board from %s' % gpath, file=sys.stderr)
    if board is None:
        print('page.py: warning: no board.json and no build_graph.json; writing the fixture page', file=sys.stderr)
        board = fixture_board(graph)
    if board.get('schema') != BOARD_SCHEMA:
        sys.exit('board schema %r, expected %r' % (board.get('schema'), BOARD_SCHEMA))
    gmpath = a.games or first_existing(DEFAULT_GAMES)
    if gmpath and os.path.exists(gmpath):
        games = load_json(gmpath)
    else:
        print('page.py: warning: no games.json (run tournament.py); using the fixture games', file=sys.stderr)
        games, gmpath = fixture_games(board), None
    if games.get('schema') != GAMES_SCHEMA:
        sys.exit('games schema %r, expected %r' % (games.get('schema'), GAMES_SCHEMA))
    data = build_data(board, games, graph)
    if data['graph_mismatch']:
        print('warning: graph cut %s != board cut %s; file links left out' % (graph.get('cut'), board.get('cut')),
              file=sys.stderr)
    os.makedirs(a.out, exist_ok=True)
    with open(os.path.join(a.out, 'index.html'), 'w', encoding='utf-8') as fh:
        fh.write(render(data))
    with open(os.path.join(a.out, 'data.json'), 'w', encoding='utf-8') as fh:
        json.dump(data, fh, separators=(',', ':'), ensure_ascii=False)
    print('wrote %s (%d pieces, %d games, board=%s, games=%s, graph=%s)' % (
        os.path.join(a.out, 'index.html'), len(data['pieces']), len(data['games']),
        bpath or 'fixture', gmpath or 'fixture', gpath or 'none'))
    return 0


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