GLOBALGRID2050 / EXPLORE CODE

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

Describe Bigbang and 1 more file

A Python module in the explore folder of Cosmic that works with function clauses (`function_clauses`) and io facts (`io_facts`) (units: kV), using haversine and Newton-Raphson.

614 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1075 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. Describe Bigbang transform · cosmic / tools/explore/bigbang/describe_bigbang.py lines 1–374
  2. Judge transform · cosmic / tools/explore/bigbang/judge.py lines 1–240

Describe Bigbang

A Python module in the explore folder of Cosmic that works with function clauses (`function_clauses`) and io facts (`io_facts`) (units: kV), using haversine and Newton-Raphson.

transformcosmic / tools/explore/bigbang/describe_bigbang.py · lines 1–374 of 374 · Entry point · pattern _cap_words (shared by 2 files)

What it does
It calculates its inputs. Defines 17 functions or classes, including _verb_clause, function_clauses, specifics, _plain_ok, _cap_words. Uses libraries os, re, sys.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
Inputs & outputs
Coordinate systems named: Web Mercator / EPSG:3857. Voltage levels named: 400kV.
Downstream impact
Used directly by 2 files: Arena (cosmic); Test Describe Bigbang (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
What it achieves
It describes bigbang (`describe_bigbang`) and is built from the specifics step (`specifics`) and the first step (`first`). Distilled Big Bang translation rules (arbiter TALLY-58). Its code works with 400 kV.
Why it matters
Imported by Arena. Checked by Test Describe Bigbang.
Application
cosmic · tools/explore/bigbang · Python module
Uses
Describe (sys.path import), os, re, sys
Used by
imported by Arena (import), imported by Test Describe Bigbang (import)
Produces
function_clauses, specifics, io_facts, units_with_numbers, helper_clause, main_names, describe_bigbang, translate
Defines here
_verb_clause, function_clauses, specifics, _plain_ok, _cap_words, _sentence, _short_sentences, _place, io_facts, first, units_with_numbers, helper_clause, main_names, describe_bigbang, _bad, _guard, translate
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/describe_bigbang.py:1-374 · blob 13eb717f63049b61979cc0b93c78fad074ce72d3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""tools/explore/bigbang/describe_bigbang.py - distilled Big Bang translation rules (arbiter TALLY-58).

A PROPOSAL for describe.py, merged from the rule sets that won moves in the Big Bang arena (see DISTILLED.md for
which player each rule came from and the arena evidence). Pure, deterministic, stdlib only; reads no files.

    translate(rec, src) -> {'title', 'synopsis', 'achieves'}     (arena player interface)
    describe_bigbang(ev, src, rec=None) -> same, from a describe.py evidence dict

Rules, in order (R-numbers are referenced in DISTILLED.md):
  R1 verb-led function clauses: public defined names whose first word is a verb become "<verb>s <object words>
     (`name`)", in file order, up to 3 in the synopsis; nouns are never turned into verbs.
  R2 own words first: the file's cleaned leading comment (describe.clean_comment) is the achieves line; else the
     README sentence that names the file (describe.readme_match); else the code-facts phrase.
  R3 place in the estate: the synopsis opens with the kind noun and the repository's descriptor or the folder words,
     and names the page/file that uses it ("used by <title>") when the graph has one.
  R4 verified specifics: standards (IEC/BS/EN/IEEE/ISO numbers, G99, EPSG codes) and recognised method words
     (haversine, Newton-Raphson, PageRank, ...) are named only when they occur in the source; units only when the
     source uses them at least twice (describe.code_facts).
  R5 plain English guard: no raw identifiers outside backticks, sentences <= 28 words, status notes, dates, hashes and
     URLs dropped; synopsis cut to 12-40 words; achieves never repeats the synopsis.
  R6 never invent: every sentence is checked with describe.invented() against the evidence and dropped if it adds a
     proper noun; every `quoted` name must occur in the source.
"""
import os
import re
import sys

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

VERBS3 = dict(describe.VERB_LEAD)
VERBS3.update({'get': 'gets', 'read': 'reads', 'write': 'writes', 'save': 'saves', 'show': 'shows', 'hide': 'hides',
               'add': 'adds', 'remove': 'removes', 'init': None, 'setup': None, 'set': 'sets', 'run': 'runs',
               'format': 'formats', 'normalise': 'normalises', 'normalize': 'normalizes', 'sort': 'sorts',
               'filter': 'filters', 'group': 'groups', 'count': 'counts', 'score': 'scores', 'rank': 'ranks',
               'solve': 'solves', 'simulate': 'simulates', 'project': 'projects', 'resolve': 'resolves',
               'select': 'selects', 'open': 'opens', 'close': 'closes', 'send': 'sends', 'post': 'posts',
               'write': 'writes', 'bind': 'binds', 'attach': 'attaches', 'mount': 'mounts', 'toggle': 'toggles',
               'handle': None, 'on': None, 'is': None, 'has': None, 'to': None, 'make': 'makes', 'list': 'lists',
               'search': 'searches', 'match': 'matches', 'test': None, 'assert': None, 'expect': None,
               'snap': 'snaps', 'zoom': 'zooms', 'pan': 'pans', 'fit': 'fits', 'pick': 'picks', 'place': 'places',
               'route': 'routes', 'size': 'sizes', 'rate': 'rates', 'classify': 'classifies', 'encode': 'encodes',
               'decode': 'decodes', 'hash': 'hashes', 'write_': 'writes', 'emit': 'emits', 'append': 'appends',
               'insert': 'inserts', 'delete': 'deletes', 'replace': 'replaces', 'wrap': 'wraps', 'clamp': 'clamps',
               'interpolate': 'interpolates', 'integrate': 'integrates', 'aggregate': 'aggregates',
               'summarise': 'summarises', 'translate': 'translates', 'describe': 'describes', 'explain': 'explains',
               'judge': 'judges', 'compare': 'compares', 'diff': 'compares', 'reset': 'resets', 'start': 'starts',
               'stop': 'stops', 'step': 'steps', 'tick': 'advances', 'animate': 'animates', 'paint': 'paints',
               'highlight': 'highlights', 'label': 'labels', 'mark': 'marks', 'join': 'joins', 'split': 'splits',
               'resample': 'resamples', 'reproject': 'reprojects', 'tile': 'tiles', 'mosaic': 'mosaics',
               'mask': 'masks', 'warp': 'warps', 'query': 'queries', 'lookup': 'looks up', 'serve': 'serves',
               'emit_': 'emits', 'log': None, 'print': 'prints', 'dump': 'dumps', 'cache': 'caches', 'store': 'stores'})
OBJ_STOP = {'the', 'a', 'an', 'of', 'to', 'for', 'and', 'or', 'by', 'from', 'with', 'in', 'on', 'at', 'it', 'all',
            'data', 'value', 'values', 'item', 'items', 'obj', 'fn', 'cb', 'el', 'tmp', 'impl', 'helper', 'async'}
STD_RX = re.compile(r'\b(?:IEC|BS|IEEE|ISO|ENA|IET)\s?[A-Z]?\s?\d{3,5}(?:-\d+)*\b|\bBS\s?EN\s?\d{3,5}(?:-\d+)*\b|'
                    r'\bG(?:59|83|98|99|100)(?:/\d)?\b|\bEPSG:\d{4,5}\b')
METHODS = [('haversine', 'haversine'), ('vincenty', 'Vincenty'), ('newton-raphson', 'Newton-Raphson'),
           ('newton_raphson', 'Newton-Raphson'), ('gauss-seidel', 'Gauss-Seidel'), ('pagerank', 'PageRank'),
           ('dijkstra', 'Dijkstra'), ('louvain', 'Louvain'), ('bradley-terry', 'Bradley-Terry'),
           ('douglas-peucker', 'Douglas-Peucker'), ('delaunay', 'Delaunay'), ('voronoi', 'Voronoi'),
           ('k-means', 'k-means'), ('kmeans', 'k-means'), ('monte carlo', 'Monte Carlo'), ('kalman', 'Kalman'),
           ('fft', 'FFT'), ('sha-256', 'SHA-256'), ('sha256', 'SHA-256'), ('helmert', 'Helmert'),
           ('ostn15', 'OSTN15'), ('web mercator', 'Web Mercator'), ('levenshtein', 'Levenshtein'),
           ('topological sort', 'topological sort'), ('point in polygon', 'point in polygon'),
           ('ray casting', 'ray casting'), ('bilinear', 'bilinear'), ('least squares', 'least squares')]
RAW_ID = re.compile(r'(?<![`\w])(?:[a-z]+[A-Z]\w*|[a-z]+_\w+|\w+\.(?:mjs|cjs|py|js|ts))(?![`\w])')
HOUSE = re.compile(r'\b(candidate|retired|deprecated|superseded|unreviewed|quarantined|placeholder|copied|draft|'
                   r'legacy|archived|todo|fixme)\b|\b20\d{6,}\b|\b20\d\d-\d\d-\d\d\b|\b[0-9a-f]{10,}\b|https?://|'
                   r'run with|usage:', re.I)


def _verb_clause(name):
    ws = describe.ident_words(name)
    if len(ws) < 2 or name.startswith('_') or name.isupper():
        return ''
    v = VERBS3.get(ws[0])
    if not v:
        return ''
    obj = [w for w in ws[1:] if w not in OBJ_STOP and not w.isdigit() and len(w) > 1]
    if not obj or len(obj) > 4:
        return ''
    return '%s %s (`%s`)' % (v, ' '.join(describe._shown(w) for w in obj), name)


def function_clauses(defines, src, title='', n=3):
    """R1: verb-led clauses for public defined names that occur in the source, file order, de-duplicated by phrase."""
    out, seen = [], set()
    tl = title.lower()
    for d in defines or []:
        if d not in src:
            continue
        c = _verb_clause(d)
        if not c:
            continue
        ph = c.split(' (`')[0]
        if ph in seen or (len(ph) > 8 and ph.split(' ', 1)[-1] == tl):
            continue
        seen.add(ph)
        out.append(c)
        if len(out) == n:
            break
    return out


def specifics(src):
    """R4: standards and method words that occur in the source (comments or code), in first-seen order."""
    found = []
    for m in STD_RX.finditer(src[:200000]):
        s = re.sub(r'\s+', ' ', m.group(0))
        if s not in found:
            found.append(s)
    head = src[:200000]
    low = head.lower()
    for key, _shown in METHODS:
        k = low.find(key)
        if k >= 0 and re.match(r'(?<![a-z])', low[k - 1:k] if k else ''):
            lit = head[k:k + len(key)]  # the source's own spelling, so the never-invent check holds
            if lit.lower() not in (f.lower() for f in found):
                found.append(lit)
    return found[:3]


def _plain_ok(s):
    return s and not RAW_ID.search(re.sub(r'`[^`]*`', '', s)) and not HOUSE.search(re.sub(r'`[^`]*`', '', s))


def _cap_words(s, n):
    ws = s.split()
    if len(ws) <= n:
        return s
    cut = ' '.join(ws[:n])
    # do not cut inside a backtick pair
    if cut.count('`') % 2:
        cut = cut[:cut.rfind('`')].rstrip(' (,')
    return cut.rstrip(',;:( ') + '.'


def _sentence(s):
    s = s.strip()
    if not s:
        return ''
    s = s[0].upper() + s[1:]
    return s if s.endswith(('.', '!', '?')) else s + '.'


def _short_sentences(text, max_words=28, n=2):
    out = []
    for s in describe._sentences(text):
        s = s.strip()
        if 3 <= len(s.split()) <= max_words and _plain_ok(s):
            out.append(_sentence(s))
        if len(out) == n:
            break
    return ' '.join(out)


GENERIC_DIRS = set('src js lib libs assets static public dist scripts script app apps modules module core css styles '
                   'releases release versions build web site docs pages www code tools utils util helpers common '
                   'shared engine original current latest data files test tests archive workflows github'.split())


def _place(ev, rec):
    """R3: where the file lives, as a short phrase from the repository descriptor or folder words."""
    rt = (ev.get('repo_title') or '').strip()
    if rt and len(rt.split()) <= 8 and _plain_ok(rt):
        return 'in %s' % rt.rstrip('.')
    folders = [w for w in (rec or {}).get('folder_hierarchy', [])[1:] if re.match(r'^[a-z][a-z\-]{2,}$', w)
               and w not in GENERIC_DIRS]
    if folders:
        return 'in the %s folder' % folders[-1].replace('-', ' ')
    return ''


UNIT_NUM = re.compile(r'(?<![\w.])(\d+(?:\.\d+)?)\s?(kV|kVA|MVA|MW|GW|kW|MWh|GWh|kWh|kA|mm²|Hz)\b')
READS = [re.compile(r"fetch\(\s*[`'\"]([\w./\-]+\.(?:json|geojson|csv|parquet|txt|pmtiles|topojson|xml))[`'\"]"),
         re.compile(r"read(?:File|FileSync|_text|_csv|_json|_parquet)?\w*\(\s*[^,)]*?['\"`]([\w./\-]+\.(?:json|geojson|"
                    r"csv|parquet|txt|tsv|ya?ml))['\"`]"),
         re.compile(r"open\(\s*[^,)]*?['\"]([\w./\-]+\.(?:json|geojson|csv|txt|tsv|ya?ml))['\"]\s*\)")]
WRITES = [re.compile(r"write(?:File|FileSync|_text)?\w*\(\s*[^,)]*?['\"`]([\w./\-]+\.(?:json|geojson|csv|html|md|txt|"
                     r"parquet|svg|png))['\"`]"),
          re.compile(r"open\(\s*[^,)]*?['\"]([\w./\-]+\.(?:json|geojson|csv|html|md|txt|svg))['\"]\s*,\s*['\"][wa]")]
FLAGS = re.compile(r"add_argument\(\s*['\"](--[\w\-]+)")
EVENTS = re.compile(r"addEventListener\(\s*['\"](\w+)")
DRAWS = [(re.compile(r"maplibregl\.|mapboxgl\.|\bL\.map\(|new\s+ol\.Map"), 'draws a map'),
         (re.compile(r"getContext\(\s*['\"]webgl|WebGLRenderer|navigator\.gpu"), 'draws with the GPU'),
         (re.compile(r"getContext\(\s*['\"]2d"), 'draws on a canvas'),
         (re.compile(r"createElementNS\([^)]*svg|d3\.select"), 'draws SVG graphics')]


def io_facts(src, kind=''):
    """R7 (TRUSS-47): what the file reads, writes, accepts and draws, from literal source patterns only."""
    def first(rxs, n):
        out = []
        for rx in rxs:
            for m in rx.finditer(src[:200000]):
                v = m.group(1)
                if v not in out and '${' not in v:
                    out.append(v)
        return out[:n]
    f = {'reads': first(READS, 2), 'writes': first(WRITES, 2), 'flags': first([FLAGS], 3), 'draws': ''}
    ev = []
    for m in EVENTS.finditer(src[:200000]):
        if m.group(1) not in ev:
            ev.append(m.group(1))
    f['events'] = ev[:3]
    for rx, ph in DRAWS:
        if rx.search(src[:200000]):
            f['draws'] = ph
            break
    return f


def units_with_numbers(src, n=3):
    """R4b (FEEDER-47): ratings written with their numbers in the source ("400 kV"), most frequent first."""
    c = {}
    for m in UNIT_NUM.finditer(src[:200000]):
        k = '%s %s' % (m.group(1), m.group(2))
        c[k] = c.get(k, 0) + 1
    return [k for k, _ in sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))][:n]


def helper_clause(name):
    """R1b (PRIMER-48): a defined name that is not verb-led, said by its own words: "the seg dist helper (`segDist`)"."""
    ws = describe.ident_words(name)
    if name.startswith('_') or not ws or len(ws) > 4 or name.isupper():
        return ''
    words = ' '.join(describe._shown(w) for w in ws)
    if name[:1].isupper():
        return 'the %s class (`%s`)' % (words, name)
    return 'the %s step (`%s`)' % (words, name) if len(ws) == 1 else 'the %s helper (`%s`)' % (words, name)


def main_names(defines, src, n=6):
    out = []
    for d in defines or []:
        if d.startswith('_') or d.startswith('test') or d in ('main', '__init__', 'constructor') or len(d) < 3:
            continue
        if d in src and d not in out:
            out.append(d)
    return out[:n]


def describe_bigbang(ev, src, rec=None):
    rec = rec or {}
    title = describe.polish_title(ev.get('title') or rec.get('title') or '')
    kind = ev.get('kind') or rec.get('kind') or ''
    noun = describe.KIND_NOUN.get(kind, 'file')
    if kind == 'page' and ev.get('has_map'):
        noun = 'map page'
    defines = ev.get('defines') or rec.get('defines') or []
    names = main_names(defines, src)
    verb_cl, helper_cl = [], []
    for d in names:
        c = _verb_clause(d)
        if c:
            verb_cl.append(c)
        else:
            h = helper_clause(d)
            if h:
                helper_cl.append(h)
    io = io_facts(src, kind)
    specs = specifics(src)
    units = units_with_numbers(src)
    cf = ev.get('code') or {}
    # R3 synopsis head
    head = '%s %s' % (describe.article(noun), noun)
    place = _place(ev, rec)
    if place:
        head += ' ' + place
    acts = list(verb_cl[:3])
    if io['reads'] and len(acts) < 3:
        acts.append('reads `%s`' % io['reads'][0])
    if io['draws'] and len(acts) < 3:
        acts.append(io['draws'])
    if io['writes'] and len(acts) < 3:
        acts.append('writes `%s`' % io['writes'][0])
    if not acts and cf.get('phrase') and _plain_ok(cf['phrase']):
        acts.append(cf['phrase'])
    if not acts and ev.get('verb') and ev.get('objects'):
        acts.append('%s %s' % (describe.VERBS.get(ev['verb'], (ev['verb'],))[0], describe.join_words(ev['objects'][:3])))
    used_helpers = 0
    if len(acts) < 2 and helper_cl:  # R1b in the synopsis when verbs are scarce
        used_helpers = min(len(helper_cl), 3 - len(acts))
        acts.append('is built from ' + describe.join_words(helper_cl[:used_helpers]))
    own = describe.clean_comment(ev.get('comment', ''), os.path.basename(ev.get('path', '')), defines,
                                 max_words=24, title=title)
    if acts:
        syn = '%s that %s' % (head, describe.join_words(acts))
    elif own and _plain_ok(own):
        syn = head + ': ' + own.rstrip('.')
        own = ''
    else:  # R0: nothing better in the code; keep describe.py's synopsis
        syn = describe.describe(ev)['synopsis'].rstrip('.')
    if specs and len(syn.split()) < 32:
        syn += ', using %s' % describe.join_words(specs[:2])
    syn = _sentence(_cap_words(syn, 40))
    if len(syn.split()) < 12 and io['flags']:
        syn += ' It accepts %s.' % describe.join_words('`%s`' % f for f in io['flags'])
    if len(syn.split()) < 12:
        deps = [d for d in (rec.get('ctx') or {}).get('dependents', []) if d and _plain_ok(d)]
        if deps:
            syn += ' Used by %s%s.' % (deps[0], ' and %d other file%s' % (len(deps) - 1, 's' * (len(deps) > 2))
                                       if len(deps) > 1 else '')
    if len(syn.split()) < 12 and own and _plain_ok(own) and len(own.split()) <= 26:
        syn += ' ' + _sentence(own)
        own = ''
    # achieves (R2 own words first, then the rest of the functions, specifics, README context)
    ach = []
    if own:
        own = describe.clean_comment(ev.get('comment', ''), os.path.basename(ev.get('path', '')), defines,
                                     max_words=40, title=title)
    o = _short_sentences(own, 28, 2)
    if o and o.rstrip('.').lower() not in syn.lower():
        ach.append(o)
    rest = verb_cl[3:] + helper_cl[used_helpers:]
    if rest:
        ach.append(_sentence(('It also ' if verb_cl[3:] else 'It is built from ') + describe.join_words(rest[:3])))
    facts = [x for x in specs[2:] + units if x.lower() not in syn.lower()]
    if facts:
        ach.append(_sentence('Its code works with %s' % describe.join_words(facts[:3])))
    if io['events'] and kind in ('page', 'script', 'JavaScript module', 'component'):
        ach.append(_sentence('It responds to %s events' % describe.join_words(io['events'])))
    if len(ach) < 2 and ev.get('path'):
        r = _short_sentences(describe.readme_match(ev.get('readme') or [], ev['path']), 28, 1)
        if not r and ev.get('readme'):
            r = _short_sentences(' '.join(ev['readme'][:3]), 28, 1)
        if r and r.rstrip('.').lower() not in (syn + ' '.join(ach)).lower():
            ach.append(r)
    out = {'title': title, 'synopsis': syn, 'achieves': ' '.join(a for a in ach if a)}
    return _guard(out, ev, src, rec)


def _bad(s, evt, src):
    if any(x not in src for x in re.findall(r'`([^`]+)`', s)):
        return True
    test = re.sub(r'(^|[.!?:]\s+)([A-Z][a-z]+)\b(?![\w\-])', lambda m: m.group(1) + m.group(2).lower(), s)
    return bool(describe.invented(test, evt))


def _guard(out, ev, src, rec):
    """R6: drop any sentence that invents a proper noun or quotes a name absent from the source."""
    evt = describe.evidence_text(ev) + '\n' + src + '\n' + ' '.join((rec.get('ctx') or {}).get('dependents', []))
    for k in ('synopsis', 'achieves'):
        keep = []
        for s in re.split(r'(?<=[.!?])\s+(?=[A-Z`])', out[k]):
            if ', using ' in s and _bad(s, evt, src):
                s = re.sub(r', using [^.]*', '', s)
            q = re.findall(r'`([^`]+)`', s)
            if any(x not in src for x in q):
                continue
            test = re.sub(r'(^|[.!?:]\s+)([A-Z][a-z]+)\b(?![\w\-])', lambda m: m.group(1) + m.group(2).lower(), s)
            if describe.invented(test, evt):
                continue
            keep.append(s)
        out[k] = ' '.join(keep)
    if not out['synopsis']:
        noun = describe.KIND_NOUN.get(ev.get('kind', ''), 'file')
        out['synopsis'] = _sentence('%s %s' % (describe.article(noun), noun))
    return out


NAME = 'describe_bigbang (distilled)'
STRATEGY = 'Merged winning rules: verb-led function clauses, own words first, estate place, verified specifics.'


def translate(rec, src):
    ev = dict((rec.get('ctx') or {}).get('evidence') or {})
    if not ev:
        ev = {k: rec.get(k) for k in ('title', 'kind', 'role', 'repo', 'path', 'defines')}
        ev['readme'] = (rec.get('ctx') or {}).get('readme', [])
        ev['repo_title'] = (rec.get('ctx') or {}).get('repo_title', '')
    return describe_bigbang(ev, src or '', rec)

Judge

A Python module in the bigbang folder of Cosmic that uses haversine and Vincenty.

transformcosmic / tools/explore/bigbang/judge.py · lines 1–240 of 240 · Entry point · pattern main_functions (shared by 3 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including _words, main_functions, _plain_words, explained, _occurs. Uses libraries os, re, sys.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
Downstream impact
Used directly by 3 files: Arena (cosmic); Test Arena (cosmic); Test Describe Bigbang (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
What it achieves
It is built from the main functions helper (`main_functions`), the explained step (`explained`) and the sentence case off helper (`sentence_case_off`). Deterministic scoring of one translation (Big Bang arena, TALLY-58).
Why it matters
Imported by Arena. Checked by 2 tests, including Test Arena.
Application
cosmic · tools/explore/bigbang · Python module
Uses
Describe (sys.path import), os, re, sys
Used by
imported by Arena (import), imported by Test Arena (import), imported by Test Describe Bigbang (import)
Produces
main_functions, explained, sentence_case_off, score, move
Defines here
_words, main_functions, _plain_words, explained, _occurs, sentence_case_off, score, move
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/judge.py:1-240 · blob db287949d07e875f9738a9821bd1e36fc687e823 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""tools/explore/bigbang/judge.py - deterministic scoring of one translation (Big Bang arena, TALLY-58).

score(out, rec, src, evidence) -> {'total', 'fail', 'parts', 'detail'}

  out       {'title','synopsis','achieves'} from a player's translate()
  rec       the build_graph.json file record (as passed to the player, with rec['ctx'])
  src       the file's source text (first 400 kB)
  evidence  describe.evidence_text(ev) + source text: everything a player may draw words from

Components (all deterministic, no network):
  HARD FAIL  describe.invented(title+synopsis+achieves, evidence) is non-empty (a plain Titlecase word that starts a
             sentence is lower-cased first, see sentence_case_off), or the output is malformed,
             or a `quoted` identifier does not occur in the source. A failed translation loses every move
             against a non-failed one (two failures draw).
  spec  0..6 specificity: distinct `quoted` identifiers that occur in the source (+0.75 each, cap 3), plus
             recognised units / standards / formulas that occur in the source and in the text (+1 each, cap 3);
             a formula word must occur in the source as a whole word (v1.3: "elo" in "below" does not count).
  cov   0..4 coverage: share of the file's main functions (public defines, first 6 in file order) EXPLAINED in
             the text (see explained(): plain words "build tables" for build_tables, or `code` with 2+ content words
             before it in its clause); a bare list mention ("Defines `a`, `b`") counts half. 4 * share.
             Files with no defines score 2 (neutral).
  plain 0..3 plainness: 3, minus 1 per describe.flags() problem among jargon/identifiers, broken English,
             status/housekeeping; minus 1 if the mean sentence is over 28 words; minus 1 for a bare
             camelCase/snake_case dump (3+ raw identifiers outside backticks); minus 1 if any sentence lists 4+
             `quoted` names (v1.2: a backticked dump is still a dump).
  agree 0..2 agreement: distinct content words (4+ letters, not stock) shared with the README sentences,
             folder names and repo title: 0.4 each, cap 2.
  brief -2..2 brevity: synopsis 12-40 words +1 (else -1 per started 10 words outside, floor -2 overall);
             achieves present and not a copy of the synopsis +0.5; title 1-8 words +0.5;
             synopsis repeats the title verbatim (title 2+ words) -0.5.
total = spec + cov + plain + agree + brief. A move goes to the higher total if the gap is >= 0.25, else drawn.
"""
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import describe  # noqa: E402  (read-only import of tools/explore/describe.py)

UNIT_RX = re.compile(r'(?<![\w.])\d+(?:\.\d+)?\s?(?:kV|kVA|MVA|MVAr|kW|MW|GW|kWh|MWh|GWh|TWh|Hz|mm²|mm2|km|°C|K/W|'
                     r'W/m|Ω|ohm|A)\b|\b(?:kV|kVA|MVA|MVAr|kW|MW|GW|kWh|MWh|GWh|TWh|Hz|mm²|°C|K·m/W|W/m²|Ω/km)(?!\w)')
STD_RX = re.compile(r'\b(?:IEC|BS|EN|IEEE|ISO|ENA|ER|IET|NFPA|UL|ANSI)\s?[A-Z]?\s?\d{2,5}(?:[-‐:]\d+)*\b|'
                    r'\bG(?:59|83|98|99|100)\b|\bP2/[67]\b|\bEPSG:\d{4,5}\b|\bRFC\s?\d{3,5}\b')
FORMULA_WORDS = ['haversine', 'vincenty', 'newton-raphson', 'gauss-seidel', 'pagerank', 'dijkstra', 'a*', 'kruskal',
                 'prim', 'bradley-terry', 'elo', 'louvain', 'label propagation', 'least squares', 'kalman',
                 'fourier', 'fft', 'monte carlo', 'bisection', 'interpolation', 'bilinear', 'trilinear',
                 'douglas-peucker', 'delaunay', 'voronoi', 'convex hull', 'k-means', 'kmeans', 'sha-256', 'sha256',
                 'crc32', 'base64', 'mercator', 'web mercator', 'transverse mercator', 'helmert', 'ostn15', 'wgs84',
                 'ohm\'s law', 'i²r', 'i2r', 'voltage drop', 'power factor', 'derating', 'thermal resistance',
                 'short-circuit', 'fault level', 'load flow', 'power flow', 'per-unit', 'impedance', 'reactance',
                 'capacitance', 'skin effect', 'irradiance', 'mppt', 'levelised cost', 'lcoe', 'npv', 'irr',
                 'discount rate', 'regression', 'percentile', 'median', 'standard deviation', 'cosine similarity',
                 'jaccard', 'levenshtein', 'bfs', 'breadth-first', 'depth-first', 'topological sort', 'quadtree',
                 'r-tree', 'rtree', 'geohash', 'hilbert curve', 'raycast', 'ray casting', 'point in polygon']
STOCKW = set('''this that with from into which their there these those file files module script page code data
function functions uses used using defines define where when what does also each other only more than then them
they have will your about over under after before while through within without between using reads writes runs
makes builds shows draws loads returns gives takes keeps part tests test python javascript typescript workflow
github actions style sheet repository repo folder readme'''.split())


def _words(t):
    return {w.lower() for w in re.findall(r'[A-Za-z][A-Za-z\-]{3,}', t)} - STOCKW


def main_functions(rec, n=6):
    out = []
    for d in rec.get('defines') or []:
        if d.startswith('_') or d.startswith('test') or d in ('main', '__init__') or len(d) < 3:
            continue
        if d not in out:
            out.append(d)
    return out[:n]


def _plain_words(name):
    return ' '.join(describe.ident_words(name)).lower()


LIST_WORDS = set('defines define defined functions function and the its it including exports export also with or '
                 'plus classes class methods method helpers named called such as'.split())


def explained(name, text):
    """True if `name` is explained, not just listed: its plain words occur ("build tables" for build_tables), or a
    mention of it has 2+ content words in the same clause before it (since the previous backtick or ;:. boundary)."""
    if len(describe.ident_words(name)) > 1 and _plain_words(name) in text.lower():
        return True
    for m in re.finditer(r'`' + re.escape(name) + r'(?:\(\))?`', text):
        before = re.split(r'[`;:.!?]', text[:m.start()])[-1]
        ws = [w for w in re.findall(r'[A-Za-z]{3,}', before) if w.lower() not in LIST_WORDS]
        if len(ws) >= 2:
            return True
    return False


def _occurs(ident, src):
    """A quoted identifier counts if it occurs in the source (case-sensitive), or its path tail does."""
    i = ident.strip()
    if not i:
        return False
    if i in src:
        return True
    if i.endswith('()') and i[:-2] in src:
        return True
    tail = i.rsplit('/', 1)[-1]
    return len(tail) >= 3 and tail in src


INITIAL = re.compile(r'(^|[.!?:]\s+|\n)([A-Z][a-z]+)\b(?![\w\-])')


def sentence_case_off(text):
    """Lower-case a plain Titlecase word that starts a sentence ("Gives", "Reads") before invented(), so ordinary
    sentence starts are not taken for proper nouns. Acronyms, CamelCase and every later capitalised word are kept,
    so "National Grid ..." still fails on "Grid"."""
    return INITIAL.sub(lambda m: m.group(1) + m.group(2).lower(), text)


def score(out, rec, src, evidence):
    detail = {}
    if not isinstance(out, dict) or not all(isinstance(out.get(k, ''), str) for k in ('title', 'synopsis', 'achieves')):
        return {'total': 0.0, 'fail': 'malformed output', 'parts': {}, 'detail': {}}
    title, syn, ach = (out.get(k, '') or '' for k in ('title', 'synopsis', 'achieves'))
    text = ' '.join((title, syn, ach))
    if not syn.strip():
        return {'total': 0.0, 'fail': 'empty synopsis', 'parts': {}, 'detail': {}}
    bad = describe.invented(' \n'.join(sentence_case_off(t) for t in (title, syn, ach)), evidence)
    if bad:
        return {'total': 0.0, 'fail': 'invented: ' + ', '.join(sorted(set(bad)))[:160], 'parts': {}, 'detail': {}}
    quoted = [q for q in re.findall(r'`([^`]+)`', text)]
    missing = [q for q in quoted if not _occurs(q, src) and q not in evidence]
    if missing:
        return {'total': 0.0, 'fail': 'quoted identifier not in source: ' + ', '.join(missing[:4]), 'parts': {},
                'detail': {}}
    # specificity
    real = sorted({q for q in quoted if _occurs(q, src)})
    sl, tl = src.lower(), text.lower()
    terms = set()
    for m in UNIT_RX.findall(text) + STD_RX.findall(text):
        k = m.strip()
        if k.lower().replace(' ', '') in sl.replace(' ', ''):
            terms.add(k)
    for w in FORMULA_WORDS:
        rx = r'(?<![\w])' + re.escape(w) + r'(?![\w])'
        if re.search(rx, tl) and re.search(rx.replace(re.escape(w), re.escape(w).replace('\\ ', '[\\s_\\-]?')), sl):
            terms.add(w)
    spec = min(3.0, 0.75 * len(real)) + min(3.0, float(len(terms)))
    detail['quoted'] = real[:6]
    detail['terms'] = sorted(terms)[:6]
    # coverage
    mf = main_functions(rec)
    body = syn + ' ' + ach  # the title alone does not explain a function
    if mf:
        hit, named = [], []
        for d in mf:
            if explained(d, body):
                hit.append(d)
            elif d in body:
                named.append(d)
        cov = 4.0 * (len(hit) + 0.5 * len(named)) / len(mf)
        detail['covered'] = hit
        detail['named_only'] = named
        detail['main'] = mf
    else:
        cov = 2.0
    # plainness
    fl = describe.flags(title, syn, ach, '', rec.get('kind', ''))
    pf = sorted(fl & {'jargon/identifiers', 'broken English', 'status/housekeeping'})
    plain = 3.0 - len(pf)
    sents = [s for s in re.split(r'(?<=[.!?])\s+', (syn + ' ' + ach).strip()) if s]
    mean = sum(len(s.split()) for s in sents) / max(1, len(sents))
    if mean > 28:
        plain -= 1
        pf.append('long sentences (%.0f words)' % mean)
    raw = re.findall(r'(?<![`\w])(?:[a-z]+[A-Z]\w*|[a-z]+_\w+)(?![`\w])', re.sub(r'`[^`]*`', ' ', text))
    if len(raw) >= 3:
        plain -= 1
        pf.append('identifier dump')
    if any(len(re.findall(r'`[^`]+`', x)) >= 4 for x in sents):
        plain -= 1
        pf.append('list of 4+ `names` in one sentence')
    plain = max(0.0, plain)
    detail['plain_flags'] = pf
    # agreement
    ctx = rec.get('ctx') or {}
    ctxt = ' '.join(list(ctx.get('readme') or [])[:12] + list(rec.get('folder_hierarchy') or []) +
                    [ctx.get('repo_title', ''), rec.get('context', '') or ''])
    shared = sorted(_words(syn + ' ' + ach) & _words(ctxt))
    agree = min(2.0, 0.4 * len(shared))
    detail['agree_words'] = shared[:6]
    # brevity
    n = len(syn.split())
    brief = 1.0 if 12 <= n <= 40 else -float(-(-(12 - n if n < 12 else n - 40) // 10))
    if ach.strip() and ach.strip().rstrip('.').lower() != syn.strip().rstrip('.').lower():
        brief += 0.5
    if 1 <= len(title.split()) <= 8:
        brief += 0.5
    if len(title.split()) >= 2 and title.lower() in syn.lower():
        brief -= 0.5
    brief = max(-2.0, brief)
    detail['syn_words'] = n
    parts = {'spec': round(spec, 2), 'cov': round(cov, 2), 'plain': plain, 'agree': round(agree, 2),
             'brief': brief}
    return {'total': round(sum(parts.values()), 2), 'fail': '', 'parts': parts, 'detail': detail}


PART_NAMES = {'spec': 'specificity', 'cov': 'coverage', 'plain': 'plainness', 'agree': 'README agreement',
              'brief': 'brevity'}


def move(sw, sb, eps=0.25):
    """Compare two score dicts -> ('1-0'|'0-1'|'1/2-1/2', reason)."""
    if sw['fail'] and sb['fail']:
        return '1/2-1/2', 'both hard-fail (white: %s; black: %s)' % (sw['fail'], sb['fail'])
    if sw['fail']:
        return '0-1', 'white hard-fails: ' + sw['fail']
    if sb['fail']:
        return '1-0', 'black hard-fails: ' + sb['fail']
    d = sw['total'] - sb['total']
    if abs(d) < eps:
        return '1/2-1/2', 'level on points (%.2f v %.2f)' % (sw['total'], sb['total'])
    win, lose, res = (sw, sb, '1-0') if d > 0 else (sb, sw, '0-1')
    gaps = sorted(((win['parts'][k] - lose['parts'][k], k) for k in win['parts']), reverse=True)
    g, k = gaps[0]
    why = '%s wins on %s (+%.2f)' % ('white' if res == '1-0' else 'black', PART_NAMES[k], g)
    dt = win['detail']
    if k == 'spec' and (dt.get('quoted') or dt.get('terms')):
        why += ': ' + ', '.join(['`%s`' % q for q in dt.get('quoted', [])[:3]] + dt.get('terms', [])[:2])
    elif k == 'cov' and dt.get('covered'):
        why += ': explains ' + ', '.join('`%s`' % c for c in dt['covered'][:3])
    elif k == 'plain' and lose['detail'].get('plain_flags'):
        why += ': loser has ' + ', '.join(lose['detail']['plain_flags'])
    elif k == 'agree' and dt.get('agree_words'):
        why += ': shares ' + ', '.join(dt['agree_words'][:4])
    elif k == 'brief':
        why += ': synopsis %d v %d words' % (dt.get('syn_words', 0), lose['detail'].get('syn_words', 0))
    return res, why + ' (%.2f v %.2f)' % (max(sw['total'], sb['total']), min(sw['total'], sb['total']))