GLOBALGRID2050 / EXPLORE CODE

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

Arena and 1 more file

A Python command-line tool in the bigbang folder of Cosmic that reads build graph, games and translations, using Bradley-Terry and SHA-256.

562 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1074 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. Agentdocs render · cosmic / tools/explore/agentdocs.py lines 701–924
  2. Arena storage · cosmic / tools/explore/bigbang/arena.py lines 1–338

Agentdocs

A Python module in the explore folder of Cosmic that maps composer, jsconfig, 33kV and substations, using EPSG:27700 and EPSG:4326.

rendercosmic / tools/explore/agentdocs.py · lines 701–924 of 924 (continued from section 1073) · Entry point · pattern _compact (shared by 2 files)

What it does
It maps composer, jsconfig, 33kV and substations. Defines 41 functions or classes, including words_of, _stage_from_words, voltages_in, crs_in, _add. Uses libraries collections, hashlib, html, posixpath, re. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: 33kV, substations, 400kV, 275kV, 132kV, 11kV.
Inputs & outputs
In: browser storage (getItem); browser IndexedDB; DuckDB queries; user-supplied file (file picker); form fields (user input); command-line arguments. Out: CSV file x.csv; downloaded file x.csv; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258, UTM. Voltage levels named: 400kV, 275kV, 132kV, 33kV, 11kV, 11kV/400V, 6.6kV, 1500V.
Downstream impact
Used directly by 3 files: Build (cosmic); Test Agentdocs (cosmic); Test Build (cosmic). Reached from 3 other entry points, including Cadastre 27 (cosmic); Ship (cosmic); Test Ship (cosmic).
What it achieves
It splits parts (`split_parts`), sizes label (`size_label`) and finds step (`find_step`). Defines `words_of`, `voltages_in`, `crs_in` and 28 more. Its code works with 33 kV, 132 kV and 11 kV.
Why it matters
Imported by Build. Checked by 2 tests, including Test Agentdocs.
Application
cosmic · tools/explore · Python module
Uses
collections, hashlib, html, posixpath, re
Used by
imported by Build (import), imported by Test Agentdocs (import), imported by Test Build (import)
Produces
words_of, voltages_in, crs_in, data_contracts_of, contracts_words, domain_stage_of, commercial_users_of, canonical_statuses, entry_reach, signatures_of, what_it_does, why_it_exists
Defines here
elevator, shard_order, _label_words, _compact, homepage_links, find_step, location_files, resolve_journeys, link_sentence
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/agentdocs.py:701-924 · blob 80e530ff52856be49421e4a62fd011773fbd3196 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: unknown · users: none · canonical: unknown

def elevator(intro, engines, outro='', cap=ELEVATOR_WORDS):
    """The 'read this first' block at the top of llms.txt, at most `cap` words (links not counted): the elevator
    sentences of Ventus Ltd's stated mission (unchanged), then one line per core engine [(title, hook, link)].
    Hooks are cut to fewer words, never invented, until the block fits. Returns a list of lines."""
    for k in range(28, 5, -1):
        lines = [intro, '', 'Core engines (one line each; drafts awaiting owner approval where marked):']
        lines += ['- **%s**: %s %s' % (t, _cap(h, k), link) for t, h, link in engines]
        if outro:
            lines += ['', outro]
        if _words(lines) <= cap:
            return lines
    return lines


def shard_order(f):
    """Sort key for files in an llms-repo-*.txt shard, so the front teaches: live entry pages first, then other
    entry points, then the most-used files; tests and CI last (path breaks ties). f: graph-like dict."""
    low = (f.get('path') or '').lower()
    late = (f.get('kind') == 'test' or f.get('role') == 'test' or f.get('kind') == 'workflow'
            or low.startswith('.github/') or '/test' in '/' + low)
    live = bool(f.get('entry') and f.get('published'))
    return (late, not live, not f.get('entry'), -int(f.get('n_dependents') or 0), f.get('path') or '')


# ---------------------------------------------------------------- mission (owner brief only)
MISSION = (
    "Ventus Ltd states the purpose of this estate as follows. GlobalGrid2050 bridges upstream GB transmission and "
    "distribution topology (TSO/DNO networks, 132kV and above, the REPD renewables pipeline, data centres), modelled "
    "for engineering foresight, with commercial execution: inside-the-fence electrical and civil design below 33kV, "
    "HV materials procurement, and on-road and off-road farm-gate SatNav (LiDAR terrain, soil ground-bearing limits, "
    "secondary substations). Ventus Ltd describes its commercial boundary as deliberately limited to HV materials "
    "procurement and design below 33kV, avoiding DNO/TSO contestable and adoption balance-sheet and regulatory risk. "
    "It notes that about 92% of the UK landmass is off-road private land, where standard SatNavs fail at the farm "
    "gate, and that open utility coordinates such as UK Power Networks' 50,000+ secondary 11kV/400V substations can "
    "bridge the road network to exact off-road coordinates. Explore Code is its plain-English translation layer and "
    "dependency map for energy professionals, planners, landowners, procurement teams and AI agents. Read every file "
    "as domain engineering code, not generic web code.")


# ---------------------------------------------------------------- journeys
JOURNEYS = [
    ('a', 'Substation-to-Site Feasibility', ['PipelineNews', 'GridAtlas', 'See Through', 'LiDAR']),
    ('b', 'Inside-the-Fence Sub-33kV Design & BoQ',
     ['Solar Design Studio', 'Ventus Grid Engine', 'Cable Trench or Drill', 'Soil', 'Metals & Cable Prices']),
    ('c', 'Farm-Gate Off-Road Field Routing', ['Data UK DNO/TSO', 'SatNav', 'Compass', 'LiDAR']),
    ('d', 'Multi-Agent Memory & Code Audit', ['VEDIC', 'CVAA', 'Neural Link', 'Kuiper Editions']),
]
LABEL_STOP = {'and', 'or', 'the', 'of'}
LAUNCH_LEAD = re.compile(r'^(?:open|read|enter)\s+(?:the\s+)?|^the\s+', re.I)
ANCHOR = re.compile(r'<a\b([^>]*)>(.*?)</a>', re.I | re.S)
HREF = re.compile(r'''\bhref\s*=\s*["']([^"']+)["']''', re.I)


def _label_words(s):
    return [w for w in words_of(s.replace('&', ' and ')) if w not in LABEL_STOP]


def _compact(s):
    return ''.join(_label_words(s))


def homepage_links(text, launch_only=False):
    """[(anchor text, href)] of every <a> in the homepage (or only the launch buttons, class "launch"), text with
    tags stripped and entities decoded."""
    out = []
    for m in ANCHOR.finditer(text):
        h = HREF.search(m.group(1))
        if not h or (launch_only and not re.search(r'''\bclass\s*=\s*["'][^"']*\blaunch\b''', m.group(1), re.I)):
            continue
        t = html.unescape(re.sub(r'<[^>]+>', ' ', m.group(2)))
        t = re.sub(r'\s+', ' ', t).replace('→', '').strip()
        out.append((t, h.group(1)))
    return out


def find_step(label, repos, folders, links, resolve_url, files, map_url=lambda u: None, other_file=lambda r, p: ''):
    """(locations, notes) of one journey step; locations: [{"repo", "folder", "evidence", "detail", "target"}].
    See module docstring. map_url(u) -> (repo, path) for an estate address; other_file(repo, path) -> the name of a
    non-code file in the repository that would serve that address ('' if none)."""
    lw = _label_words(label)
    lset = set(lw)
    lc = _compact(label)
    locs, notes = [], []
    folder_set = set(folders)
    exact = [r for r in sorted(repos) if set(_label_words(r)) == lset or _compact(r) == lc]
    for r in exact:
        locs.append({'repo': r, 'folder': '', 'evidence': 'repository name', 'detail': r, 'target': None})
    seen_href = set()
    for text, href in links:
        t = LAUNCH_LEAD.sub('', text).strip()
        if t and _compact(t) == lc and href not in seen_href:
            seen_href.add(href)
            hit = resolve_url(href)
            if hit is None:
                rp = map_url(href)
                if not rp:
                    notes.append('The homepage links "%s" to %s, outside the public estate.' % (text, href))
                    continue
                r, p = rp
                folder = p.rstrip('/') if (p.endswith('/') or '.' not in p.rsplit('/', 1)[-1]) else posixpath.dirname(p)
                if (r, folder) in folder_set and not any(l['repo'] == r and not l['folder'] for l in locs):
                    locs.append({'repo': r, 'folder': folder, 'evidence': 'homepage launch link',
                                 'detail': '"%s" -> %s (the page itself is not among the code files)' % (text, href),
                                 'target': None})
                elif not any(l['repo'] == r for l in locs):
                    other = other_file(r, p)
                    notes.append('The homepage links "%s" to %s, but no code file in the public estate serves that '
                                 'address%s.' % (text, href, ('; %s/%s holds it, which is not code' % (r, other)) if other else ''))
                continue
            j = hit
            g = files[j]
            folder = posixpath.dirname(g['path'])
            if any(l['repo'] == g['repo'] and (l['folder'] == '' or folder == l['folder'] or
                                               folder.startswith(l['folder'] + '/')) for l in locs):
                for l in locs:
                    if l['repo'] == g['repo'] and l['target'] is None:
                        l['target'] = j
                        l['detail'] += '; homepage link "%s" -> %s' % (text, href)
                continue
            locs.append({'repo': g['repo'], 'folder': folder, 'evidence': 'homepage launch link',
                         'detail': '"%s" -> %s' % (text, href), 'target': j})
    if not exact:
        for r in sorted(repos):
            if lset and lset < set(_label_words(r)) and not any(l['repo'] == r for l in locs):
                locs.append({'repo': r, 'folder': '', 'evidence': 'repository name (contains the label words)',
                             'detail': r, 'target': None})
        whole = {l['repo'] for l in locs if not l['folder']}
        cands = []
        for r, d in folders:
            if r in whole:
                continue
            base = d.rsplit('/', 1)[-1]
            bw = set(_label_words(base))
            if bw & lset and lset <= (bw | set(_label_words(r))):
                cands.append((d.count('/'), r, d))
        if cands:
            dmin = min(c[0] for c in cands)
            for depth, r, d in sorted(cands):
                if depth != dmin:
                    continue
                if any(l['repo'] == r and (l['folder'] == d or (l['folder'] and d.startswith(l['folder'] + '/')) or
                                           (l['folder'] and l['folder'].startswith(d + '/'))) for l in locs):
                    for l in locs:
                        if l['repo'] == r and l['evidence'] == 'homepage launch link':
                            l['detail'] += '; folder name %s/%s' % (r, d)
                    continue
                locs.append({'repo': r, 'folder': d, 'evidence': 'folder name', 'detail': '%s/%s' % (r, d), 'target': None})
    return locs[:4], list(dict.fromkeys(notes))


def location_files(loc, files_by_repo, files):
    fis = files_by_repo.get(loc['repo'], [])
    if not loc['folder']:
        return list(fis)
    pre = loc['folder'] + '/'
    return [i for i in fis if files[i]['path'].startswith(pre)]


def resolve_journeys(files, repos, links, resolve_url, edges, reach_size, dependents, map_url=lambda u: None,
                     other_file=lambda r, p: ''):
    """The journeys array for build_graph.json (ids are file ids). files: build.py dicts (repo, path, title, entry);
    repos: repository names; links: homepage [(anchor text, href)] (homepage_links, already checked for non-public
    matches); resolve_url(url) -> file id or None; edges: [[from, to, kind, via]]."""
    files_by_repo = collections.defaultdict(list)
    folders = set()
    for i, f in enumerate(files):
        files_by_repo[f['repo']].append(i)
        d = posixpath.dirname(f['path'])
        while d:
            folders.add((f['repo'], d))
            d = posixpath.dirname(d)
    out = []
    for jid, title, labels in JOURNEYS:
        steps, sets = [], []
        for label in labels:
            locs, notes = find_step(label, repos, sorted(folders), links, resolve_url, files, map_url, other_file)
            fis = []
            for l in locs:
                l['files'] = location_files(l, files_by_repo, files)
                fis.extend(x for x in l['files'] if x not in fis)
            fset = set(fis)
            sets.append(fset)
            entries = [i for i in fis if files[i].get('entry')]
            targets = [l['target'] for l in locs if l['target'] is not None]
            entries = targets + sorted((i for i in entries if i not in targets),
                                       key=lambda i: (not files[i].get('published'), -reach_size.get(i, 0),
                                                      files[i]['repo'], files[i]['path']))
            key = sorted((i for i in fis if dependents.get(i)), key=lambda i: (-len(dependents[i]), i))
            steps.append({'label': label, 'found': bool(locs), 'notes': notes,
                          'locations': [{'repo': l['repo'], 'folder': l['folder'], 'evidence': l['evidence'],
                                         'detail': l['detail'], 'files': len(l['files']),
                                         'target': l['target']} for l in locs],
                          'entry_files': entries[:8], 'key_files': key[:6]})
        pairs = []
        by_pair = collections.defaultdict(list)
        owner = collections.defaultdict(set)
        for k, s in enumerate(sets):
            for i in s:
                owner[i].add(k)
        for a, b, kind, via in edges:
            for ka in owner.get(a, ()):
                for kb in owner.get(b, ()):
                    if ka != kb:
                        by_pair[(min(ka, kb), max(ka, kb))].append([a, b, kind])
        for k in range(len(labels) - 1):
            ev = by_pair.get((k, k + 1), [])
            pairs.append({'from': labels[k], 'to': labels[k + 1], 'adjacent': True, 'count': len(ev), 'edges': ev[:8]})
        for (ka, kb), ev in sorted(by_pair.items()):
            if kb - ka > 1:
                pairs.append({'from': labels[ka], 'to': labels[kb], 'adjacent': False, 'count': len(ev), 'edges': ev[:8]})
        out.append({'id': jid, 'title': 'Journey %s: %s' % (jid.upper(), title), 'url': 'journeys/%s.html' % jid,
                    'shard': 'llms-journey-%s.txt' % jid, 'source': "named in Ventus Ltd's brief", 'steps': steps,
                    'links': pairs})
    return out


def link_sentence(p, files):
    if not p['count']:
        return 'No direct code link found between %s and %s.' % (p['from'], p['to'])
    ex = '; '.join('%s/%s -> %s/%s (%s)' % (files[a]['repo'], files[a]['path'], files[b]['repo'], files[b]['path'], k)
                   for a, b, k in p['edges'][:3])
    return '%d resolved reference%s between %s and %s, e.g. %s.' % (p['count'], '' if p['count'] == 1 else 's',
                                                                    p['from'], p['to'], ex)

Arena

A Python command-line tool in the bigbang folder of Cosmic that reads build graph, games and translations, using Bradley-Terry and SHA-256.

storagecosmic / tools/explore/bigbang/arena.py · lines 1–338 of 338 · Entry point · pattern load_cache (shared by 4 files)

What it does
It loads build graph, games and translations. Defines 16 functions or classes, including load_players, Corpus, __init__, prep, key. Uses libraries argparse, hashlib, importlib.util, json, math. Side effects: reads or writes files.
Inputs & outputs
In: JSON file build_graph.json; JSON file translations.json; command-line arguments. Out: JSON file games.json.
Downstream impact
Used directly by 3 files: Test Primer 48 (cosmic); Test Arena (cosmic); Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It loads players (`load_players`), runs player (`run_player`) and loads cache (`load_cache`). Big Bang translation tournament (ARBITER: TALLY-58). It accepts `--n`, `--players` and `--out`.
Why it matters
Run by Extras. Checked by 2 tests, including Test Primer 48.
Application
cosmic · tools/explore/bigbang · Python CLI
Uses
Describe (sys.path import), Judge (import), Describe Bigbang (import), argparse, hashlib, importlib.util, json, math, os, random, sys
Used by
imported by Test Primer 48 (sys.path import), imported by Test Arena (import), run by Extras (script call)
Produces
load_players, Corpus, run_player, bt_elo, player_hash, load_cache, tournament, crosstable, write, main
Defines here
load_players, Corpus, __init__, prep, key, readable, sample, run_player, bt_elo, _sha, player_hash, load_cache, tournament, crosstable, write, 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/bigbang/arena.py:1-338 · blob eef1249b17b9246e3905084b58163d02fc57107f · 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
"""tools/explore/bigbang/arena.py - Big Bang translation tournament (ARBITER: TALLY-58).

PLAYER INTERFACE (v1)
  A player is tools/explore/bigbang/rules/<CODENAME>.py exposing

      translate(rec, src) -> {"title": str, "synopsis": str, "achieves": str}

  rec  one build_graph.json file record (a copy; keys as in /tmp/site8/explore-code/build_graph.json: repo, path,
       title, synopsis, achieves, why, kind, role, lang, lines, defines, signatures, imports_external,
       data_contracts, four_part, context, folder_hierarchy, name_words, ...) plus
       rec["ctx"] = {"readme":     [README sentences, nearest folder first],
                     "repo_title": "<repo display title>",
                     "evidence":   describe.py evidence dict for the file (describe.evidence_from_graph, no _text),
                     "dependents": [titles of files importing this one], "imports": [titles it imports]}
  src  the file's source text (first 400 kB; '' if unreadable).
  Optional module constants: NAME (display), STRATEGY (one line).
  Rules: deterministic, stdlib (+numpy) only, no network, no LLM, no file writes, < 1 s per file.
  Exceptions or malformed output = hard fail for that file.

JUDGE (judge.py, deterministic): hard fail if describe.invented(title+synopsis+achieves, evidence) is non-empty
  (evidence = describe.evidence_text(ev) + the record's JSON + source) or a `quoted` identifier is not in the source. Otherwise
  total = specificity(0-6: real `identifiers` in source, units/standards/formulas in source) + coverage(0-4: share
  of main public defines named) + plainness(0-3: describe.flags jargon/broken/status, long sentences, raw dumps)
  + README agreement(0-2) + brevity(-2..2: synopsis 12-40 words, achieves distinct, short title).
  Per file: higher total wins the move (gap >= 0.25, else draw). Match: more moves won = 1, equal = 1/2.

MATCHES: round robin, every pair once (white = earlier in sorted order, swapped on odd pairing index).
  Sample per match: N (default 60) files, seeded by the pair names, stratified round-robin over roles and, within a
  role, over repos (one file per repo before a second), source must be readable and non-empty.

CACHE: <out>/cache/<player>-<hash>.json keeps each player's outputs and scores; the hash covers the player file,
  judge.py and describe.py, so only changed players are re-run.

OUTPUT (/tmp/vk/bigbang/arena/): games.json (schema explore-bigbang-games-v1, chess-style crosstable with per-file
  moves: ply, file key repo@commit path:1-N, result, reason, both totals), results.md (standings + Elo from a
  Bradley-Terry fit over all moves, 1500-centred, 400 log10 scale), translations.json (every output per player).

Usage: python3 arena.py [--n 60] [--players a,b] [--out /tmp/vk/bigbang/arena]
"""
import argparse
import hashlib
import importlib.util
import json
import math
import os
import random
import sys
import time

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

GRAPH = '/tmp/site8/explore-code/build_graph.json'
SRC = '/home/claude/src'
OUT = '/tmp/vk/bigbang/arena'
RULES = os.path.join(HERE, 'rules')


def load_players(names=None):
    ps = {}
    for fn in sorted(os.listdir(RULES)):
        if not fn.endswith('.py') or fn.startswith(('test_', '_')):
            continue
        name = fn[:-3]
        if names and name not in names:
            continue
        spec = importlib.util.spec_from_file_location('bbplayer_' + name.replace('-', '_'), os.path.join(RULES, fn))
        try:
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
        except Exception as e:  # a broken player is reported, not fatal
            print('skip %s: %s' % (name, e), file=sys.stderr)
            continue
        if callable(getattr(mod, 'translate', None)):
            ps[name] = mod
    return ps


class Corpus:
    def __init__(self, graph=GRAPH, src=SRC):
        self.g = json.load(open(graph))
        self.F = self.g['files']
        self.src = src
        self.commit = {r['repo']: r.get('commit', '')[:12] for r in self.g['repos']}
        self.repo_titles = {}
        for f in self.F:
            r = describe.parse_synopsis(f['synopsis'])['repo_title']
            if r and f['repo'] not in self.repo_titles:
                self.repo_titles[f['repo']] = r
        for r in self.g['repos']:
            self.repo_titles.setdefault(r['repo'], r.get('descriptor') or r['repo'])
        self.cache = {}
        self._prep = {}

    def prep(self, i):
        """-> (rec, src, evidence_text) for file i, cached."""
        if i not in self._prep:
            ev = describe.evidence_from_graph(self.g, i, self.src, self.cache, self.repo_titles)
            src = ev.pop('_text', '')
            rec = json.loads(json.dumps(self.F[i]))
            rec['ctx'] = {'readme': list(ev.get('readme') or []), 'repo_title': ev.get('repo_title', ''),
                          'evidence': ev, 'dependents': [self.F[j]['title'] for j in self.F[i].get('dependents', [])],
                          'imports': [self.F[j]['title'] for j in self.F[i].get('imports', [])]}
            recj = json.dumps({k: v for k, v in self.F[i].items() if k != 'ctx'}, ensure_ascii=False)
            self._prep[i] = (rec, src, describe.evidence_text(ev) + '\n' + recj + '\n' + src)
        return self._prep[i]

    def key(self, i):
        f = self.F[i]
        return '%s@%s %s:1-%d' % (f['repo'], self.commit.get(f['repo'], '?'), f['path'], max(1, f.get('lines') or 1))

    def readable(self, i):
        f = self.F[i]
        p = os.path.join(self.src, f['repo'], f['path'])
        try:
            return os.path.getsize(p) > 0
        except OSError:
            return False

    def sample(self, seed, n=60):
        rng = random.Random(seed)
        by_role = {}
        for i, f in enumerate(self.F):
            by_role.setdefault(f['role'], {}).setdefault(f['repo'], []).append(i)
        queues = {}
        for role in sorted(by_role):
            repos = sorted(by_role[role])
            rng.shuffle(repos)
            for r in repos:
                rng.shuffle(by_role[role][r])
            order, depth = [], 0
            while True:  # one file per repo, then a second, ...
                layer = [by_role[role][r][depth] for r in repos if depth < len(by_role[role][r])]
                if not layer:
                    break
                order.extend(layer)
                depth += 1
            queues[role] = order
        out, roles = [], sorted(queues)
        while len(out) < n and any(queues.values()):
            for role in roles:
                while queues[role]:
                    i = queues[role].pop(0)
                    if self.readable(i):
                        out.append(i)
                        break
                if len(out) >= n:
                    break
        return out


def run_player(mod, rec, src):
    t = time.time()
    try:
        out = mod.translate(json.loads(json.dumps(rec)), src)
    except Exception as e:
        return {'title': '', 'synopsis': '', 'achieves': '', '_error': '%s: %s' % (type(e).__name__, e)}, time.time() - t
    if not isinstance(out, dict):
        return {'title': '', 'synopsis': '', 'achieves': '', '_error': 'not a dict'}, time.time() - t
    return {k: out.get(k, '') if isinstance(out.get(k, ''), str) else '' for k in ('title', 'synopsis', 'achieves')}, \
        time.time() - t


def bt_elo(players, games, iters=200):
    """Bradley-Terry over all moves (draw = half win each), as 1500-centred Elo."""
    w = {p: {q: 0.0 for q in players} for p in players}
    for g in games:
        for m in g['moves']:
            a, b = g['white'], g['black']
            s = {'1-0': 1.0, '0-1': 0.0}.get(m['result'], 0.5)
            w[a][b] += s
            w[b][a] += 1 - s
    r = {p: 1.0 for p in players}
    for _ in range(iters):
        nr = {}
        for p in players:
            num = sum(w[p][q] for q in players) + 0.5  # +0.5 prior keeps zero-win players finite
            den = sum((w[p][q] + w[q][p]) / (r[p] + r[q]) for q in players if q != p) + 1.0 / (r[p] + 1.0)
            nr[p] = num / den if den else r[p]
        gm = math.exp(sum(math.log(v) for v in nr.values()) / len(nr))
        r = {p: v / gm for p, v in nr.items()}
    return {p: round(1500 + 400 * math.log10(r[p])) for p in players}


def _sha(path):
    try:
        return hashlib.sha256(open(path, 'rb').read()).hexdigest()[:16]
    except OSError:
        return 'none'


def player_hash(mod):
    """Cache key: the player's own file + judge.py + describe.py (any change re-runs that player)."""
    return _sha(getattr(mod, '__file__', '') or '') + _sha(judge.__file__)[:8] + _sha(describe.__file__)[:8]


def load_cache(cache_dir, name, mod):
    p = os.path.join(cache_dir, '%s-%s.json' % (name, player_hash(mod)))
    try:
        return {int(k): v for k, v in json.load(open(p)).items()}, p
    except (OSError, ValueError):
        return {}, p


def tournament(corpus, players, n=60, log=print, cache_dir=None):
    names = sorted(players)
    games, trans, fails = [], {p: {} for p in names}, {p: [0, 0] for p in names}
    paths = {}
    if cache_dir:
        os.makedirs(cache_dir, exist_ok=True)
        for p in names:
            trans[p], paths[p] = load_cache(cache_dir, p, players[p])
    pairs = [(a, b) for k, a in enumerate(names) for b in names[k + 1:]]
    for k, (a, b) in enumerate(pairs):
        white, black = (a, b) if k % 2 == 0 else (b, a)
        seed = int(hashlib.sha256(('%s|%s' % (a, b)).encode()).hexdigest()[:8], 16)
        ids = corpus.sample(seed, n)
        moves, sc = [], [0.0, 0.0]
        for ply, i in enumerate(ids, 1):
            res = []
            for p in (white, black):
                if i not in trans[p]:
                    rec, src, evt = corpus.prep(i)
                    out, dt = run_player(players[p], rec, src)
                    s = judge.score(out, rec, src, evt)
                    if out.get('_error'):
                        s = {'total': 0.0, 'fail': 'player error: ' + out['_error'][:120], 'parts': {}, 'detail': {}}
                    trans[p][i] = {'out': out, 'score': s, 'secs': round(dt, 3)}
                res.append(trans[p][i]['score'])
            r, why = judge.move(res[0], res[1])
            sc[0] += {'1-0': 1, '0-1': 0}.get(r, 0.5)
            sc[1] += {'1-0': 0, '0-1': 1}.get(r, 0.5)
            moves.append({'ply': ply, 'file_id': i, 'key': corpus.key(i), 'role': corpus.F[i]['role'],
                          'result': r, 'white_total': res[0]['total'], 'black_total': res[1]['total'],
                          'note': '%s: %s' % (corpus.key(i), why)})
        result = '1-0' if sc[0] > sc[1] else '0-1' if sc[1] > sc[0] else '1/2-1/2'
        games.append({'white': white, 'black': black, 'seed': seed, 'files': len(ids), 'result': result,
                      'score': '%g-%g' % tuple(sc), 'moves': moves})
        log('%-12s v %-12s %s (%s)' % (white, black, result, games[-1]['score']))
        sys.stdout.flush()
    used = {i for g in games for m in g['moves'] for i in [m['file_id']]}
    for p in names:
        if cache_dir:
            json.dump({str(i): v for i, v in trans[p].items()}, open(paths[p], 'w'), ensure_ascii=False)
        trans[p] = {i: v for i, v in trans[p].items() if i in used}
        fails[p] = [len(trans[p]), sum(bool(v['score']['fail']) for v in trans[p].values())]
    return games, trans, fails


def crosstable(names, games):
    ct = {p: {q: None for q in names if q != p} for p in names}
    table = {p: {'player': p, 'played': 0, 'won': 0, 'drawn': 0, 'lost': 0, 'points': 0.0, 'moves_for': 0.0,
                 'moves_against': 0.0} for p in names}
    for g in games:
        w, b = g['white'], g['black']
        sw, sb = (float(x) for x in g['score'].split('-'))
        pw = {'1-0': 1.0, '0-1': 0.0}.get(g['result'], 0.5)
        ct[w][b], ct[b][w] = pw, 1 - pw
        for p, pts, mf, ma in ((w, pw, sw, sb), (b, 1 - pw, sb, sw)):
            t = table[p]
            t['played'] += 1
            t['won' if pts == 1 else 'lost' if pts == 0 else 'drawn'] += 1
            t['points'] += pts
            t['moves_for'] += mf
            t['moves_against'] += ma
    return ct, table


def write(out_dir, corpus, players, games, trans, fails):
    os.makedirs(out_dir, exist_ok=True)
    names = sorted(players)
    elo = bt_elo(names, games)
    ct, table = crosstable(names, games)
    rows = sorted(table.values(), key=lambda t: (-t['points'], -t['moves_for'], t['player']))
    for t in rows:
        t['elo'] = elo[t['player']]
        t['hard_fails'] = '%d/%d' % (fails[t['player']][1], fails[t['player']][0])
    doc = {'schema': 'explore-bigbang-games-v1', 'arbiter': 'TALLY-58', 'graph_cut': corpus.g.get('cut'),
           'judge': 'judge.py (see docstring): hard fail on invented(); spec+cov+plain+agree+brief; move eps 0.25',
           'players': [{'id': p, 'name': getattr(players[p], 'NAME', p),
                        'strategy': getattr(players[p], 'STRATEGY', '')} for p in names],
           'crosstable': ct, 'table': rows, 'games': games}
    json.dump(doc, open(os.path.join(out_dir, 'games.json'), 'w'), indent=1, ensure_ascii=False)
    json.dump({p: {str(i): v for i, v in trans[p].items()} for p in names},
              open(os.path.join(out_dir, 'translations.json'), 'w'), ensure_ascii=False)
    L = ['# Big Bang arena results (TALLY-58, arbiter)', '',
         'Graph cut `%s`; %d games, %d files per match, judge in `bigbang/judge.py`.' %
         (corpus.g.get('cut'), len(games), games[0]['files'] if games else 0), '',
         '| # | player | pts | W-D-L | moves for-against | Elo (BT) | hard fails |', '|---|---|---|---|---|---|---|']
    for k, t in enumerate(rows, 1):
        L.append('| %d | %s | %g | %d-%d-%d | %g-%g | %d | %s |' % (k, t['player'], t['points'], t['won'], t['drawn'],
                 t['lost'], t['moves_for'], t['moves_against'], t['elo'], t['hard_fails']))
    L += ['', '## Crosstable (row v column, 1 / 0.5 / 0)', '', '| | ' + ' | '.join(names) + ' |',
          '|---' * (len(names) + 1) + '|']
    for p in names:
        L.append('| %s | ' % p + ' | '.join('x' if q == p else '%g' % ct[p][q] for q in names) + ' |')
    L += ['', '## Mean component scores per translation (non-failed)', '',
          '| player | spec | cov | plain | agree | brief | total |', '|---|---|---|---|---|---|---|']
    for p in names:
        ok = [v['score'] for v in trans[p].values() if not v['score']['fail']]
        m = lambda k: sum(s['parts'][k] for s in ok) / max(1, len(ok))  # noqa: E731
        L.append('| %s | %.2f | %.2f | %.2f | %.2f | %.2f | %.2f |' % (p, m('spec'), m('cov'), m('plain'), m('agree'),
                 m('brief'), sum(s['total'] for s in ok) / max(1, len(ok))))
    L += ['', '## Hard-fail reasons (first 3 per player)', '']
    for p in names:
        fl = [(i, v['score']['fail']) for i, v in sorted(trans[p].items()) if v['score']['fail']][:3]
        for i, why in fl:
            L.append('- %s: `%s` %s' % (p, corpus.key(i), why))
    open(os.path.join(out_dir, 'results.md'), 'w').write('\n'.join(L) + '\n')
    return rows


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--n', type=int, default=60)
    ap.add_argument('--players', default='')
    ap.add_argument('--out', default=OUT)
    ap.add_argument('--graph', default=GRAPH)
    ap.add_argument('--with-distilled', action='store_true',
                    help='exhibition: add describe_bigbang.py as player "distilled" (use a separate --out)')
    a = ap.parse_args()
    players = load_players(set(a.players.split(',')) if a.players else None)
    if a.with_distilled:
        import describe_bigbang
        players['distilled'] = describe_bigbang
    corpus = Corpus(a.graph)
    games, trans, fails = tournament(corpus, players, a.n, cache_dir=os.path.join(a.out, 'cache'))
    rows = write(a.out, corpus, players, games, trans, fails)
    for t in rows:
        print('%-14s %4g pts  Elo %d  fails %s' % (t['player'], t['points'], t['elo'], t['hard_fails']))


if __name__ == '__main__':
    main()